57 Commits
Author SHA1 Message Date
local 93498d13c9 优化断卦规范(59.4k→41.6k 字):删古籍索引/扩展路线、精简六畜、去各专项输出顺序;起卦「指定」与掷钱并列等高;页头加项目链接 2026-11-10 21:24:07 +08:00
woniu336 0801dcac51 fix(prompt): 新增硬规则「六亲名 ≠ 五行生克」,修正官鬼误作克世
问题(实测):火天大有之雷天大壮(戌月己巳日,世三爻父母甲辰土、应上爻官鬼己巳火),
模型写「巳火…克世之土」,同一段又写「巳生辰土」——把六亲名号当成了五行生克,生克写反。

修正:
- §五 新增 5 节「六亲名 ≠ 五行生克(硬规则)」:名号只表示代表什么,生克按两爻真实五行算;
  官鬼=克卦宫者而非克世者;世五行≠宫五行时官鬼可能是生;禁止「官鬼临火克土」类写法;
  官鬼生世时压力象须由其他依据(勾陈迟滞/化空/旬空/月破…)承担
- §六.1 矩阵加注:六亲是名号,不是生克
- §二十 推理层自检加一条(生克是否按真实五行算)

验证:gen:prompt + 85 测试通过;已部署 195828d9;线上复测同一卦例,输出改为
「巳火生辰土,名鬼而实生世,压力象不成立」,全篇无「克世」
2026-11-07 22:31:38 +08:00
woniu336 77b0d75beb feat(settings): DeepSeek 官方预设标注「支持上下文缓存」,模型名改官方 deepseek-chat / deepseek-reasoner
- 40k 前缀在 OpenCode 网关无缓存、易被 prefill 容量拒;官方 API 自动缓存重复前缀
  (命中后输入按缓存价、预填充更快),设置里直接可切换对比
- 设置默认值模型名同步为 deepseek-chat
2026-11-07 19:45:06 +08:00
woniu336 17a1cf0e9a refactor(prompt): 彻底移除关键词正则,system 恒为整份规范(全量 40k token)
- prompt.ts: composeSystem() 直接返回 PROMPT_SPEC,不再按问句选章;删掉 lib/readings/specialties.ts
  (含 pickSpecialtyChapters / QUICK_REF / quickRefBlock)与其测试
- 断卦的章别适用完全交给模型理解;不再有任何正则替模型做判断
- 重试策略按网关提示调整:间隔 5s/20s 起步,并优先采用上游消息里的 "retry after N s"(上限 35s)
- 文档与生成脚本同步:投放说明改为「整份、不删减、不选章」
- 测试:reading-prompt 改为断言 system 恒等于规范全文、九个专项章全部随全量发送;85 通过 + 4 skipped
2026-11-07 19:06:58 +08:00
woniu336 27fa16b1a3 feat(prompt): 新增第十五章「学业、升学与职业资格考试专项」;原十五~二十二顺延为十六~二十三
按批准方案实施:
- 新章 §十五:先辨主体(自占世/父母代占以子孙为主体、世仍为父母)、三轴用神
  (考生主体/父母=学业文书/官鬼=考核资格)、8 类事项 A–H、六步流程、应期、安全边界、
  8 条严禁机械断法、四段内输出要点;含「可建议发挥与录取分开各占一卦」但不强迫
- 子孙双重语义硬规则:主体状态与「克官」分层,克官只作低权重旁证,禁止双向机械断
- 章号顺延:应期通则→十六、证据→十七、输出格式→十八、风格→十九、自检→二十、执行→二十一、
  索引→二十二、日常分类→二十三;正文 20+ 处引用同步(§十六/十七/十八/十九/二十/二十二/二十三)
- §三 新增第 12 类并从「其他日常事项」移出学业;§六.1 矩阵加「学业」列;
  §十八 加 J 输出清单;§二十 自检加 3 条;§二十二 加「学业、升学与考试」索引(含核验结果);
  §二十三 把学业移入已建立专项
- 古籍核验(本次实抓维基文库):增删卜易 学业45/治经46/延师47/求名48/童试49/岁科考50/乡试55/
  功名到何品级66/子占父功名67 章名序号可核;「发案持榜」为文库篇名(坊间作「挂榜」属异文);
  增廪51/考遗才52/廷试54 在文库本未检到→传本待核;《黄金策》「财若交重…福如发动…」可核,
  但「以父为文章,鬼为宫职」未命中→只能作通行注解,不得当原文
- 运行时:章号动态识别(OUTPUT_CHAPTER_ID),composeSystem 按文档顺序拼,顺延不再写死;
  学业关键词路由置顶(高考/中考/考研/考公/法考/职称/志愿/录取/上岸/成绩…),裸「面试」不触发学业
- 测试:新增 prompt-refs.test.ts(章号连续、正文引用都存在、核心章不含专项、A–J 齐全、学业章结构);
  学业路由用例;live-worker 加学业端到端用例
- 全量 96 通过 + 4 skipped;线上实测:高考问句 9.7s 返回四段,取用即分层
  (子孙=子女主体只断状态、考试看父母+官鬼),走势分文书/考核两层
2026-11-07 18:26:12 +08:00
woniu336 f02d6bcd20 fix(prompt): 猫本命统一取寅(戌说降为传本待核、仅备查,不并列取用) 2026-11-07 17:53:38 +08:00
woniu336 4d1ae35749 fix(prompt): 宠物走失不再把「现实提醒」置顶,四段外壳优先
- §八.4.2.8 删掉第 1 项「现实行动提醒」,改为并入「四、应期」段末;
  并注明「不单独设现实提醒置顶」
- §十七 优先级说明改写:专项输出顺序只是内部检查顺序,对外不得在四段前另加前置段;
  唯一例外——人物疾病/六畜出现急症征象时第一句先提醒就医(安全优先于格式)
- 测试补 2 条断言;全量 88 通过 + 3 skipped
- 已部署 58ab666e;线上实测:输出严格从「一、取用」起,现实搜寻并入应期段末
2026-11-07 17:46:23 +08:00
woniu336 34d1e1c103 perf(prompt): 按问句只发「核心章 + 命中专项章」(整章原样,内容不精简)
- scripts/build-prompt-spec.mjs 改为按一级标题拆章 + 把 §十七 再拆成「头部 + A~I 输出清单」,
  生成 SPEC_CHAPTERS / OUTPUT_HEAD / OUTPUT_FORMATS / CORE_CHAPTER_IDS / CHAPTER_FORMAT_MAP
- prompt.ts: composeSystem(question) = 核心章(零…二十,含 §十七 头部与 A)+ 命中的专项章
  (多命中:「面试完顺便问财运」→ §十三 + §十二;无命中只发核心章,不硬套)
- 体积:全量 5.4 万字/36k tok → 核心 1.16 万字/7.9k tok,核心+宠物章 2.25 万字/15.3k tok
  实测 prompt_tokens:7929(核心)/15320(+宠物章),首字 7s/28s(网关波动为主)
- 修规范内部冲突:§十七 加「优先级」说明 —— 专项的输出顺序只是内部检查顺序,
  对外仍以四段段首为外壳(此前宠物走失会把现实提醒顶到最前)
- 测试:reading-prompt.test.ts 重写(章节一致性、多命中、无专项兜底、体积上限)
  全量 87 通过 + 3 skipped;已部署 9e5c72bf
2026-11-07 17:07:51 +08:00
woniu336 9e32a1cac7 fix(read): 上游 429/overloaded 服务端自动重试两次;错误文案改人话
- lib/llm/server.ts 新增 shouldRetryUpstream(429/502/503/504 + overloaded/prefill_cap_refused/
  at capacity/rate limit 判为瞬时)与 friendlyUpstreamError(429→繁忙提示、401/403→key 问题、
  404→地址或模型名、其它保留原文)
- /api/read:上游失败在开始流式输出前重试(间隔 2.5s、6s),仍失败才把友好文案推给前端
- ReadingPanel:错误提示按类型分流,繁忙时提示「已自动重试,稍后点重试即可,不会重复计费」
- 测试 +2(重试判定、错误翻译),全量 85 通过 + 3 skipped;已部署 55409463
- 线上实测:宠物走失问句 200 + 四段正文(43s 内含一次重试)
2026-11-07 16:50:19 +08:00
woniu336 3f4a616b17 feat(prompt): 运行时改为整份规范(原版不精简,36k token),默认关闭思考
- 新增 scripts/build-prompt-spec.mjs:把 docs/prompt-liuyao.md 内联成
  lib/readings/prompt-spec.generated.ts(Workers 无 fs),npm run gen:prompt / check:prompt
- prompt.ts: system = PROMPT_SPEC 整份(不再速查层/路由);user 仍只带盘面事实与问句
- §十七 补四段原文与字数预算,使规范本身即可独立投放(Agent system prompt)
- 关键发现并修复:整份规范 36k token 时,若模型默认开思考,reasoning 会吃光 max_tokens,
  正文为空(finish_reason=length)→ /api/read 默认 thinking: disabled,设置页默认值同步
- 新增 tests/live-specialty.test.ts(默认跳过,LIUYAO_LIVE_KEY 才跑):真实调用验证专项命中
  实测「我家猫跑丢了」→ 子孙为生命主体、猫戌/寅并列、不指认盗窃、先现实搜寻、四段齐全
- 全量 83 通过 + 2 skipped;已部署 af0c6c07
2026-11-07 16:08:46 +08:00
woniu336 476b5d9ffd refactor(prompt): 去掉关键词路由与用户选择,改为常驻「专项速查层」由模型自判
为什么改:
- 关键词对复合问句(面试+财运)与指代模糊必错;让用户选又多一步操作
- 完整规范 141KB≈4.5 万 token 不可能每次发,而输出只有 400–550 字,细则展不开

做法:
- lib/readings/specialties.ts 重写为 QUICK_REF(9 专项 × 2 行:用神 / 忌)+ quickRefBlock(),
  约 0.9k 字常驻,带逃生门「不属于任何专项时按通用规则判断,不要硬套」
- prompt.ts: system = SYSTEM_PROMPT(1930) + quickRefBlock(),不再 detectSpecialty
- 专项名与章号对齐规范(六畜/宠物、工作事业…),测试校验不脱节
- docs/prompt-liuyao.md 投放说明同步(运行时 = 通用 + 速查层,不路由不选择)
- 全量 86 测试通过;已部署 e5e3b802
2026-11-07 15:49:16 +08:00
woniu336 6a9718d3fa feat(prompt): 专项要点真正接入运行时(按问句路由注入),规范文档即 Agent 提示词
- 新增 lib/readings/specialties.ts:9 个专项精编要点(各 300–500 字,标注规范章号)+ 关键词路由
  (宠物走失优先于失物/行人;病、婚恋、行人、失物、工作、求财、家宅各一档)
- prompt.ts:buildLiuyaoPrompt = SYSTEM_PROMPT + specialtyBlock(detectSpecialty(question))
  问「猫跑丢了」只注入宠物走失要点,问「欠款到账」只注入求财要点;无问句不注入
- docs/prompt-liuyao.md 顶部加「投放说明」:整份可直接作 Agent system prompt,含输入/输出契约
- 测试:新增 tests/specialties.test.ts(18 项)—— 路由样例、规范章号漂移校验、注入生效、字数上限
- 全量 97 测试通过;已部署(版本 9d8587ba)
2026-11-07 15:34:03 +08:00
woniu336 8c1ecc0874 feat(prompt): 断卦提示词 v3 —— 按「引擎出事实、AI 只推理」重写(审计修订)
BLOCKER 修复
- 新增 §零 两层职责与事实层硬约束(八条 + 事实包字段清单 + 异常处理)
- §四「输入核对与排盘前检查」→「事实核对(只读)」:删「尝试重排」「发现明确错误可重排」
- §五「排盘规范」→「盘面读法(只读)」:删六神起法表、旬空起法、变卦六亲基准推导
- §十七 各格式「排盘表」→「盘面引用」;§十九 自检清单拆为 事实层 6 条 + 推理层 12 条

MAJOR/MINOR 修复
- §六.1 用神总表扩成「爻类 × 场景」矩阵(疾病/六畜/失物/求财/工作/婚姻/家宅/行人)
- 猫本命地支:戌(易林补遗猫犬同位)与寅(易隐传本)并列,以子孙为主,不得单选
- 「合伙不嫌兄弟」降级为传本待核(去引号、不作硬规则)
- §二十一 索引补「医药」条目 + 四档来源可信度标签(镜像站不得标可核原文)
- §八.4.2.5 方位取象去重指向 §十一.4;三处失踪分流声明合并到 §三
- §十五 补应期边界;§十一.2 补现代物品取用顺序;术语统一(主法/辅助法/现代类比/传本待核)

运行时
- prompt.ts 加「事实层铁律」+ 专项路由(1930 字,仍在 2000 上限内),四段与字数不变
- 测试补 5 条断言(事实层铁律/未提供/宠物/求财)
- 完整规范入库 docs/prompt-liuyao.md(1578 行),README 指向
2026-11-07 15:20:26 +08:00
woniu336 ef98473116 docs: 移除博客草稿(不入库) 2026-11-06 21:58:37 +08:00
woniu336 805e5704dd docs: 新增项目介绍博客草稿(标题候选 + 正文 + 发布建议) 2026-11-06 21:55:03 +08:00
woniu336 321ee7abf7 docs: 删掉 README 技术要点里的「引擎与差分」整段 2026-11-06 21:48:35 +08:00
woniu336 38f3a042ca docs: README 顶部去掉引擎同源说明 2026-11-06 21:46:49 +08:00
woniu336 11804fc017 docs: README 即部署文档(原 docs/deploy.md 并入并补技术要点),删除重复文件 2026-11-06 21:42:52 +08:00
woniu336 0f843f8b7a docs: NEXT.md 去掉本机绝对路径,标注已上线 2026-11-06 15:30:50 +08:00
woniu336 c7c6af6b93 chore: 撤掉安卓 App 相关(android/、workflow、APK、assetlinks);新增部署文档 docs/deploy.md
- 按决定不再做 App:移除 android 工程、.github/workflows/android.yml、public/download/*.apk、
  public/.well-known/assetlinks.json(已同步下线,线上 404)
- docs/deploy.md:从零部署到 Cloudflare 的完整流程 —— 先决条件 / cf auth login / D1 /
  Custom Domain / 运行时变量 / 部署与 dry-run / 验收命令 / 边缘限流(免费套餐限制)/
  更新回滚 / 常见坑(含 @ 文件名 307 循环、triggers.fetch 无 DNS)
- README 顶部指向部署文档
2026-11-06 15:28:05 +08:00
woniu336 3b8f878623 feat(android): APK 挂到自有域名下载;README 补安卓打包说明
- public/download/yehe-liuyao-1.0.0.apk(419KB)→ https://zhanbu.lufei.de/download/…
  GitHub 直链在本地网络不稳定,走自己的域名更稳
- README:TWA 构建方式、secrets 名称、包名/版本、签名密钥保管
2026-11-06 15:11:03 +08:00
woniu336 ce1f98c003 ci(android): 用 runner 预装 SDK 替代 setup-android(后者装已下线的 tools 包会失败) 2026-11-06 15:03:11 +08:00
woniu336 46f7c281eb feat(android): TWA 安卓 App(Chrome 内核跑线上站)+ GitHub Actions 构建
- android/:最小 TWA 工程(androidbrowserhelper 2.5.0,AGP 8.5.2 / compileSdk 34 / minSdk 23)
  启动页用站点图标,包名 de.lufei.zhanbu,默认 URL https://zhanbu.lufei.de/
- public/.well-known/assetlinks.json:Digital Asset Links(包名 + 签名 SHA-256),
  已部署验证 200 application/json
- .github/workflows/android.yml:JDK17 + Android SDK + Gradle 8.7 → assembleRelease → 上传 APK artifact
  签名从 secrets 注入(ANDROID_KEYSTORE_BASE64 / ANDROID_KEYSTORE_PASSWORD / ANDROID_KEY_ALIAS)
2026-11-06 15:01:29 +08:00
woniu336 1dfb5d93c2 fix(assets): 铜钱 2x/3x 图改名去掉 @ —— Workers Assets 会把 @2x 重写成 %402x 并 307 循环
- 线上 /images/coin-4@2x.png → 307 → /images/coin-4%402x.png → 307 → 无限循环,
  手机 DPR 3 命中 @3x 直接裂图(本地 dev 正常,所以一直没暴露)
- 改名 coin-3/4-2x.png、-3x.png,Coin.tsx 的 srcSet 同步
- check:portability 增加守卫:public/ 下任何文件名含 @ 直接报错(附原因)
- 已重新部署,实测 390×844@3x:三枚铜钱均 200、naturalWidth 85、无异常响应
2026-11-06 14:41:59 +08:00
woniu336 bdb933c6cb feat(deploy): 默认开启上游白名单(LLM_ALLOWED_HOSTS 内置常用供应商)
- cloudflare.config.ts 内置默认白名单:opencode.ai / deepseek.com / api.openai.com /
  api.moonshot.cn / open.bigmodel.cn / dashscope.aliyuncs.com / openrouter.ai / api.siliconflow.cn
  可用同名环境变量覆盖;本机 Ollama(localhost)不受影响
- 设置页「自定义网关」提示:服务端只放行白名单内域名,自建网关需先加入白名单
2026-11-06 14:20:12 +08:00
woniu336 5b3201edfb feat(security): 上线前加固 —— 同源校验、分钟+小时双限流、可选上游白名单
- /api/read 与 /api/llm-test:带 Origin 但不是本站的一律 403(挡住第三方拿本站当转发口)
- /api/read 限流加小时窗(8/分、60/时);/api/llm-test 10/分
- 新增 LLM_ALLOWED_HOSTS(逗号分隔域名后缀):设了就只放行列表内上游,不设保持「通用供应商」;
  后缀匹配做了防绕过(deepseek.com.evil.com 不放行)
- 测试:新增上游白名单用例(共 79)
2026-11-06 14:11:51 +08:00
woniu336 8d136ed8fa feat(pwa): 可安装 PWA(manifest + 图标 + service worker 离线排盘);部署支持自有域名
- app/manifest.ts:standalone、暖纸主题色、案例/历史排盘快捷方式
- public/icons:由 app/icon.svg 渲染 192/512/maskable/apple-touch 图标
- public/sw.js:导航 network-first 回落离线壳;静态资源 cache-first + 后台更新;/api 直连不缓存
- ServiceWorkerRegister:仅非本机域名注册(localhost 自动注销,避免 dev 缓存脏 chunk)
- layout:manifest 图标、apple-touch-icon、themeColor、viewportFit=cover
- cloudflare.config.ts:WORKER_DOMAIN / WORKER_ZONE 环境变量 → triggers.fetch 绑定自有域名
- docs/cloudflare.md:补部署命令(cf auth login / d1 create / cf deploy)与 PWA 说明
2026-11-06 14:01:53 +08:00
woniu336 919a22e19a feat(settings): 预置 OpenCode Zen / Go 供应商(https://opencode.ai/zen/go/v1)
- 实测可用模型:deepseek-v4.1-flash(默认)/ deepseek-v4-pro / kimi-k3 / glm-5.3 / qwen3.8-max / claude-haiku-5-5
- 该网关强制要求 x-opencode-session 路由头,lib/readings/provider-headers.ts 已对 *.opencode.ai 自动补
- 设置里选中后自动填 baseUrl 与默认模型
2026-11-06 13:34:23 +08:00
woniu336 c4c961b318 design(nav): 去掉「六爻」入口(首页即六爻);案例/历史排盘导航字号加大
- NAV 只留 案例 / 历史排盘(+ 设置)
- 导航字号 12.5/13.5 → 15/16px,字色略深(#5A564C);360–430px 实测不溢出
2026-11-06 13:29:31 +08:00
woniu336 8ef24eb90c fix: 排出此卦不再先闪旧表单;案例页卦盘窄屏对齐、伏神注记;原文不再截断
- /liuyao 加三态门(boot → restoring / form):静态页首帧只渲染「载入中…」,
  带 ?c=/?case= 进来时不再先闪出旧的起卦表单,直接「排盘中…」→ 盘面
- 案例页:卦盘表头与数据行共用 .ex-grid(CSS 变量化列宽),窄屏收起伏神列时
  不再错位(有伏神时整盘仍在 430px 内对齐),表下补一行「伏神:…(N爻)」注记
- 抽取脚本不再截断原注与 1/2/3 三段(例1 原注此前断在句中),JSON 74KB → 313KB
2026-11-06 13:20:21 +08:00
woniu336 a76036af88 fix(examples): 卦盘改 CSS grid,本卦/变卦表头正压各自列;移除「复制此例」
- 表头与数据行共用同一 gridTemplateColumns,【本 卦】/【变 卦】分别压在
  「爻画 + 纳甲」两列之上(实测 x/宽度完全一致),不再偏移
- 无伏神时不渲染伏神列,窄屏整盘可见
- 去掉「复制此例」按钮(保留「排出此卦 · 看完整盘面」与对应公历说明)
2026-11-06 13:07:15 +08:00
woniu336 38534678a6 design(examples): 去掉配色切换(固定暖纸);一例一个大框,卦盘照书的列次,原注与三段回到连续正文
- 移除冷白配色与切换入口,固定暖纸(#F7F4EF / 朱砂 #C23A2B)
- 每例收进一张卡,行文照书:例N 古筮知识 → 占问得卦 → 干支旬空 → 卦盘 → 原注 → 1/2/3
- 卦盘表头改为「六神 /【本 卦】/【变 卦】」,列宽压到窄屏整盘可见;无伏神时不渲染伏神列
- 原注与三条断语改回连续段落(不再各占一卡),整体高度明显收紧
- 保留:排出此卦 · 看完整盘面 / 复制此例 / 对应公历说明
2026-11-06 13:02:06 +08:00
woniu336 dfe0fd0408 design(examples): 案例页改现代研读档案版式 —— 桌面双栏 + 卦盘居中 + 分层阅读 + 暖纸/冷白双配色
- 桌面端:主内容 + 右侧吸顶侧栏(检索、六冲/六合/游魂/归魂 快筛、页码、读法、配色);移动端侧栏落到列表上方
- 每例一张卡:占问标题 + 例号 / 古筮知识 / 占问时间与得卦 / 卦盘(独立成块,动爻行高亮 + 朱砂世应圆标)
  / 原注按句断段 / 01 选取用神 · 02 吉凶判断 · 03 应期细节 各成一卡(编号 + 标题 + 提示)
  / 朱砂主按钮「排出此卦 · 看完整盘面」+ 描边「复制此例」(可整例复制成文本)
- 配色:暖纸(#F7F4EF + 朱砂)与冷白(#F5F7F8 + 浅青灰 + 古铜),记在本机;冷白时页头切 tone=cool
- 卦盘列宽改 CSS 变量(globals.css .ex-chart):窄屏整盘放得下(含变卦世应),宽屏放宽
- 提高文字对比:正文 #33322E、次要 #6F6A60、分隔 #E1D8C8(不再一片米黄)
2026-11-06 12:44:20 +08:00
woniu336 5fb75bfec5 design(examples): 案例页改成古籍排版 —— 逐例照书排:例N+古筮知识 / 占问 / 干支旬空 / 宫位卦名 / 六爻卦盘 / 原注 / 三段评述
- 卦盘不再照抄乱掉空格的原文,改用同一引擎按「投掷值 + 同月建同日辰公历」重排
  (六神 · 伏神 · 本卦纳甲 · 世应 · 动爻 ×→/○→ · 变卦纳甲 · 变世应)
- 爻画用实心块而非 ▅ 字符,跨字体对齐;窄屏隐藏伏神列并改为表下一行注记
- 每页 6 例 + 页码;检索保留
- 「排出此卦」入口保留在每例末尾
2026-11-06 12:23:56 +08:00
woniu336 d08c661791 feat(examples): 新增案例页(增删卜易 100 例,可一键还原盘面);DeepSeek 默认 deepseek-flash;排盘页去掉重新起卦
- /examples + 导航「案例」:数据由 scripts/extract-zengshan-cases.mjs 抽取到
  public/data/zengshan-cases.json(古筮知识/占问/干支旬空/本卦变卦/原注/用神·吉凶·应期,长段截断)
- 每例「排盘」:卦名反推六次投掷(6/7/8/9),再取同月建同日辰的公历(1990–2026 最早命中),
  新标签页打开 /liuyao?c=…&t=…;缺月建/干支的 3 例不给入口并注明
- 校验:coins 反推二进制与卦名逐例一致(100/100)
- DeepSeek 预设默认模型改 deepseek-flash
- 排盘页顶部移除「重新起卦」(历史排盘 / 截图 / 设置)
2026-11-06 12:11:41 +08:00
woniu336 38f0297ad0 feat!: 下线后台;站名改「野鹤六爻」+ 毛笔艺术字;新增设置(自带大模型)
BREAKING: 移除后台与公告/统计
- 删 app/admin、app/api/admin/*、components/admin/*、lib/admin/*、公告条、统计注入、
  /api/site-config、/api/announcement;D1 迁移只剩 cases(schema 已重生成)
- D1Like / getRuntimeEnv 移到 lib/db/

站名与导航
- 站名「野鹤六爻」,移除篆印;用「马善政毛笔楷书」子集(public/fonts,2.7KB,OFL)
- 导航去掉「古籍」(页面保留 /classics)

设置:只配大模型,通用各种供应商
- components/site/SettingsDialog.tsx + lib/llm/settings.ts:预置 DeepSeek/OpenAI/Moonshot/智谱/
  通义/OpenRouter/SiliconFlow/Ollama/自定义,按 OpenAI 兼容协议
- 配置只存本机 localStorage(liuyao.llm.v1),不上传、不入库;弹窗 portal 到 body(页头有 backdrop-blur)
- /api/read 接受请求体 llm(lib/llm/server.ts:协议/模型名校验 + 拦内网地址,本机 Ollama 放行),
  没配退回服务端 env;新增 /api/llm-test 连通性测试
- ReadingPanel 未配置时提示去「设置」,配置随请求发送

测试:新增 llm-settings 10 项(含 SSRF 用例),移除 admin/site-config 测试(共 78)
2026-11-06 11:46:15 +08:00
woniu336 c3d4c552db design(home): 首页去掉「起 卦」大标题,题签只留「取象于天地,观变于阴阳」并放大
- PC 题签高度 162/182 → 118/136,副标题 15/16 → 18/19/22px,字距 0.24em,色改赭金 #8E6337
- 移动端题签本就隐藏,不受影响
2026-11-06 11:32:46 +08:00
woniu336 4ad039c135 fix(result): 问事只在盘面出现一次;去掉解卦页脚说明
- 页首时间下的「问事」移除(盘面卦单里已有落款),解卦按钮不再被挤出首屏
- 解卦面板移除「只发送上列盘面事实 · 密钥不出服务端」页脚说明
2026-11-06 11:12:57 +08:00
woniu336 75d7ff770c feat(ui): PC 排盘改左右两栏(盘面吸顶 + 解卦纸);移动端首页去大标题
- PC:左栏卦名 + 盘面(卡片仍 440,爻盘 390 基准不变)+ 盘面下方解卦按钮(不再悬浮);
  右栏一张解卦纸,未解时居中提示,读完全文落纸;移动端保持单列 + 底部悬浮条
- 解卦正文 PC 字号 15.5 / 行高 2.15,移动端不变
- 移动端首页:sm 以下隐藏山水题签与「起 卦」大标题,纸笺上移,首屏基本放得下整张求测笺
- 删「跟随此刻 / 归位当前」标签(默认当前时刻,改时间用「修改」)
2026-11-05 23:59:43 +08:00
woniu336 f45cb19d89 fix(ui): 修 PC 截图错位;首页去婚否/随机源核查;手动指定下移;时间改「修改」
- 截图:html-to-image 克隆时 mx-auto 会按外层容器重新居中,宽屏下整块右移被裁;
  改为固定 width/height + style{margin:0,transform:none},PC 导出与屏幕一致
- 首页:移除婚否切换与「随机源核查」;手动指定移到「重新起卦」下方居中
- 起卦时间:隐藏原生选择器图标,改中文「修改」按钮唤起 showPicker(.no-native-picker)
2026-11-05 23:32:53 +08:00
woniu336 3a1b5cc291 feat!: 下线小成图;移动端起卦悬浮;解卦研墨中与自动滚动
BREAKING: 移除小成图全部 UI 与功能
- 删 app/xct、components/xct/*、lib/xct/*、prompt-xct、docs/xct-prompt-spec、xct 测试
- readings 的 xct 事实类型、cases 的 xct 记录/校验、store 的 xct 读写一并清理
- 历史排盘只列 kind=liuyao(旧 xct 记录留在库里但不显示)
- 导航改「六爻 / 古籍 / 历史排盘」;卦成弹窗只留「排盘解卦」

六爻体验
- 移动端:掷钱起爻改为底部悬浮条(safe-bottom),行内按钮 sm 以上才显示
- 解卦:起解即滚到解卦段;等待态改墨滴涟漪「研墨中」动画(尊重 reduced-motion)
- 修动爻位提示错一位:新增 movingLineNumbers(1-based) 并补测试
- 修 hydration 报错:复原占位改由 useIsoLayoutEffect 置位,不在 render 读 window
2026-11-05 23:08:22 +08:00
woniu336 04bbaa813d feat(ui): 小成图改版去吉凶;六爻结果页去用神标注;首页与重起流程微调
- 小成图:表单/结果页统一宣纸+松墨绿+淡金,结果页重排(卦名 ⇌ 天时 太极 卦象纸 九宫 折叠)
- 小成图去吉凶:删 VerdictCard 与 verdict-mark,九宫只列四象式,盘面详录与提要移除八断/得配失配
- 六爻结果页:移除用神标注与高亮;解卦入口回面板;底部常显 重新起卦 / 切换到小成图排盘
- 重新起卦改为回首页起卦台(router.replace('/')),修掉「点了像回到旧缓存页」
- 首页:删一键起卦,手动指定移到卦象台右侧,掷钱起爻收窄+小圆角,右上加历史排盘,
  题签上移、副标题放大、PC 内容宽 960
- 清理 LiuyaoView 死代码(handleCopy/HexagramBoard 等)
2026-11-05 22:13:56 +08:00
woniu336 5fed4706d9 feat(ui): 易林寻踪站名与导航统一;静卦不出小成图;六爻结果页按设计稿重做
- 新增 components/site/SiteHeader.tsx(篆印 + 易林寻踪 + 六爻/小成图/古籍),首页/历史排盘/古籍接入
- 起卦弹窗居中;静卦只给六爻解卦,主按钮改墨绿渐变
- 六爻结果页:本卦 ⇌ 变卦、公历干支、太极分隔、淡金边盘面纸、用神/伏神行
- 解卦四段改「圆标序号 + 标题 + 发丝线」;底部只留 重新起卦 / 切换到小成图排盘
- 移除保存与再解一次:解卦完成即静默归档进历史排盘;保留所呈事实抽屉
- 用神解析:认「以财爻为用」类取用句与单字简称;地支唯一才补;有地支只认精确匹配
- /cases 更名历史排盘;新增 3 项 use-god 测试(共 113)
2026-11-05 21:38:29 +08:00
woniu336 1821fa61ae docs: 新增 NEXT.md 交接文档,README 指向 2026-11-05 20:59:08 +08:00
woniu336 703fee4160 design(home): 依新设计图重做首页并收紧标题留白 2026-11-05 19:34:49 +08:00
woniu336 6755e071d7 fix(cast): 起卦页恢复原版表单与起卦台;修正爻值 8 的铜钱朝向
设计回退(用户反馈:太丑,不如原项目)
- 首页恢复成原项目 /qigua 的结构:求测事项输入 + 性别 + 婚否 + 起卦时间全部明面可见,
  下面接原版三钱起卦台(大铜钱、进度胶囊、逐爻判决、卦象生成台)
- 删掉此前自制的极简版与折叠「补充」;随机自证不再占首页
- 起卦台卡片改用设计令牌(paper-0 / line / ink),主按钮由赭金改墨色

铜钱修正
- 起卦台原本用 CSS 圆 + 文字(依赖未迁移的样式表),改为真铜钱照片 Coin 组件
- 尺寸回到原项目 74px(≥640 为 84px),源图 85×85 不再放大,避免发虚
- 三枚静置给 -9°/6°/-4° 轻微倾斜,落地阴影加强

爻值换算修正(用户指出 8 应为两背一字)
- coinFacesOf(8):[2,2,3] → [3,3,2](2+2+3=7 才是少阳)
- coinSidesOf(8) 同步为 背背字,两个方向自洽
- 新增 tests/coin-math.test.ts:双向换算、和值=爻值、背枚数=爻值−6
- 浏览器实测四种点数:6 字字字 / 7 背字字 / 8 背背字 / 9 背背背,全部 ✓

测试 110 项通过;构建通过。
2026-11-05 18:41:21 +08:00
woniu336 29090298df feat(cast): S1 起卦页 —— 单动作摇卦、手动指定、卦成双入口
首页(app/page.tsx → components/cast/CastPage.tsx)
- 一屏一动作:铜钱(真图)+ 进度点 + 唯一主按钮;手动指定为次级描边按钮
- 补充项(所问/性别/婚否/时间)收折叠;随机自检收进 ⓘ details,不占首屏
- 修复 hydration:起卦时间与自检统计只在客户端确定,SSR 不渲染差异文本
- 六爻已齐弹窗:卦名 + 动爻(朱砂)+ 两入口(六爻标「推荐」),顶部可重新起卦

手动指定(components/cast/GuaPicker.tsx)
- 八宫以宫主卦为入口(底色带 + 卦画 + 宫名),再选本宫八卦(卦画 + 全名,热区 ≥56px)
- 变卦默认折叠(多数为静卦),动爻由两卦逐爻比对自动得出,静卦提示走宜变法

同一卦两看
- lib/liuyao/cast-url.ts:c/t/g/m/q 编码,非法参数返回 null 不猜;截图校验 4 项
- /liuyao 接受 ?c=… 直接重排;页顶「小成图」一键互跳
- /xct 接受同一串参数,用 structureFromCoins 立盘(静卦自动走宜变法立之卦)

设计对齐(按三轮视觉评审收敛)
- 宫组加底色带与「选宫/选卦」分组标题;卦格字号与热区调整
- 弹窗副标题外移、动爻改朱砂、推荐角标保留、说明压到一行
- PC 右栏收窄、文案精简,两列顶部对齐

验证:390/1440 全流程(起卦→弹窗→六爻→切小成图)通过,0 overflow、0 console error;
测试 100 项通过;next/vinext build 与 check 通过。
2026-11-05 17:37:58 +08:00
woniu336 0bb0b78c6d feat(cast): 加密级起卦随机 + 真实铜钱 3D 翻转 + PC 双栏布局
随机(lib/liuyao/random.ts)
- 逐位取 Uint32 最低有效位,字/背各半且无模偏差;小成图报数用拒绝采样
- 缺 Web Crypto 时 fail-closed,绝不回落 Math.random
- CastWorkbench 单掷/连摇、小成图一键报数全部改用该模块(原 Math.random 已清除)
- tossStats() 供界面自证:/design 实时显示字背占比与爻值偏差
- tests/random.test.ts:来源 spy、卡方分布、源码内禁止 Math.random 三条护栏
- 独立核查 50 万掷:字 50.033%,卡方 0.664/3.284(df=1/3,均低于临界值)

铜钱(components/liuyao/Coin.tsx)
- 改用 public/images/coin-4.png(字)/coin-3.png(背)真实照片
- 3D rotateY 真翻转:背面预置 180°,落地由结果决定;animationend 后才定格
- 加静态薄环 + 落地阴影:转到 90° 时仍有边缘可见,三枚始终可数

布局
- /design 改为移动单栏 + lg 双栏(左起卦与盘面 520px,右九宫与解卦自适应),1440 实测无溢出
- /design 拆成 server 包装页 + DesignPreview 客户端组件(metadata 合法、加 noindex)
- 雾蓝皮肤为默认;宣纸米皮肤保留为可切换备选

测试 88 项通过;check、next build、vinext build 均通过。
2026-11-05 17:12:18 +08:00
woniu336 1db44514d7 design(s0): 设计系统 v2 + /design 设计稿(雾蓝/宣纸米双皮肤)
令牌(app/globals.css):
- 雾蓝体系:页底 paper-1 #EEF2F3、纸面 paper-0 #FBFBF7、发丝线 #D3DBDE
- 墨 ink-900 #1F2A30、雾蓝主色 mist-600 #6E8F9C、赭金 #8A6A3A、朱砂 #A8453C
- 字体:正文系统无衬线;卦名/区块标题/解卦正文用宋;楷体只作签注
- [data-skin='paper']:宣纸米备选皮肤(覆盖 --color-* 变量即可整体换肤)
- 移动端基础:安全区、禁 tap 高亮、44px 触控、发丝线工具类

组件(components/ui):
- Button(墨/描边/文字/危险;圆角 2px,主按钮带纸边压印)
- Panel(留白 + 标题,不用描边卡片)、Paper(唯一容器)
- Tabs(下划线式,替代 iOS 胶囊分段)
- Tag(去胶囊,符号 + 字色)、ProgressDots(细环,非信号格)、YaoBar(去圆角)
- AppBar / BottomBar

/design 设计稿:起卦页近似稿(单主按钮、补充项折叠)+ 盘面(去表格线)+ 九宫(无框、
赭金短线选中)+ 解卦(宋体正文)+ 控件/色板/字号对照

采纳的两轮视觉评审意见:主色不做大面积填充、去卡片套卡片、去胶囊标签、去网格线、
首屏只留一个黑按钮、世应分色、逐条修掉报表感/电商感。
390 宽无横向溢出、0 console error;check 与 next/vinext build 通过。
2026-11-05 16:14:12 +08:00
woniu336 abc2cc07a0 feat(xct): 小成图解卦 prompt 落地 —— 用宫取用、宜变立静卦、坤宫生育判据
口径(docs/xct-prompt-spec.md v0.2,已确认):
- 取「用宫」不看爻位;主用一宫 + 兼看并列,只对主用宫做完整推演
- 正推链不预计算:给九宫天盘 + 卦→本宫 + 收敛规则,由解卦者自行推演
- 生育:不论求测者性别一律看坤二宫天盘卦;卦象法(乾坎巽兑男/坤离震艮女)
  与中爻法(第二爻阳男阴女)并列,不一致则并列呈现不强行定一
- 本版禁用:用宫空亡、归藏九星、卦气旺弱(资料只有用法无定义,原著 PDF 无文本层)

引擎小件:
- lib/xct/yong-gong.ts:八宫事类表、婚姻四路(已婚男坤/女乾;未婚男寻巽→兑、女寻震→艮)、
  生育、父母、官运、牢狱、固定单宫项
- lib/xct/yi-bian.ts:高亨宜变法(55−Σ 之字折返);静卦翻一爻立之卦,多动仍以动爻定之卦
- facts 增补:gender/marital/castFrom/rising/guaToPalace/heavenSeen/heavenMissing/heavenDuplicate/yiBian
- prompt 拆分:六爻 buildLiuyaoPrompt 与小成图 buildXctPrompt 分文件,route 按 kind 分发

实测(opencode deepseek-v4.1-flash thinking=high,女·已婚·问丈夫升职):
模型自行正推 乾6→艮8→坎1 并判「阻在艮、滞在坎」,未使用五行六亲与禁用概念;
字数 569、耗时 8s。测试 82 项通过;next/vinext build 与 check 通过。
2026-11-05 15:57:23 +08:00
woniu336 d0396239c1 docs(xct): 小成图解卦 prompt 口径草案 v0.1(待审)
- 划清与六爻的边界:小成图取「用宫」不看爻位,且绝弃五行生克,两套解读必须分开写
- 列出代码必须先给的确定性事实:九宫天地盘、四象八断、中宫归藏、
  卦→本宫对照(供模型自行正推)、天盘缺席/重复卦、静卦宜变爻
- 系统提示词草案:定宫→四象→推演(正推/旁推/反推)→应期,四段 400–550 字
- 八宫取用表与婚姻/子女/父母/考学/官运/牢狱/财/失物专项要领(均标资料出处)
- 明确本版禁用:空亡、归藏九星、卦气旺弱(资料只有用法没有定义,原著 PDF 无文本层)
- 列 6 个待定口径:空亡定义、卦气旺弱、归藏对应、婚否输入、用宫多义、正推起点
2026-11-05 15:40:48 +08:00
woniu336 5f57d6b3ba feat(llm): 切到 opencode 网关 deepseek-v4.1-flash;prompt 定稿字数与病占专项
opencode 网关:
- base https://opencode.ai/zen/go/v1,模型 deepseek-v4.1-flash(模型列表已核对)
- 流式请求必须带 x-opencode-session,缺失直接 400 MissingSessionID;
  新增 lib/readings/provider-headers.ts 按主机名附加(不影响官方 API),会话 id 稳定可配
- .llm.local 改为 opencode 配置(gitignore,不进仓库/D1);后台 profile 同步切换

prompt 定稿:
- 字数收紧到 400–550、硬上限 600,并给出四段预算(100/180/150/80)
- 四行标题必须单独成行,解决模型把「一、取用」写进句子导致 UI 认不出
- 恢复病占专项(墓绝受冲/白虎临用/鬼旺克用/近病久病/子孙制鬼等),
  限定仅病症类占问启用,医疗建议置于结论后
- 提示词不再要求 Markdown,输出中已无 ** 标记

/api/read:加 SSE 注释心跳(8s),避免思考模式首字慢时中间层断流导致正文腰斩

实测(thinking=high):正文 520/572/522 字,耗时 45–69s(原 72–78s),四段标题 3/3 全齐;
病占代占案例 541 字、58s,专项条款明显生效。
测试 70 项通过;next/vinext build 与 check 通过。
2026-11-05 15:02:23 +08:00
woniu336 141ed9f4a8 feat(llm): DeepSeek Flash + 思考模式;本地密钥加载器
- llm_profiles 增加 thinking / reasoning_effort(migrations/0002),
  ensureD1Schema 容忍 ALTER 重复列,已有库平滑升级
- /api/read 按 profile 组装 thinking / reasoning_effort;只转发 delta.content,
  思考链 reasoning_content 不下发;max_tokens 4096
- 后台 LLM 表单新增「思考模式」「思考强度」,列表显示当前设置;测试连通沿用同一配置
- scripts/load-secrets.mjs:启动前读取 .llm.local(gitignore),
  dev / dev:bg / dev:vinext / build:vinext / start:vinext 共用
- 解卦面板显示「研墨中 · Ns」,思考模式首字慢时有提示
- 新增 llm-request 纯函数与 4 项测试;总 68 项测试通过

本地实测:DeepSeek Flash + thinking=high,/api/read 约 23s、840 字、四段齐全;
UI 4 标题/5 段、0 错误。密钥仅存于 .llm.local(不进仓库/D1)。
2026-11-05 14:36:38 +08:00
woniu336 60df211c6a feat(reading): 禅意解卦 UI + 精简 prompt(不重排盘,事实只读)
Prompt(app/api/read/prompt.ts,系统提示 5KB → 1,040 字符):
- 移除:排盘规范/六神起法/旬空起法/输入核对、病占专项、13 段报告与自检清单、复盘条款、
  重复的取象权重与缺日干假设
- 保留:取用/月日/动变/世应/六神神煞/辞象合参、不断死与不断人价值、应期区间+条件、
  医疗法律财务安全
- 新增:明确「不重排盘、不改写干支六亲世应旬空动变、不补神煞与爻辞」;输出四段 500–800 字

事实层:
- 十三神煞改为与盘面同源(calcGuShiShenSha),避免模型自行补写
- 新增 lib/hexagram/oracle-text.ts(64 卦仅卦辞+爻辞,剥离翻译/象征注文)
  事实带本卦/变卦卦辞、动爻爻辞,六爻全动带用九/用六

UI(components/liuyao/ReadingPanel.tsx):
- 默认只留「解 卦」入口;流式落下,窄栏宽行距,短行识别为小标题
- 竖排「观象」小标、朱砂光标、研墨三点;停止/再解一次/复制/所呈事实
- 换卦自动重置;仅贴底时自动跟随滚动;桌面与 390px 均无溢出

验证:mock 上游端到端(四段标题、事实抽屉含经文与神煞、无密钥泄漏);64 项测试通过;
next/vinext build 与 check 通过。
2026-11-05 14:12:54 +08:00
woniu336 38e0dfe103 feat(cases): 卦例上云 —— 匿名设备归属 + D1 存储 + 本地一次性迁移
- ly_device:首次访问下发 HttpOnly UUID Cookie(1 年),服务端作为 owner_id 隔离
- D1CaseStore:按 owner 查询/写入/收藏/删除,每 owner 保留最近 200 条(写入时裁剪)
- getServerCaseStore:有 DB 绑定走 D1,next dev 走内存;客户端探活决定远端/本地
- RemoteCaseStore:/api/cases 的客户端实现;接口不可用自动回退 localStorage
- 一次性迁移:切到远端时把旧 localStorage 卦例批量导入(幂等,失败下次重试)
- /api/cases:probe/list/get/save/import/favorite/delete;parseCaseRecord fail-closed 校验、
  512KB 体限、写入限流、同源校验;设备 Cookie 由服务端签发
- schema 生成物与 ensureD1Schema 移到 lib/db(admin 与 cases 共用)
- /cases 提示区分「云端(匿名设备)」与「本机浏览器」

验证(workerd + D1):保存/列表/打开/收藏/删除、新上下文 owner 隔离、旧本地卦例自动迁移;
58 项测试通过;next/vinext build 与 check 通过。
2026-11-05 13:54:30 +08:00
woniu336 1959d112aa feat(site): 前台公告条与统计脚本注入(M3 第一部分)
- GET /api/site-config:公开配置(公告仅在生效时返回 + 统计公开字段),60s 缓存,失败静默
- lib/site/site-config.ts:publicSiteConfig / analyticsScript 纯函数(白名单 provider + https 校验)
- AnnouncementBar:全站顶部条(info/warn/danger),按 updatedAt 记忆关闭,后台更新后重现
- AnalyticsInjector:运行时注入 <script>(data-liuyao-analytics 防重复),不做任意 JS
- layout 挂载;新增 9 项站点配置测试

验证(workerd + 本地 D1):公告显示/关闭/更新重现;Cloudflare 统计注入与关闭;
0 console error;48 测试通过;next build / vinext build / check 通过。
2026-11-05 13:42:30 +08:00
woniu336 4f50b7668e feat(admin): M1 后台地基 —— D1 存储、口令鉴权、公告/LLM 切换/统计配置/审计
数据层:
- migrations/0001_init.sql(单一事实源)+ 生成器 gen-admin-schema
  → lib/admin/store/schema.generated.ts(Workers 内联建表),check:schema 校验一致性
- settings / llm_profiles / cases / admin_audit 四表
- AdminStore 接口 + D1 实现 + 内存实现(next dev 无绑定时使用,界面明示)
- 惰性 ensureSchema:本地 D1 与首次部署免手工迁移

鉴权:
- ADMIN_PASSWORD + ADMIN_SESSION_SECRET,WebCrypto HMAC 签名 Cookie(7 天,HttpOnly/SameSite)
- 常量时间口令比较、登录限流(5/5min)、写操作同源校验、写操作全部审计
- 开发默认口令 dev-admin 仅限本机 hostname + 非 production;线上缺 env 一律 503

接口:
- 公开 GET /api/announcement(60s 缓存,失败静默)
- 受保护 /api/admin/{session,login,logout,state,announcement,analytics,llm,audit}
- /api/read 改为优先使用后台选定的 LLM profile(密钥只从 keyEnv 读),未配置时精确报缺哪个 env

后台 UI(/admin):
- 登录 → 公告(启停/级别/正文/起止时间/预览)→ LLM profiles(增删改/设为当前/测试连通)
  → 统计配置(结构化 provider/token/siteId,不接受任意 JS)→ 审计
- 顶部标明 D1 / 内存模式与开发口令状态;移动端可用

其他:
- vite.config 放行本机局域网 IP(手机可访问 dev)
- tsconfig 排除 .next,避免 next build 与 vinext build 生成的类型互相覆盖

验证:39 项测试通过;workerd + 本地 D1 端到端(登录/公告/LLM 切换/SSE/审计/退出 401/跨源 403);
next build 与 vinext build 均通过;check:schema / check:portability 通过。
2026-11-05 13:29:55 +08:00
119 changed files with 12738 additions and 2955 deletions
+4
View File
@@ -16,3 +16,7 @@ __pycache__
.cloudflare/
.dev.vars
.llm.local
+129
View File
@@ -0,0 +1,129 @@
# 交接:继续开发(当前进程)
> 新开窗口后先 `@NEXT.md` 引入本文件,再开工。
## 先读
- `AGENTS.md`(若有)与 `README.md`
- 上一提交:`1821fa6 docs: 新增 NEXT.md 交接文档,README 指向`
- 工作树应为干净;dev 服务在 <http://localhost:3001>(vinext/workerd + 本地 D1)
## 已完成(不要重做)
- **六爻纳甲引擎** `lib/liuyao/najia.ts`:与 bazi-web 原 Python `core.py` 4696 案 SHA-256 差分全一致。
- **随机源** `lib/liuyao/random.ts`:逐位取 Uint32 LSB,Web Crypto 实现,缺 crypto 即 fail-closed;
50 万掷实测 6:0.1255 / 7:0.3746 / 8:0.3753 / 9:0.1246。
- **首页** `components/cast/CastPage.tsx` 已按设计图重做:淡墨山水 `InkLandscape` + 宣纸求测笺;
页首只留「取象于天地,观变于阴阳」,标题 34/40/44px,hero 168/188/214px,内容宽 `max-w-[1040px]`。
- **六十四卦可输入下拉** `components/cast/GuaCombobox.tsx` + `lib/liuyao/hexagram-index.ts`(旧 `GuaPicker` 已删)。
- **结果页** `components/liuyao/LiuyaoResult.tsx` 单列居中 + 右上「截图确定性排盘」(`html-to-image` toPng pixelRatio 3)。
- `/classics` 与 `/about` 已建(classics 是分类 / 来源校核空态)。
- **站名与导航**:站名 **野鹤六爻**(毛笔艺术字,见下),共享页头 `components/site/SiteHeader.tsx`
(左站名,右 **六爻 / 历史排盘** + 「设置」;古籍已从导航移除,页面仍在 `/classics`)。
- **站名艺术字**:`public/fonts/yehe-brand.woff2` 是「马善政毛笔楷书」按 4 个字(野鹤六爻)做的子集
(2.7KB,OFL-1.1,`public/fonts/OFL-MaShanZheng.txt`),`app/globals.css` 里 `.font-brand` 使用,
回退栈 STXingkai / 华文行楷 / KaiTi。改站名要重新子集,否则回退字体。
- **起卦弹窗**:卦成弹窗与手动指定弹窗都居中(不再是底部抽屉),卦成后只有一个「排盘解卦」。
- **六爻结果页按设计稿重做**(`components/liuyao/LiuyaoResult.tsx`):
卦名 `本卦 ⇌ 变卦` + 公历干支 + 太极分隔 + 淡金边盘面纸 + 「用神 / 伏神」行;
解卦四段用「圆标序号 + 标题 + 发丝线」。
顶部工具条:历史排盘 / 重新起卦 / 截图;**底部固定栏只承载当前动作**(解卦 → 停止),读完自动收起。
「保存」按钮已删:**解卦完成即静默归档**进历史排盘(`onSave` 在 phase=done 时调一次)。
「再解一次」已删(面板只留 停止 / 重试 / 复制 / 所呈事实抽屉——抽屉是给模型的事实包,必须保留)。
- **用神解析**(`lib/liuyao/use-god.ts`):认「以财爻为用」类取用句(含单字简称);地支只在全文该六亲唯一出现时补齐;
**给了地支就只认精确匹配**,不再回退到「六亲唯一」去猜。注意:盘面上**已不显示用神标注**(用户要求),
lib 与测试保留,将来若恢复高亮可直接接 `HexagramBoard` 的 `highlightPosition`。
- **六爻结果页第二轮**:去掉用神标注;底部只放当前动作(解卦 / 停止);
「重新起卦」直接回首页起卦台(`router.replace('/')`,不再回到旧版 `/liuyao` 表单)。
- **首页第二轮**:删「一键起卦」;「手动指定」移到铜钱下方进度圆点行的右侧;
掷钱起爻按钮收窄到 `max-w-[300px]`、圆角 6px;右上加「历史排盘」;
题签上移(146/162/182px)、副标题 14/15/16px、PC 内容宽 `max-w-[960px]`。
- **案例页**(`/examples`,导航「案例」):`public/data/zengshan-cases.json`(100 例,74KB,静态资源按需 fetch),
生成脚本 `scripts/extract-zengshan-cases.mjs`(源:`bazi-web/artifacts/refs/增删卜易卦例初探230例.txt`)。
**版式**(第三版,现代研读档案):桌面端「主内容 + 右侧吸顶侧栏」(检索 / 快筛胶囊 / 页码 / 读法 / 配色切换),
移动端侧栏落到列表上方;每例一张卡:占问标题 + 例号 / 古筮知识 / 占问时间与得卦 / 卦盘(独立成块,视觉中心)
/ 原注(按句断段)/ 01 选取用神 · 02 吉凶判断 · 03 应期细节 三张卡 / 操作(朱砂主按钮「排出此卦 · 看完整盘面」+ 描边「复制此例」)。
**两套配色**:暖纸(默认,`#F7F4EF` 底 + 朱砂 `#C23A2B`)与冷白(`#F5F7F8` 底 + 浅青灰面 + 古铜 `#8A5A2B`),
选择存本机 `liuyao.examples.palette`;冷白时页头也切 `tone="cool"`。每页 6 例。
卦盘不是照抄原文(原文空格已乱),而是用同一引擎按「投掷值 + 同月建同日辰的公历」重排,与点「排出此卦」看到的盘面一致。
投掷值由卦名反推;公历取 1990–2026 内最早命中(古例不记年)。3 例原缺月建/干支,不给卦盘与排盘入口。
- **设置默认模型**:DeepSeek 默认 `deepseek-flash`(下拉里还有 chat / reasoner)。
- **排盘页顶部去掉「重新起卦」**:只留 历史排盘 / 截图 / 设置。
- **后台已移除 + 设置(大模型)**:
- 删 `app/admin`、`app/api/admin/*`、`components/admin/*`、`lib/admin/*`、公告条、统计注入、
`/api/site-config`、`/api/announcement`;D1 迁移只剩 `cases`(`migrations/0001_init.sql`)。
`D1Like` / `getRuntimeEnv` 移到 `lib/db/`。
- 新增 `components/site/SettingsDialog.tsx` + `lib/llm/settings.ts`:右上角「设置」只做一件事 ——
配大模型。预置 DeepSeek / OpenAI / Moonshot / 智谱 / 通义 / OpenRouter / SiliconFlow / Ollama / 自定义,
按「OpenAI 兼容」通用;**只存本机 localStorage**(`liuyao.llm.v1`),不上传、不入库。
- `/api/read` 改为接受请求体里的 `llm`(`lib/llm/server.ts` 校验:协议、模型名、**拦内网地址**、
本机 Ollama 放行),没配时退回服务端 env;新增 `/api/llm-test` 做连通性测试。
- 弹窗必须 portal 到 body:页头有 `backdrop-blur`,会成为 fixed 后代的包含块。
- **小成图整体下线(用户决定,不可回退)**:删 `app/xct`、`components/xct/*`、`lib/xct/*`、
`app/api/read/prompt-xct.ts`、`docs/xct-prompt-spec.md`、`tests/xct-*.test.ts`;
`readings` 的 xct 事实类型、`cases` 的 xct 记录类型与校验分支、`store` 的 xct 读写分支一并清理;
历史排盘只列 `kind=liuyao`(旧 xct 记录留在库里但不再显示)。
- `/cases` 更名「历史排盘」(UI 文案 + metadata)。
- 全局 `<footer>` 已从 `app/layout.tsx` 删除。
- **移动端悬浮起卦**:首页 `sm` 以下把「掷钱起爻」做成底部固定条(`safe-bottom`),行内按钮 `hidden sm:block`。
- **首页第三轮**:删「婚否」与「随机源核查」;「手动指定」移到「重新起卦」下方居中;
起卦时间的原生选择器图标隐藏,改成中文「修改」按钮(`input.showPicker()`,`app/globals.css` 的 `.no-native-picker`)。
- **PC 排盘页两栏**(用户定稿):`lg:grid-cols-[440px_1fr]`,左栏卦名 + 盘面(吸顶,卡片仍 440 不变)
+ 盘面下方的解卦按钮;右栏是一张解卦纸(idle 时居中提示,读完全文落纸)。
移动端仍单列中轴 + 底部悬浮动作条。
- **移动端首页首屏**:`sm` 以下不显示山水题签与「起 卦」大标题(纸笺上移),
并删掉「跟随此刻 / 归位当前」标签(默认即当前时刻,改时间用「修改」)。
- **截图错位修复**:`html-to-image` 克隆节点时 `mx-auto` 会按外层容器重新居中,宽屏下(卡片 440 < 容器)整块右移被裁。
现在 `toPng` 传 `width/height` + `style:{ margin:'0', transform:'none' }`,PC 导出与屏幕一致。
- **解卦体验**:起解即 `scrollIntoView` 到解卦段(`scroll-mt-20` 避开吸顶条),等待态换成「研墨中」墨滴动画
(`.ink-ripple` / `.ink-drop`,见 `app/globals.css`,尊重 `prefers-reduced-motion`)。
- **动爻位提示修正**:`movingPositions` 是 0-based,页面文案错一位;新增 `movingLineNumbers`(1-based)并补测试。
- **hydration 修复**:结果页/复原占位不能在 render 里读 `window`,改为 `useIsoLayoutEffect` 置位。
- `npm run check` = check:schema + check:portability + 78 项测试,全绿;`next build` 与 `build:vinext` 均通过。
## 硬约束(违反即返工)
- 随机必须 `crypto.getRandomValues`,禁止 `Math.random`;三钱概率严格 **6:1/8 · 7:3/8 · 8:3/8 · 9:1/8**。
- 字面 = 2、背面 = 3;**8 少阴 = 背背字**。
- 铜钱用 `public/images/coin-4.png`(字)/ `coin-3.png`(背),CSS 尺寸 74px(≥640 为 84px),
不得放大(会发虚);已有 `@2x` / `@3x`。
- 六爻盘面版式必须与原项目 `MobileHexagramPoster` 等价;盘面只呈现确定性排盘,不标用神、不印吉凶。
- 解卦 prompt:400–550 字,硬上限 600;四段 = 取用 / 盘面 / 走势 / 应期。
- 大模型 key **只存用户本机 localStorage**,随请求体转发一次,不落库、不写日志、不回显;
自建部署的 env 兜底 key 只放 `.llm.local`(已 gitignore),不进仓库、不进 D1。
- 不得修改 `bazi-web` 源码(只允许读取 / 复制)。
- 已部署到 Cloudflare Workers:<https://zhanbu.lufei.de>(部署步骤已写进 `README.md`);`npm run check:portability` 必须保持通过。
## 命令
```bash
npm run dev:vinext # 3001,带 D1 绑定(改完后端/接口用这个验证)
npm run dev:bg # 后台 + logs/dev.out.log
npm run check # schema + portability + 78 测试
npm run build && npm run build:vinext
```
重启 3001:kill 占用端口的 PID 后 `rm -f .vinext/dev/lock.json`。
UI 实测脚本写在 `bazi-web/scratch/*.mjs`(那里才有 `playwright-core`),
浏览器 `C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`,加 `--no-proxy-server`;
时间输入框约 1s 后才自动填入,等待 ≥1500ms 再断言。
## 下一步(按序)
> 已上线,线上问题优先修:手机端体验、案例页内容扩充、古籍原文校核。
1. **S2 盘面收尾**:字号线宽 / 神煞字号(看板 12.5 vs 12)统一 —— 版式不可动,只能微调字重。
2. **`/classics` 填入经校核的周易原文**(来源与版本必须标注,未核校就保持空态)。
3. **部署准备**:Node ≥26.12、`cf auth login`、secret 注入实测(仍不要真部署)。
4. **小成图如果要做回来**:代码在 `git show 04bbaa8:lib/xct/...` 可取回(引擎与 prompt 都在那个提交里)。
## 已知问题
- 铜钱源图仅 85×85,即使 `@3x` + Lanczos + UnsharpMask 仍略虚;若用户再提,需换更高分辨率原图。
- `components/design/DesignPreview.tsx`(`/design` 页)仍是旧版设计稿内容,未随新视觉重做。
- `build:vinext` 有非致命警告:`vite.config.ts:4` 的 `import "./lib/dev/dev-origins"` 缺扩展名。
## 收工纪律
每次改完必须跑 `npm run check` + 两个 build,报错就别提交。
+270 -87
View File
@@ -1,111 +1,294 @@
# liuyao · 六爻 / 小成图 确定性排盘
# 野鹤六爻 · 六爻确定性排盘
从 [bazi-web](https://github.com/woniu336/bazi-web) 抽出并裁剪的两个排盘工具,单进程跑:
三钱摇卦 · 纳甲装卦 · 世应六亲 · 十三神煞 · 四段解卦,附《增删卜易》卦例 100 例研读。
排盘由确定性引擎计算,解读依盘面事实展开;大模型由用户自带(key 只存本机浏览器)。
| 工具 | 保留 | 移除 |
- 线上:<https://zhanbu.lufei.de>
- 技术栈:Next.js 16(App Router)+ vinext / Cloudflare Workers + D1 + PWA
| 页面 | 内容 |
| --- | --- |
| `/` 起卦 | 所问 / 性别 / 时间 + 三钱摇卦(Web Crypto)· 可手动指定本卦变卦 · 移动端底部悬浮起卦 |
| `/liuyao` 排盘 | 纳甲、安世应、定六亲、旬空、伏神、六神、月卦身、十三神煞;四段解卦(取用 / 盘面 / 走势 / 应期) |
| `/examples` 案例 | 《增删卜易》卦例 100 例:古筮知识 / 原注 / 用神·吉凶·应期;每例可一键还原盘面 |
| `/cases` 历史排盘 | 只存起卦输入,打开时由引擎重排同一卦 |
| `/classics` 古籍 | 周易经传与象数文献入口(原文核校后逐步加入) |
> 本文即是**部署文档**:从零把本项目部署到 Cloudflare Workers + D1 + 自有域名。
> 更深的取舍与约束见 [docs/cloudflare.md](docs/cloudflare.md),开发交接见 [NEXT.md](NEXT.md)。
---
## 0. 先决条件
| 项 | 要求 | 说明 |
| --- | --- | --- |
| **六爻**(`/liuyao`) | 三钱摇卦 / 大衍筮法 / 手工录入 → 纳甲装卦、安世应、定六亲、旬空、伏神、六神、月卦身、天医文昌等神煞 | 问句意图引擎、用神取舍、五层 DAG、生克旺衰、应期、大模型解卦 |
| **小成图**(`/xct`) | 天地数 / 梅花时间 / 自定选卦 → 八宫天盘、中宫归藏、九宫四象八断、正推气路、盘面详录 | 问句输入、类象用神、LLM 意图识别、专事公理库、LLM 解盘 |
| Node.js | ≥ 20(推荐 22) | 构建与 CLI |
| Cloudflare 账号 | 免费即可 | Workers / D1 / 自定义域名都在免费额度内 |
| 域名 | 已托管在同一个 CF 账号 | 否则无法用 Custom Domain 绑定 |
| `cf` CLI | `npm i -g cf` | 新版官方 CLI(也可以用 `npx cf`) |
两个工具都只输出**可核查的排盘事实**:卦象由投掷与时间决定,不由解释决定。
六爻页的问句只原样写在盘面顶部(便于留档/复制),**不参与任何计算**。
```bash
node -v # v22.x
npm i -g cf
cf --version
```
## 跑起来
本地先跑通一次(可选但强烈建议):
```bash
npm install
npm run dev # 前台:http://localhost:3000
npm run dev:bg # 后台:日志写 logs/dev.out.log,按端口重启旧进程
npm test # 引擎自证 + 差分对齐(见下)
# Cloudflare Workers 回路(分支 spike/vinext 验证通过;M1 起成为部署目标)
npm run dev:vinext # vite dev(workerd,带本地 D1 绑定)
npm run build:vinext # vite build
npm run start:vinext # vite preview(生产包本地验证)
npm run deploy:vinext # 需要先 cf auth login
npm run dev:vinext # http://localhost:3001,workerd + 本地 D1
npm run check # schema + portability + 测试
```
`npm run dev/build` 走 `scripts/next.mjs`:先清掉宿主进程可能泄漏进来的
`__NEXT_PRIVATE_STANDALONE_CONFIG` 等私有变量再启动 Next。不清的话,
这些变量会被当成真实配置读入(distDir 被改写、outputFileTracingRoot 指到不存在的路径),
表现为 dev 起不来或 build 报 `TypeError: generate is not a function`。
---
手机用局域网 IP 打开时,`next.config.ts` 会把本机所有非回环 IPv4 放进
`allowedDevOrigins`。否则 Next 16 会拦掉 `/_next/static/chunks/*.js`,
页面看着完整、按钮全部不动(React 没 hydration)。
## 目录
```
app/ 首页 / 六爻页 / 小成图页
components/liuyao/ 六爻:LiuyaoView(起卦表单)· CastWorkbench(三钱/大衍)· ManualCast · HexagramBoard(古法卦单)
components/xct/ 小成图:XiaoChengTuView · NinePalaceBoard · HexagramFigure · ZhengTuiPathView · VerdictCard · ReportView
lib/liuyao/najia.ts 六爻确定性排盘引擎(core.py 的逐条移植)
lib/liuyao/board-view.ts 引擎结果 → 盘面视图数据 + 复制文本
lib/liuyao/ganzhi.ts 起卦时刻 → 四柱干支
lib/xct/ 小成图引擎(boardBuilder / judgeEngine / dagTracker / constants / guizang)
lib/hexagram/ 六爻几何与 64 卦查表(矢量爻象用)
tests/ 差分基准与引擎自证
```
## 六爻盘面版式
`components/liuyao/HexagramBoard.tsx` 是 bazi-web `components/zhanbu/MobileHexagramPoster.tsx`
embedded 分支的逐行搬运,只换数据来源:
- 占问 + 男占/女占落款、时空看板(公历 / 月建+日辰 / 旬空 / 十三神煞)
- 双卦对瞻表头(本卦 · 变卦,附归魂/游魂/六冲/六合)
- 定宽栅格:六神 32 / 本卦纳甲 68 / 爻画 46 / 世应 18 / 动爻 22 / 变卦纳甲 68 / 变爻画 46 / 动变标签 52
- 伏神就地引出 `↑伏神: 妻财子水`
版式未靠目测:同一份盘面数据分别交给原组件与本仓库组件渲染 4 类卦例
(初爻动附伏神 / 静卦 / 六爻全动 / 混杂多动),逐元素比对 DOM 结构、文本、相对几何与
字号/字重/颜色,结果完全一致。问句与性别只作落款,不参与计算。
## 六爻引擎的验证方式
`lib/liuyao/najia.ts` 是对 bazi-web `src/engine/core.py::HexagramEngine` 的逐条移植。
为了不靠"看起来对",用原引擎生成差分基准再逐案比对:
## 1. 登录 Cloudflare
```bash
# 基准已提交在 tests/fixtures/python-baseline.json(4696 案,SHA-256 指纹)
python tests/generate_python_baseline.py # 需要 bazi-web 在同级目录;仅重建基准时用
npm test
cf auth login
```
- 4096 种三钱投掷组合(固定丙午年 / 申月 / 己丑日 / 申时)
- 600 组随机年/月/日/时 + 投掷(覆盖十神起例、神煞、旬空全干支)
- 比对字段:本卦/变卦名、动爻、旬空、月卦身、驿马桃花禄神贵人、
六爻的纳甲/六亲/世应/六神/伏神(含飞伏生克描述)/动爻变出
设备码流程:终端会给出一个链接和验证码,浏览器打开
<https://dash.cloudflare.com/oauth2/device/verify> 输入验证码确认即可(5 分钟内有效)。
新增的「天医(月建前一位)」「文昌(依日干)」不参与差分(原 core.py 没有),
由 `tests/liuyao-engine.test.ts` 单独断言。
```bash
cf auth whoami # 确认已登录
cf auth list # 查看本地 profile
```
## 小成图引擎
> CI 或不想用浏览器授权时,也可以在环境变量里放 `CLOUDFLARE_API_TOKEN`(需要 Workers / D1 / Zone 权限)。
`lib/xct/` 与 bazi-web 同源,未改算法。`tests/xct-engine.test.ts` 遍历
64×64 种本卦/之卦组合 × 9 宫,断言:
---
- 八方断语必落在四象八断集合内,中宫恒为「归藏之枢」;
- 任一起点宫位的正推链都会收敛(归位 / 闭环 / 归藏 / 链止),不会死循环。
## 2. 建 D1 数据库
裁剪后没有了"用神在哪一宫",正推起点改为**读者点选的宫位**(默认中宫立极)。
这不是算法改动,只是去掉了用神层。
```bash
cf d1 create --name liuyao-db
```
## 服务端边界(为 Cloudflare 预留)
会返回一个 `uuid`。**不用手工建表** —— 应用首次访问 `/api/cases` 时会惰性执行
`migrations/0001_init.sql`(`CREATE TABLE IF NOT EXISTS cases ...`)。
- `lib/store/`:卦例存储接口(异步)+ localStorage 实现;换 D1 只改实现。
`/cases` 里可收藏、打开复原(只存起卦输入,盘面由引擎重算)、删除。
- `lib/readings/`:解卦**事实契约**(客户端只发盘面事实与问句)。
`app/api/read/route.ts` 是服务端流式代理:prompt 在服务端拼(`route` 同目录 `prompt.ts`),
密钥只在服务端 env/secret,未配置时明确返回 501。暂无前端入口,断卦口径待定。
- `scripts/check-portability.mjs`:`npm run check:portability` 守住 Workers 兼容性
(禁 `fs`/`node:*`、`next/image`、`next/font`、锁死 `output: 'export'`)。
- 目标与约束、后台规划、部署触发条件见 [docs/cloudflare.md](docs/cloudflare.md)。
想手动建也可以:
## 刻意不做的事
```bash
cf d1 query <uuid> --sql "$(cat migrations/0001_init.sql)"
cf d1 query <uuid> --sql "SELECT name FROM sqlite_master WHERE type='table'"
```
- 不取用神、不判吉凶、不排应期:这些属于规则层,原项目在五层 DAG 里,本仓库不搬。
- 不接大模型:没有提问 → 意图 → 用神 → prompt 的链路,也没有流式解卦面板。
- 不为个案写特例:引擎只有查表与确定性算法,没有 `if case_id == ...` 之类的补丁。
> 数据库名必须和 `cloudflare.config.ts` 里的 `bindings.d1({ name: 'liuyao-db' })` 一致。
> 部署时 `--provision` 默认开启,D1 不存在会自动创建。
---
## 3. 配置域名与变量
部署配置在 `cloudflare.config.ts`(TypeScript,有类型检查,写错字段会当场报错)。
### 3.1 自定义域名
用环境变量传,避免把域名写死在仓库里:
```bash
WORKER_DOMAIN=zhanbu.example.com npx cf deploy
```
配置里对应的是 **Custom Domain**(会自动建 DNS 记录 + 证书):
```ts
...(workerDomain ? { domains: [workerDomain] } : {}),
```
> 注意:不要用 `triggers.fetch({ pattern })` 代替 —— 路由不会自动建 DNS 记录,
> 会得到「部署成功但域名打不开」。Custom Domain 才是子域名的正确姿势。
不设 `WORKER_DOMAIN` 就只挂 `*.workers.dev`(首次部署会问一次子域名)。
### 3.2 运行时变量
| 变量 | 必需 | 作用 |
| --- | --- | --- |
| `LLM_ALLOWED_HOSTS` | 有默认值 | 上游域名白名单(逗号分隔后缀)。默认已含 opencode.ai / deepseek.com / api.openai.com / api.moonshot.cn / open.bigmodel.cn / dashscope.aliyuncs.com / openrouter.ai / api.siliconflow.cn |
| `LLM_API_KEY` / `LLM_BASE_URL` / `LLM_MODEL` | 否 | 服务端兜底模型(正常不需要:用户在页面「设置」里自带 key) |
| `LLM_THINKING` / `LLM_REASONING_EFFORT` | 否 | 兜底模型的思考模式 / 强度 |
**大模型 key 不需要配到服务端**:用户在右上角「设置」里填,只存自己浏览器的
`localStorage['liuyao.llm.v1']`,解卦时随请求体发给 `/api/read`,服务端只转发一次。
想改白名单,直接传环境变量即可覆盖默认值:
```bash
LLM_ALLOWED_HOSTS=opencode.ai,api.deepseek.com npx cf deploy
```
---
## 4. 部署
```bash
WORKER_DOMAIN=zhanbu.example.com npx cf deploy
```
`cf deploy` 会先跑构建(`build:vinext`),再上传静态资源 + Worker。成功输出类似:
```
✨ Success! Uploaded 46 files
Total Upload: 1553.77 KiB / gzip: 487.06 KiB
Your Worker has access to the following bindings:
env.DB (liuyao-db) D1 Database
env.ASSETS Assets
env.LLM_ALLOWED_HOSTS ("opencode.ai,…") Environment Variable
Uploaded liuyao
Deployed liuyao triggers
zhanbu.example.com (custom domain)
◆ Deploy complete
```
只检查不发布(强烈建议首次先跑):
```bash
WORKER_DOMAIN=zhanbu.example.com npx cf deploy --dry-run
```
---
## 5. 上线验收清单
```bash
curl -I https://zhanbu.example.com/ # 200
curl -I https://zhanbu.example.com/examples # 200
curl -I https://zhanbu.example.com/cases # 200
curl -I https://zhanbu.example.com/manifest.webmanifest # 200(PWA)
curl -I https://zhanbu.example.com/sw.js # 200(离线壳)
curl -I https://zhanbu.example.com/data/zengshan-cases.json # 200(案例数据)
```
接口自检(应分别得到 501 / 403 / 403):
```bash
# 1) 没配模型 → 501
curl -s -X POST https://zhanbu.example.com/api/read \
-H 'Content-Type: application/json' -d '{"facts":{"kind":"liuyao","lines":[]}}'
# 2) 跨站 Origin → 403
curl -s -X POST https://zhanbu.example.com/api/read \
-H 'Content-Type: application/json' -H 'Origin: https://evil.example.com' \
-d '{"facts":{"kind":"liuyao","lines":[]}}'
# 3) 白名单外上游 → 403
curl -s -X POST https://zhanbu.example.com/api/read \
-H 'Content-Type: application/json' -H 'Origin: https://zhanbu.example.com' \
-d '{"facts":{"kind":"liuyao","lines":[]},"llm":{"baseUrl":"https://evil.example.com/v1","model":"x","apiKey":"k"}}'
```
D1 是否就绪:
```bash
cf d1 query <uuid> --sql "SELECT name FROM sqlite_master WHERE type='table'"
# 应看到 cases
```
浏览器里再走一遍:起卦 → 排盘 → 设置里填模型 → 测试连接 → 解卦 → 历史排盘能回看。
---
## 6. 边缘限流(建议)
免费套餐的限制:**每个 phase 只能 1 条规则、`period` 只能是 10 秒、不能用 `matches` 运算符**。
所以规则只能写成「10 秒 N 次 + 路径包含」。
```bash
# 找到 zone 的 http_ratelimit 规则集
cf rulesets list --zone example.com # 取 phase=http_ratelimit 的 id
# 规则文件(注意 characteristics 必须带 cf.colo.id;mitigation_timeout 只能为 0 或 ≥ period)
cat > rl.json <<'EOF'
[
{
"action": "block",
"description": "API 限流(10 秒内最多 4 次)",
"enabled": true,
"expression": "(http.request.uri.path contains \"/api/\")",
"ratelimit": {
"characteristics": ["ip.src", "cf.colo.id"],
"mitigation_timeout": 10,
"period": 10,
"requests_per_period": 4
}
}
]
EOF
cf rulesets update <ruleset-id> --zone example.com --id <ruleset-id> --rules @rl.json
```
> 应用内还有一层:`/api/read` 8 次/分 + 60 次/时(进程内计数,只在单实例内准确)。
> 想要「每分钟 / 每小时」粒度的边缘规则需要 Pro(Advanced Rate Limiting)。
---
## 7. 日常更新与回滚
```bash
git pull
npm run check # 先本地全绿
WORKER_DOMAIN=zhanbu.example.com npx cf deploy # 重新发布(秒级)
```
- **回滚**:`cf workers deployments list liuyao` 找到上一版本,
`cf workers deployments rollback liuyao`(或控制台 Workers → Deployments 一键回滚)。
- **看日志**:`cf workers tail liuyao` 或控制台 Workers Logs。
- **D1 备份**:`cf d1 export <uuid> --output backup.sql`(定期存一份)。
---
## 8. 常见坑
| 现象 | 原因 / 处理 |
| --- | --- |
| 部署成功但域名 502/000 | 用了 `triggers.fetch` 路由却没 DNS 记录 → 改用 Custom Domain(`domains: [...]`);证书签发需要 1–2 分钟 |
| 静态资源 307 循环 | `public/` 下文件名带 `@`(如 `coin-4@2x.png`):Workers Assets 会把 `@` 编码成 `%40` 再跳回来。用 `-2x` / `-3x`。`npm run check:portability` 已加守卫 |
| 页面能开但按钮全不动 | 手机用局域网 IP 访问 dev 时被 Next 拦了 chunk:`next.config.ts` 已把非回环 IPv4 放进 `allowedDevOrigins`;线上不受影响 |
| 解卦返回 501 | 没配模型:页面右上角「设置」里填 baseUrl / model / key |
| 解卦返回 403「上游域名不在允许列表内」 | 目标供应商没进 `LLM_ALLOWED_HOSTS`:加进环境变量重新部署 |
| 解卦返回 403「仅接受本站页面发起的请求」 | 请求带了别的站点的 `Origin`:这是防代理设计,正常用页面点不受影响 |
| D1 报 `no such table: cases` | 首次访问 `/api/cases` 会自动建表;确认 `DB` 绑定名与配置一致 |
---
## 9. 目录与关键文件
```
cloudflare.config.ts Worker 名 / 绑定 / 自定义域名(部署配置的唯一事实源)
migrations/*.sql D1 表结构(gen:schema 生成运行时建表常量)
app/api/read/route.ts 解卦 SSE 代理(同源校验 + 双窗限流 + 上游白名单)
app/api/llm-test/route.ts 模型连通性测试
app/api/cases/route.ts 卦例读写(D1,按匿名设备 Cookie 隔离)
lib/llm/settings.ts 供应商预设 / 校验 / localStorage
lib/llm/server.ts 服务端校验 + SSRF 拦截 + 白名单
public/sw.js PWA 离线壳
scripts/check-portability.mjs Workers 兼容性守卫(禁 node:*、next/image、@ 文件名等)
```
---
## 10. 技术要点
**随机源**:每次投掷都来自 Web Crypto(`crypto.getRandomValues`),逐位取 Uint32 最低有效位,
天然无偏;缺 Web Crypto 直接报错,不回落 PRNG。三钱概率严格 6/7/8/9 = 1/8 · 3/8 · 3/8 · 1/8,
`tests/random.test.ts` 钉住分布与「起卦路径不得出现 Math.random」。
**案例页**:`public/data/zengshan-cases.json` 由 `scripts/extract-zengshan-cases.mjs`
从《增删卜易卦例初探》整理文本抽取 100 例(原文不截断);卦盘不是照抄原文,
而是由卦名反推六次投掷、再取「同月建同日辰」的公历重排,所以与「排出此卦」看到的盘面一致。
**刻意不做**:盘面上不标用神、不印吉凶判词(断语只在解卦正文里);不取用神规则化、不排应期;
不为个案写特例(引擎只有查表与确定性算法)。
**断卦提示词**:完整规范在 [`docs/prompt-liuyao.md`](docs/prompt-liuyao.md)(v3,含"代码引擎负责排盘事实、
AI 只负责推理"的两层职责与八条硬约束);运行时只用其中精编版(`app/api/read/prompt.ts`,四段 400–550 字)。
**PWA**:`app/manifest.ts` + `public/sw.js`,装到主屏后全屏无地址栏,起卦与排盘离线可用;
Service Worker 只在非本机域名注册(localhost 自动注销,避免开发缓存脏 chunk)。
+20
View File
@@ -0,0 +1,20 @@
import type { Metadata } from 'next';
import Link from 'next/link';
export const metadata: Metadata = { title: '关于 | 六爻' };
export default function AboutPage() {
return (
<main className="min-h-screen bg-[#F4F1E8] px-4 py-16 text-[#38423C] sm:px-7">
<div className="mx-auto max-w-[680px]">
<Link href="/" className="font-song text-[12px] text-[#756E5F] underline-offset-4 hover:underline">← 返回起卦</Link>
<h1 className="mt-8 font-song text-[30px] font-semibold tracking-[0.16em] text-[#304239]">关于</h1>
<div className="mt-5 space-y-4 font-song text-[14px] leading-[2] text-[#5D6259]">
<p>这是一个以确定性排盘为基础的六爻工具。</p>
<p>排盘由程序计算;解读是模型基于盘面事实给出的参考,不替代现实中的专业判断。</p>
<p>易学典籍页将逐步整理周易经传与相关文献,原文、版本与出处会尽量注明。</p>
</div>
</div>
</main>
);
}
+120
View File
@@ -0,0 +1,120 @@
import { CaseValidationError, parseCaseRecord } from '@/lib/cases/validate';
import { clientIp, rateLimit, sameOrigin } from '@/lib/server/request';
import { getOrCreateDeviceId } from '@/lib/server/device';
import { getServerCaseStore } from '@/lib/store/server';
import type { CaseRecord } from '@/lib/store/types';
export const dynamic = 'force-dynamic';
const MAX_BODY = 512 * 1024;
const MAX_IMPORT = 200;
function respond(data: unknown, status = 200, setCookie?: string): Response {
const res = Response.json(data, { status, headers: { 'Cache-Control': 'no-store' } });
if (setCookie) res.headers.append('Set-Cookie', setCookie);
return res;
}
async function readBody(req: Request): Promise<Record<string, unknown>> {
const raw = await req.text();
if (raw.length > MAX_BODY) throw new CaseValidationError('请求体过大');
try {
const json = JSON.parse(raw || '{}');
if (!json || typeof json !== 'object') throw new Error();
return json as Record<string, unknown>;
} catch {
throw new CaseValidationError('请求体必须是 JSON 对象');
}
}
function fail(e: unknown, setCookie?: string): Response {
if (e instanceof CaseValidationError) return respond({ error: e.message }, 400, setCookie);
console.error('[cases]', e);
return respond({ error: '卦例服务异常' }, 500, setCookie);
}
export async function GET(req: Request) {
const { ownerId, setCookie } = getOrCreateDeviceId(req);
try {
if (rateLimit(`cases:get:${clientIp(req)}`, 240, 60_000)) {
return respond({ error: '请求过于频繁' }, 429, setCookie);
}
const url = new URL(req.url);
const { store, mode } = await getServerCaseStore(ownerId);
// 客户端用它决定「远端」还是「本地 localStorage」
if (url.searchParams.get('probe')) return respond({ mode }, 200, setCookie);
const id = url.searchParams.get('id');
if (id) {
const record = await store.get(id);
return record ? respond({ mode, case: record }, 200, setCookie) : respond({ mode, case: null }, 404, setCookie);
}
return respond({ mode, cases: await store.list() }, 200, setCookie);
} catch (e) {
return fail(e, setCookie);
}
}
export async function POST(req: Request) {
const { ownerId, setCookie } = getOrCreateDeviceId(req);
if (!sameOrigin(req)) return respond({ error: '跨源请求被拒绝' }, 403, setCookie);
if (rateLimit(`cases:write:${clientIp(req)}`, 60, 60_000)) {
return respond({ error: '写入过于频繁,请稍后再试' }, 429, setCookie);
}
try {
const body = await readBody(req);
const { store, mode } = await getServerCaseStore(ownerId);
// 批量导入(本地 → 远端迁移),按 id 幂等
if (Array.isArray(body.cases)) {
if (body.cases.length > MAX_IMPORT) return respond({ error: `一次最多导入 ${MAX_IMPORT} 条` }, 400, setCookie);
const records = body.cases.map(parseCaseRecord) as CaseRecord[];
for (const record of records) await store.save(record);
return respond({ ok: true, imported: records.length, mode }, 200, setCookie);
}
const record = parseCaseRecord(body.record);
await store.save(record);
return respond({ ok: true, id: record.id, mode }, 200, setCookie);
} catch (e) {
return fail(e, setCookie);
}
}
export async function PATCH(req: Request) {
const { ownerId, setCookie } = getOrCreateDeviceId(req);
if (!sameOrigin(req)) return respond({ error: '跨源请求被拒绝' }, 403, setCookie);
if (rateLimit(`cases:write:${clientIp(req)}`, 60, 60_000)) {
return respond({ error: '写入过于频繁,请稍后再试' }, 429, setCookie);
}
try {
const body = await readBody(req);
const id = typeof body.id === 'string' ? body.id : '';
if (!id) throw new CaseValidationError('缺少 id');
const { store } = await getServerCaseStore(ownerId);
await store.setFavorite(id, body.favorite === true);
return respond({ ok: true }, 200, setCookie);
} catch (e) {
return fail(e, setCookie);
}
}
export async function DELETE(req: Request) {
const { ownerId, setCookie } = getOrCreateDeviceId(req);
if (!sameOrigin(req)) return respond({ error: '跨源请求被拒绝' }, 403, setCookie);
if (rateLimit(`cases:write:${clientIp(req)}`, 60, 60_000)) {
return respond({ error: '写入过于频繁,请稍后再试' }, 429, setCookie);
}
try {
const id = new URL(req.url).searchParams.get('id') ?? '';
if (!id) throw new CaseValidationError('缺少 id');
const { store } = await getServerCaseStore(ownerId);
await store.remove(id);
return respond({ ok: true }, 200, setCookie);
} catch (e) {
return fail(e, setCookie);
}
}
+122
View File
@@ -0,0 +1,122 @@
/**
* 大模型连通性测试(服务端一次性转发)
* ====================================
* POST { baseUrl, model, apiKey } → { ok: true, sample } | { ok: false, error }
*
* 只发一句极短的问候,用来确认「地址 + 模型 + key」三件事是否对得上。
* 与解卦一样:key 只在内存里用一次,不落库、不写日志、不回显。
*/
import { normalizeLlmRequest, upstreamHostAllowed } from '@/lib/llm/server';
import { buildChatRequestBody } from '@/lib/readings/llm-request';
import { buildProviderHeaders } from '@/lib/readings/provider-headers';
const MAX_BODY_BYTES = 8 * 1024;
const TIMEOUT_MS = 20_000;
const RATE = { windowMs: 60_000, max: 10 };
const hits = new Map<string, { count: number; resetAt: number }>();
function clientIp(req: Request): string {
const h = req.headers;
return (
h.get('cf-connecting-ip') ||
h.get('x-real-ip') ||
(h.get('x-forwarded-for') || '').split(',')[0].trim() ||
'unknown'
);
}
function rateLimited(ip: string): boolean {
const now = Date.now();
const cur = hits.get(ip);
if (!cur || cur.resetAt < now) {
hits.set(ip, { count: 1, resetAt: now + RATE.windowMs });
return false;
}
cur.count += 1;
return cur.count > RATE.max;
}
function crossSite(req: Request): boolean {
const origin = req.headers.get('origin');
if (!origin) return false;
try {
return new URL(origin).host !== new URL(req.url).host;
} catch {
return true;
}
}
export async function POST(req: Request): Promise<Response> {
if (crossSite(req)) {
return Response.json({ ok: false, error: '仅接受本站页面发起的测试请求' }, { status: 403 });
}
if (rateLimited(clientIp(req))) {
return Response.json({ ok: false, error: '请求过于频繁,请稍后再试' }, { status: 429 });
}
const raw = await req.text();
if (raw.length > MAX_BODY_BYTES) {
return Response.json({ ok: false, error: '请求体过大' }, { status: 413 });
}
let body: unknown;
try {
body = JSON.parse(raw);
} catch {
return Response.json({ ok: false, error: '请求体必须是 JSON' }, { status: 400 });
}
const resolved = normalizeLlmRequest(body);
if (!resolved.ok) return Response.json({ ok: false, error: resolved.error }, { status: 400 });
const config = resolved.config;
if (config) {
const allowed = upstreamHostAllowed(config.baseUrl);
if (!allowed.ok) return Response.json({ ok: false, error: allowed.error }, { status: 403 });
}
if (!config) {
return Response.json({ ok: false, error: '还没有配置大模型' }, { status: 400 });
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
try {
const res = await fetch(`${config.baseUrl}/chat/completions`, {
method: 'POST',
headers: buildProviderHeaders(config.baseUrl, config.key),
signal: controller.signal,
body: JSON.stringify(
buildChatRequestBody({
model: config.model,
messages: [{ role: 'user', content: '连通性测试,请只回复两个字:可用' }],
stream: false,
maxTokens: 16,
temperature: 0,
}),
),
});
const text = await res.text().catch(() => '');
if (!res.ok) {
return Response.json({ ok: false, error: `上游返回 ${res.status}:${text.slice(0, 300)}` });
}
let sample = '';
try {
const json = JSON.parse(text) as { choices?: { message?: { content?: string } }[] };
sample = json?.choices?.[0]?.message?.content?.slice(0, 80) ?? '';
} catch {
sample = text.slice(0, 80);
}
return Response.json({ ok: true, model: config.model, sample });
} catch (e) {
const err = e as Error;
return Response.json({
ok: false,
error: err.name === 'AbortError' ? '连接超时(20s)' : `连接失败:${err.message}`,
});
} finally {
clearTimeout(timer);
}
}
export const dynamic = 'force-dynamic';
+134 -54
View File
@@ -1,22 +1,77 @@
/**
* 解卦 prompt(服务端专用)
* ========================
* 只在这里拼 prompt:客户端 bundle 里不应出现任何提示词模板,
* 否则「换口径 / 调风格」就必须重新发版,而且模板会被直接读走。
*
* TODO(产品口径):宗法取用(父母/官鬼/妻财…)、吉凶表达与应期写法尚未定稿。
* 目前 prompt 刻意保守:只复述事实 + 作象理说明,不承诺结果。
* 等口径确定,只改这个文件即可,不需要动路由与前端。
* 原则:
* 1. 盘面由引擎确定性排出,模型**不重排**、不改写干支/六亲/世应/旬空/动变(第 5 条是硬约束);
* 2. 只使用事实里出现的爻辞与神煞,缺的不补、不编;
* 3. prompt 只在这里拼,不随客户端 bundle 下发;
* 4. 输出走「禅意」写法:四段、少而准,不写报告体、不罗列盘面;
* 5. 事实层与推理层分开:缺失字段标「未提供」,不补算、不把推测写成事实。
*/
import type { ReadingFacts } from '@/lib/readings/types';
import { PROMPT_SPEC } from '@/lib/readings/prompt-spec.generated';
const SYSTEM_PROMPT = `你是易学盘面解读助手。规则:
1. 只能使用用户提供的盘面事实(JSON)。不得增补、改写或臆造任何卦爻、六亲、纳甲、旬空、世应、动变、神煞、宫位。
2. 先复述关键事实(本卦/变卦、动爻、旬空、用到的神煞;小成图则复述九宫与中宫、正推链),再作象理说明。
3. 盘面事实里没有「用神」。如果你要按用神讲,必须先说明「我依据什么取用」,并明确这是解读者的取用,不是盘面事实。
4. 语言平实克制,不堆砌辞藻;不下绝对化的凶灾、疾病、诉讼、投资结论,不承诺必然结果。
5. 不虚构盘面之外的个人信息(职业、年龄、亲眷、病史等)。信息不足就直说不足。`;
const SYSTEM_PROMPT = `# 你是谁
你是一位六爻解卦者。熟悉《易冒》《黄金策》《增删卜易》《卜筮正宗》等通行法理,也清楚自己的边界:只作传统文化参考,不替代医疗、法律、财务的专业判断。
# 你收到的是已经排好的盘
用户消息是一份由引擎确定性排出的盘面事实:起卦时间、所问、本卦与变卦、宫位、动爻、旬空、月卦身、十三神煞,六爻的纳甲/六亲/六神/世应/伏神/动变,以及本卦与变卦的卦辞、动爻爻辞。
- 不要重排盘,不要改写任何干支、六亲、世应、旬空、动爻、神煞;
- 只使用事实中出现的爻辞与神煞,没有给出的不要补、不要编;
- 不要虚构古籍原文。能确证才引;不确定就写「通行法理如此」。
# 事实层铁律
- 盘面事实是唯一来源:纳甲、六亲、六神、世应、伏神、旬空、月建日辰、动变、神煞一律照用,不重算、不改写、不因流派差异改动。
- 事实里没给的(神煞、爻辞、字段)标「未提供」,不补算、不写成事实;用户质疑盘面时,说明由确定性引擎排出,解释层不改写。
- 事实与推断分开写:哪些是盘面,哪些是你的判断,不得混成一句。
# 断卦次序(内部执行,不要把这些步骤逐条复述)
1. 取用神:自占取世爻;问父母/文书取父母;问财/妻取妻财;问官/工作/病邪取官鬼;问子女/医药取子孙;问同辈/竞争取兄弟。代占先说明关系。用神多现时取动、取世应、取旺、取近,并说明取舍。
专项路由:宠物取子孙为生命主体(不得与医药混用);失物按物类(财物妻财、文书舟车父母、禽兽子孙);求财妻财为主、子孙为生财原神;工作官鬼看岗位、父母看文书、应爻看单位;家宅父母看房屋、官鬼看风险。
2. 看月建日辰:用神旺相休囚、月破日破、生扶冲克、旬空、墓绝。
3. 看动变:动爻生克、回头生克、化进退、化空破墓绝、六合六冲、三合、反吟伏吟,以及变爻对本爻的作用。
4. 看世应:世为己,应为对方或事所;看生克冲合。
5. 看六神与神煞:只作象,不单断。白虎血光、朱雀口舌、勾陈迟滞、螣蛇惊忧、青龙喜庆、玄武暗昧。
6. 看卦象与辞:卦名、六冲六合、卦辞与动爻爻辞,作取象层。
# 病占专项(仅当所问涉及疾病、伤损、身体、就医时启用;其余占问跳过本节)
- 用神墓绝受冲、白虎临用、鬼旺克用、财动生鬼:主急重、失血、正虚、手术创伤。
- 近病逢冲即愈,久病逢冲则危;六冲化六冲要分近病久病、用神旺衰。
- 墓库逢冲则开;空亡待填实;绝处逢生看贵人、子孙、动爻救应。
- 子孙制鬼为医药有效;子孙被合被克则药力受牵制,需强干预。
- 白虎凶神已应在手术血光,不等于持续凶;用神临贵人、变卦主权威医疗,可作救机。
- 病占的医疗建议放在结论之后,并明确「以主治医生 / ICU / 外科 / 介入科实时判断为准」。
# 判断原则
- 主干是用神、月建日辰与动变;六神、神煞、卦辞只是象。多条独立线索同指一事时可上调象的权重,但不得越过主干。
- 吉象与凶象并见时,分别列出,并说明各自成立的条件;不要只挑一边。
- 区分:盘面事实 / 卦理推断 / 应期推测 / 现实建议。
- 不断死,不断人的价值,不把或然当必然,不保证准确。
- 应期给区间与触发条件(冲实、填实、值日、合日等);证据不足就写「应期需更多信息」,不精确到时辰,也不把卦理应期当成现实承诺。
- 涉及健康、急症:先提醒以医生判断为准;涉及法律、财务:提醒咨询专业人士。
- 六神与神煞只作辅助象,不可喧宾夺主。
- 病占时,凶象与救机必须分列,不能只渲染凶险,也不能安慰式地抹掉凶象。
# 写法(禅意:少而准)
- 平实、克制,不写报告体;**不要任何 Markdown 标记**(不用双星号加粗、不用表格、不用层级符号),
也不要罗列盘面(界面已经给出)。
- 结构固定为四段,**段首必须是下面四行原文,单独成行**,标题后不要接正文;
正文另起一行写在这四行下面,段与段之间空一行:
一、取用
二、盘面
三、走势
四、应期
- 各段字数预算,宁短不长:
取用约 100 字:只写取了哪一爻、为什么取它,一句话交代兼看。
盘面约 180 字:只写真正改变结论的 2~3 条依据(月日如何作用于用神、动变如何、关键象);
不要把盘面重念一遍,不要逐爻罗列。
走势约 150 字:趋势一句定调,然后「有利」与「不利」各一两句,并写清成立条件。
应期约 80 字:给区间与触发条件;不确定就直说信息不足。
- 结尾只留一句可执行的提醒,不承诺结果。
- 全文 400–550 字,**硬上限 600 字**:写完先自查,超过就删掉重复的、可推断的、修饰性的句子。
- 宁可少说一句,不要为凑字数补一段。`;
function liuyaoBrief(facts: Extract<ReadingFacts, { kind: 'liuyao' }>): string {
const lines = [...facts.lines].sort((a, b) => b.position - a.position);
@@ -31,58 +86,83 @@ function liuyaoBrief(facts: Extract<ReadingFacts, { kind: 'liuyao' }>): string {
...l.stars,
]
.filter(Boolean)
.join('/');
.join('·');
const hidden = l.hidden ? `,伏神${l.hidden.relation}${l.hidden.najia}` : '';
const changed = l.changed ? `,动化${l.changed.relation}${l.changed.najia}` : '';
return `${l.position}爻|${l.sixGod}|${l.relation}${l.najia}${marks ? `|${marks}` : ''}${hidden}${changed}`;
return `${l.position}爻 ${l.sixGod} ${l.relation}${l.najia}${marks ? `[${marks}]` : ''}${hidden}${changed}`;
})
.join('\n');
const s = facts.shensha;
const shensha = [
`贵人 ${s.guiren}`,
`禄神 ${s.lushen}`,
`羊刃 ${s.yangren}`,
`文昌 ${s.wenchang}`,
`驿马 ${s.yima}`,
`桃花 ${s.taohua}`,
`将星 ${s.jiangxing}`,
`华盖 ${s.huagai}`,
`谋星 ${s.mouxing}`,
`劫煞 ${s.jiesha}`,
`灾煞 ${s.zaisha}`,
`天医 ${s.tianyi}`,
`天喜 ${s.tianxi}`,
].join('|');
const oracleBits: string[] = [`本卦卦辞:${facts.oracle.baseGuaCi ?? '(未收)'}`];
if (facts.oracle.changedGuaCi && facts.changed) {
oracleBits.push(`变卦卦辞:${facts.oracle.changedGuaCi}`);
}
for (const y of facts.oracle.movingLines) oracleBits.push(`动爻爻辞:${y.text}`);
if (facts.oracle.yong) oracleBits.push(`${facts.oracle.yong.title}:${facts.oracle.yong.text}`);
return [
`【六爻盘面】`,
`起卦:${facts.time.solar} · ${facts.time.ganzhi}`,
`问句:${facts.question || '(未填写)'}`,
`本卦:${facts.base.name}(${facts.base.palace}宫·${facts.base.element}${facts.base.tags.length ? '·' + facts.base.tags.join('') : ''})`,
`变卦:${facts.changed ? `${facts.changed.name}(${facts.changed.palace}宫·${facts.changed.element})` : '无(六爻安静)'}`,
`动爻:${facts.movingLines.length ? facts.movingLines.join('、') : '无'}`,
`旬空:${facts.voidBranches.join('')}`,
`月卦身:${facts.monthBody.branch}${facts.monthBody.position ? `(${facts.monthBody.position}爻)` : '(不现)'}`,
`神煞:驿马${facts.shensha.yima} 桃花${facts.shensha.taohua} 禄神${facts.shensha.lushen} 贵人${facts.shensha.guiren.join('')} 天医${facts.shensha.tianyi} 文昌${facts.shensha.wenchang}`,
`六爻(上→初):\n${lineText}`,
`【起卦】${facts.time.solar} · ${facts.time.ganzhi}`,
`【所问】${facts.question || '(未填写)'}`,
`【本卦】${facts.base.name}(${facts.base.palace}宫·${facts.base.element}${facts.base.tags.length ? '·' + facts.base.tags.join('') : ''})`,
`【变卦】${facts.changed ? `${facts.changed.name}(${facts.changed.palace}宫·${facts.changed.element})` : '无(六爻安静)'}`,
`【动爻】${facts.movingLines.length ? facts.movingLines.join('、') : '无'}`,
`【旬空】${facts.voidBranches.join('')} 【月卦身】${facts.monthBody.branch}${facts.monthBody.position ? `(${facts.monthBody.position}爻)` : '(不现)'}`,
`【十三神煞】${shensha}`,
`【经文】${oracleBits.join('\n')}`,
`【六爻(上→初)】\n${lineText}`,
].join('\n');
}
function xctBrief(facts: Extract<ReadingFacts, { kind: 'xct' }>): string {
const palaceText = facts.palaces
.map(
(p) =>
`${p.palaceName}|天盘${p.heaven}/地盘${p.earth}|${p.hexName || `${p.heaven}之${p.earth}`}|${
p.mode ? `${p.mode}式·` : ''
}${p.matched === null ? '' : p.matched ? '得配·' : '失配·'}${p.verdict}`,
)
.join('\n');
/** 六爻专用:系统提示与用户消息 */
/**
* 拼 prompt:整份规范(原版全量,不选章、不压缩)+ 本次盘面事实
*
* 规范正文见 docs/prompt-liuyao.md,构建期由 scripts/build-prompt-spec.mjs
* 内联成 lib/readings/prompt-spec.generated.ts(Workers 无 fs)。
*/
export function buildLiuyaoPrompt(facts: Extract<ReadingFacts, { kind: 'liuyao' }>): { system: string; user: string } {
const system = composeSystem();
return [
`【小成图盘面】`,
`起卦:${facts.time.solar} · ${facts.time.ganzhi}`,
`问句:${facts.question || '(未填写)'}`,
`本图:${facts.ben.name}(${facts.ben.upper}上${facts.ben.lower}下)`,
`之图:${facts.zhi.name}(${facts.zhi.upper}上${facts.zhi.lower}下)`,
`中宫归藏:${facts.center}`,
`九宫(洛书序 4-9-2 / 3-5-7 / 8-1-6):\n${palaceText}`,
`正推链:${facts.chain.path.join(' → ')}(${facts.chain.endReason}${facts.chain.hasCycle ? '·闭环' : ''})`,
`链注:${facts.chain.summary}`,
].join('\n');
}
export function buildReadingPrompt(facts: ReadingFacts): { system: string; user: string } {
const brief = facts.kind === 'liuyao' ? liuyaoBrief(facts) : xctBrief(facts);
const ask =
facts.kind === 'liuyao'
? '请按上面的事实解读这一卦:先复述关键事实,再说象理与走势。'
: '请按上面的事实解读这一图:先复述关键事实,再说九宫气路与走势。';
const ask = '请按四段写出这一卦的解读。盘面已是定局,不必重排,也不要复述全部爻位。';
return {
system: SYSTEM_PROMPT,
user: `${brief}\n\n${ask}\n(以上事实由引擎确定性排出;不要改写事实本身。)`,
system,
user: `${liuyaoBrief(facts)}
${ask}
(以上事实由引擎确定性排出;不要改写事实本身。)`,
};
}
/**
* 按问句组装 system:
* 核心章(零/一/二/三/四/五/六/十五/十六/十八/十九/二十)
* + 命中的专项章(七…十四,整章原样)
* + §十七 头部(四层 + 四段模板)+ 通用清单 A + 命中专项对应的输出清单
*/
/**
* system = 整份规范(59k 字 / ≈40k token),不做任何选章、不用关键词正则。
*
* 为什么全量:断卦是模型的判断工作,哪一章适用应由它自己理解;
* 用正则预选章会替模型做决定,漏命中就少一整章规则,误命中又白烧 token。
* 成本实测 ≈$0.006/次,对本站量级可忽略。
*/
export function composeSystem(): string {
return PROMPT_SPEC;
}
+141 -57
View File
@@ -1,12 +1,15 @@
/**
* 解卦流式接口(服务端)
* ======================
* POST { facts: ReadingFacts } → SSE(data: {"content": "..."} ... data: [DONE])
* POST { facts: ReadingFacts, llm?: { baseUrl, model, apiKey, thinking?, reasoningEffort? } }
* → SSE(data: {"content": "..."} ... data: {"done":true})
*
* 边界:
* - 客户端只发盘面事实与问句,**永不**持有 API key;
* - prompt 在服务端拼(./prompt.ts),不随客户端下发;
* - 未配置 LLM 时明确 501,不退化成假解读。
* - 大模型配置(含 key)**只存在用户浏览器的 localStorage**,每次请求随 body 带上;
* 服务端只在内存里用它转发一次,不落库、不写日志、不回显;
* - 请求体里的 key 只对本次上游调用有效,转发完即随请求对象一起被回收;
* - 没有客户端配置时,退回服务端环境变量(自建/私人部署的兜底),仍未配置则明确 501;
* - prompt 在服务端拼(./prompt.ts),不随客户端下发。
*
* 只用 fetch / Web Streams,没有 node:* 依赖,可直接跑在 Workers(vinext/OpenNext)。
*
@@ -14,12 +17,22 @@
* 真正上线时应换成 Cloudflare Rate Limiting 或 D1/KV 计数(见 docs/cloudflare.md)。
*/
import { buildReadingPrompt } from './prompt';
import { buildLiuyaoPrompt } from './prompt';
import type { ReadingFacts } from '@/lib/readings/types';
import { buildChatRequestBody } from '@/lib/readings/llm-request';
import { buildProviderHeaders } from '@/lib/readings/provider-headers';
import {
friendlyUpstreamError,
normalizeLlmRequest,
shouldRetryUpstream,
upstreamHostAllowed,
type LlmRequestConfig,
} from '@/lib/llm/server';
const MAX_BODY_BYTES = 64 * 1024;
const RATE_LIMIT = { windowMs: 60_000, max: 8 };
const hits = new Map<string, { count: number; resetAt: number }>();
/** 分钟窗 + 小时窗双限:分钟挡突发,小时挡刷量(进程内计数,多实例时偏松,正式上限交给 CF 边缘限流) */
const RATE_LIMIT = { windowMs: 60_000, max: 8, hourMs: 3_600_000, hourMax: 60 };
const hits = new Map<string, { count: number; resetAt: number; hourCount: number; hourResetAt: number }>();
function clientIp(req: Request): string {
const h = req.headers;
@@ -34,39 +47,53 @@ function clientIp(req: Request): string {
function rateLimited(ip: string): boolean {
const now = Date.now();
const cur = hits.get(ip);
if (!cur || cur.resetAt < now) {
hits.set(ip, { count: 1, resetAt: now + RATE_LIMIT.windowMs });
if (!cur) {
hits.set(ip, {
count: 1,
resetAt: now + RATE_LIMIT.windowMs,
hourCount: 1,
hourResetAt: now + RATE_LIMIT.hourMs,
});
return false;
}
cur.count += 1;
return cur.count > RATE_LIMIT.max;
if (cur.resetAt < now) {
cur.count = 1;
cur.resetAt = now + RATE_LIMIT.windowMs;
} else {
cur.count += 1;
}
if (cur.hourResetAt < now) {
cur.hourCount = 1;
cur.hourResetAt = now + RATE_LIMIT.hourMs;
} else {
cur.hourCount += 1;
}
return cur.count > RATE_LIMIT.max || cur.hourCount > RATE_LIMIT.hourMax;
}
interface LlmConfig {
key: string;
baseUrl: string;
model: string;
}
function llmConfig(): LlmConfig | null {
const key = process.env.LLM_API_KEY || process.env.DEEPSEEK_API_KEY || process.env.OPENAI_API_KEY || '';
if (!key) return null;
return {
key,
baseUrl: (process.env.LLM_BASE_URL || 'https://api.deepseek.com').replace(/\/+$/, ''),
model: process.env.LLM_MODEL || 'deepseek-chat',
};
/** 只接受本站页面发起的调用:带了 Origin 却不是本站,直接拒(挡住别的网站拿本站当转发口) */
function crossSite(req: Request): boolean {
const origin = req.headers.get('origin');
if (!origin) return false;
try {
return new URL(origin).host !== new URL(req.url).host;
} catch {
return true;
}
}
function validFacts(x: unknown): x is ReadingFacts {
if (!x || typeof x !== 'object') return false;
const f = x as Partial<ReadingFacts>;
if (f.kind === 'liuyao') return Array.isArray((f as never as { lines?: unknown }).lines);
if (f.kind === 'xct') return Array.isArray((f as never as { palaces?: unknown }).palaces);
return false;
if (f.kind !== 'liuyao') return false;
return Array.isArray((f as never as { lines?: unknown }).lines);
}
export async function POST(req: Request): Promise<Response> {
if (crossSite(req)) {
return Response.json({ error: '仅接受本站页面发起的解卦请求' }, { status: 403 });
}
const ip = clientIp(req);
if (rateLimited(ip)) {
return Response.json({ error: '请求过于频繁,请稍后再试' }, { status: 429 });
@@ -89,47 +116,82 @@ export async function POST(req: Request): Promise<Response> {
return Response.json({ error: 'facts 不合法:需要 kind 与其对应的盘面事实' }, { status: 400 });
}
const config = llmConfig();
const resolved = normalizeLlmRequest((body as { llm?: unknown })?.llm);
if (!resolved.ok) {
return Response.json({ error: resolved.error, configured: false }, { status: 400 });
}
const config: LlmRequestConfig | null = resolved.config;
if (config) {
const allowed = upstreamHostAllowed(config.baseUrl);
if (!allowed.ok) {
return Response.json({ error: allowed.error, configured: false }, { status: 403 });
}
}
if (!config) {
return Response.json(
{
error: '解卦服务未配置:请在服务端设置 LLM_API_KEY(可选 LLM_BASE_URL / LLM_MODEL)。客户端不会持有密钥。',
error: '还没有配置大模型:点右上角「设置」填入接口地址、模型与 API Key(只保存在本机浏览器)。',
configured: false,
},
{ status: 501 },
);
}
const { system, user } = buildReadingPrompt(facts);
const { system, user } = buildLiuyaoPrompt(facts);
let upstream: Response;
try {
upstream = await fetch(`${config.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${config.key}`,
},
body: JSON.stringify({
model: config.model,
stream: true,
temperature: 0.3,
max_tokens: 1600,
messages: [
{ role: 'system', content: system },
{ role: 'user', content: user },
],
}),
signal: AbortSignal.timeout(120_000),
});
} catch (e) {
return Response.json({ error: `上游模型不可达:${(e as Error).message}` }, { status: 502 });
const requestBody = JSON.stringify(
buildChatRequestBody({
model: config.model,
// 整份规范约 36k token:若模型默认开思考,会把输出预算全吃掉(实测 content 为空、finish_reason=length)。
// 本产品只要 400–550 字正文,默认关闭思考;用户在「设置」里显式开启才传 enabled。
thinking: config.thinking ?? 'disabled',
reasoningEffort: config.reasoningEffort,
messages: [
{ role: 'system', content: system },
{ role: 'user', content: user },
],
}),
);
/**
* 36k token 的前缀在网关满载时会被拒(429 / prefill_cap_refused / overloaded),属于瞬时错误。
* 在服务端重试(间隔 2.5s、6s)比让用户手动重点体验好;此时还没开始流式输出,重试是安全的。
*/
// 网关在长前缀满载时给的建议是 "retry after 30 s",所以间隔按 5s / 20s 起步;
// 若上游消息里给了 "after N s",以它为准(上限 35s)。
const RETRY_DELAYS = [5_000, 20_000];
let upstream: Response | null = null;
let lastError = '';
for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt += 1) {
try {
upstream = await fetch(`${config.baseUrl}/chat/completions`, {
method: 'POST',
headers: buildProviderHeaders(config.baseUrl, config.key),
body: requestBody,
signal: AbortSignal.timeout(120_000),
});
} catch (e) {
return Response.json({ error: `上游模型不可达:${(e as Error).message}` }, { status: 502 });
}
if (upstream.ok && upstream.body) break;
lastError = await upstream.text().catch(() => '');
if (!shouldRetryUpstream(upstream.status, lastError) || attempt === RETRY_DELAYS.length) {
return new Response(
`data: ${JSON.stringify({ error: friendlyUpstreamError(upstream.status, lastError) })}\n\n`,
{ status: 200, headers: { 'Content-Type': 'text/event-stream; charset=utf-8' } },
);
}
const hinted = Number(/after\s+(\d{1,2})\s*s/i.exec(lastError)?.[1] ?? 0);
const waitMs = hinted > 0 ? Math.min(hinted * 1000, 35_000) : RETRY_DELAYS[attempt];
await new Promise((r) => setTimeout(r, waitMs));
}
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => '');
if (!upstream || !upstream.ok || !upstream.body) {
return new Response(
`data: ${JSON.stringify({ error: `上游模型返回 ${upstream.status}:${text.slice(0, 200)}` })}\n\n`,
`data: ${JSON.stringify({ error: friendlyUpstreamError(429, lastError) })}\n\n`,
{ status: 200, headers: { 'Content-Type': 'text/event-stream; charset=utf-8' } },
);
}
@@ -147,6 +209,24 @@ export async function POST(req: Request): Promise<Response> {
/* 客户端断开 */
}
};
const sendComment = (text: string) => {
try {
controller.enqueue(encoder.encode(`: ${text}\n\n`));
} catch {
/* 客户端断开 */
}
};
// 思考模式首字可能要几十秒,中间任何一跳(浏览器/代理/网关)都可能因空闲断流。
// SSE 注释帧不进入客户端解析,只用来保持连接;顺带把「还在想」告诉前端。
let lastActivity = Date.now();
const heartbeat = setInterval(() => {
if (Date.now() - lastActivity > 8_000) {
lastActivity = Date.now();
sendComment('keep-alive');
}
}, 8_000);
sendComment('open');
let buffer = '';
const reader = upstreamBody.getReader();
@@ -169,7 +249,10 @@ export async function POST(req: Request): Promise<Response> {
try {
const json = JSON.parse(data);
const content = json?.choices?.[0]?.delta?.content;
if (typeof content === 'string' && content) send({ content });
if (typeof content === 'string' && content) {
lastActivity = Date.now();
send({ content });
}
} catch {
/* 上游心跳/非 JSON 行,忽略 */
}
@@ -180,6 +263,7 @@ export async function POST(req: Request): Promise<Response> {
} catch (e) {
send({ error: (e as Error).message });
} finally {
clearInterval(heartbeat);
try {
controller.close();
} catch {
+2 -2
View File
@@ -2,8 +2,8 @@ import type { Metadata } from 'next';
import CasesView from '@/components/cases/CasesView';
export const metadata: Metadata = {
title: '卦例夹 | 六爻 · 小成图',
description: '保存在本机的六爻与小成图卦例:只存起卦输入,打开时由确定性引擎重排同一卦。',
title: '历史排盘 | 野鹤六爻',
description: '六爻的历史排盘:只存起卦输入,打开时由确定性引擎重排同一卦。',
};
export default function CasesPage() {
+56
View File
@@ -0,0 +1,56 @@
import type { Metadata } from 'next';
import SiteHeader from '@/components/site/SiteHeader';
export const metadata: Metadata = {
title: '易学典籍 | 六爻',
description: '周易经传与易学文献的阅读入口;原文与来源校核后逐步整理。',
};
const shelves = [
{ title: '《周易》', subtitle: '六十四卦 · 卦辞 · 爻辞', status: '待校录' },
{ title: '十翼', subtitle: '彖传 · 象传 · 系辞 · 说卦', status: '待校录' },
{ title: '象数易学', subtitle: '先后天八卦 · 河洛 · 纳甲', status: '整理中' },
{ title: '六爻古籍', subtitle: '卜筮正宗 · 增删卜易 · 古筮真诠', status: '待校录' },
];
export default function ClassicsPage() {
return (
<div className="min-h-screen bg-[#F4F1E8] text-[#38423C]">
<SiteHeader active="classics" />
<main className="mx-auto w-full max-w-[920px] px-4 pb-20 pt-14 sm:px-7 sm:pt-20">
<div className="text-center">
<div className="mb-4 flex items-center justify-center gap-3 font-kai text-[11px] tracking-[0.28em] text-[#98784A]">
<span className="h-px w-8 bg-[#B89C6C]/70" />
观象 · 寻源 · 校文
<span className="h-px w-8 bg-[#B89C6C]/70" />
</div>
<h1 className="font-song text-[30px] font-semibold tracking-[0.18em] text-[#304239] sm:text-[34px]">易学典籍</h1>
<p className="mx-auto mt-3 max-w-[620px] font-song text-[13px] leading-[2] tracking-[0.04em] text-[#756E5F]">
周易经传与象数文献的阅读空间。原文、版本与出处校核后再入库,不以模型转述代替原典。
</p>
</div>
<div className="mt-10 grid gap-x-5 gap-y-1 sm:grid-cols-2">
{shelves.map((s, i) => (
<section key={s.title} className="group border-b border-[#D8D0BE] px-2 py-5 sm:px-4">
<div className="flex items-baseline justify-between gap-3">
<div className="flex items-baseline gap-3">
<span className="font-kai text-[11px] text-[#B49B6B]">{String(i + 1).padStart(2, '0')}</span>
<h2 className="font-song text-[18px] font-semibold tracking-[0.06em] text-[#35443D]">{s.title}</h2>
</div>
<span className="font-kai text-[10.5px] text-[#A4977E]">{s.status}</span>
</div>
<p className="mt-2 pl-8 text-[12px] text-[#7A766A]">{s.subtitle}</p>
</section>
))}
</div>
<div className="mx-auto mt-10 max-w-[620px] border-l-2 border-[#B08A4D]/60 pl-4 font-song text-[12px] leading-[2] text-[#7D7565]">
<p>典籍内容正在按来源与版本逐条整理。</p>
<p>后续会标注篇卷、版本与页码;未能核验的文字不作为确定引文展示。</p>
</div>
</main>
</div>
);
}
+12
View File
@@ -0,0 +1,12 @@
import type { Metadata } from 'next';
import DesignPreview from '@/components/design/DesignPreview';
/** 设计稿仅供评审:不进索引 */
export const metadata: Metadata = {
title: '设计稿 · 六爻',
robots: { index: false, follow: false },
};
export default function DesignPage() {
return <DesignPreview />;
}
+12
View File
@@ -0,0 +1,12 @@
import type { Metadata } from 'next';
import ExamplesView from '@/components/examples/ExamplesView';
export const metadata: Metadata = {
title: '案例 · 增删卜易卦例 | 野鹤六爻',
description:
'《增删卜易》卦例 100 例:据朱辰彬《增删卜易卦例初探》整理文本抽取,含古筮知识、原注与用神 / 吉凶 / 应期要点,供对照研读。',
};
export default function ExamplesPage() {
return <ExamplesView />;
}
+260 -42
View File
@@ -1,39 +1,103 @@
@import "tailwindcss";
/* ==========================================================================
宣纸米白 / 暖墨字 / 朱砂强调 —— 与 bazi-web 同一套版式语汇的裁剪版。
只保留三块用得到的东西:设计令牌、矢量爻象、铜钱翻滚动画。
设计系统 v2 —— 雾霾蓝 · 墨 · 赭金(配一点朱砂)
取自参考封面:底 #9FB4BD / 墨字 #333D42 / 赭金纹样 #8A6A3A
用于 App 时提亮为浅雾蓝,赭金与朱砂负责"点睛",避免全冷色滑向医院感。
字体策略:正文系统无衬线;卦名、标题用宋/楷,靠字形对比而非花字。
========================================================================== */
@theme inline {
--color-paper: #f7f3ea;
--color-paper-card: #fffdf8;
--color-ink: #22201b;
--color-ink-soft: #5e5a50;
--color-cinnabar: #8e3a2c;
--color-gold: #9c7a3c;
@theme {
/* ── 底与面:雾蓝做"水",纸做"面",两者分工,不再糊成一片灰 ── */
--color-water-1: #E2EAED; /* 页底:雾蓝,略压深以拉开与纸卡的层次 */
--color-water-2: #DCE6E9;
--color-water-3: #CBD9DE;
--color-paper-0: #FFFEF9; /* 纸面:纯暖白,与雾蓝底拉开明度差 */
--color-paper-1: #F6F3EA;
--color-paper-2: #EDE8DB;
--color-line: #DCD5C5; /* 纸上的发丝线偏暖 */
--color-line-strong: #C0B8A4;
/* ── 墨 ── */
--color-ink-900: #141C22;
--color-ink-800: #1F2A31;
--color-ink-700: #33424A;
--color-ink-600: #4A5D66;
--color-ink-500: #667A83;
--color-ink-400: #97A9B0;
/* ── 主色:青黛(比雾蓝更沉、更清),用作强调线与选中态 ── */
--color-mist-300: #A9C3CB;
--color-mist-400: #8AACB6;
--color-mist-500: #6C94A0;
--color-mist-600: #4F7C8A;
--color-mist-700: #3D6673;
--color-mist-900: #244450;
/* ── 赭石:唯一的热色,用于用神/印章/主按钮边 ── */
--color-gold-200: #EFE2C9;
--color-gold-300: #D9BC8A;
--color-gold-500: #A9713F;
--color-gold-600: #8E582B;
/* ── 朱砂:动爻 ── */
--color-cinnabar-300: #D08C7C;
--color-cinnabar-500: #A8402F;
--color-cinnabar-600: #8F3323;
--color-jade-500: #3F6B55;
--font-sans-cn: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", "Hiragino Sans GB", system-ui, sans-serif;
--font-song: "Songti SC", "Noto Serif SC", "Source Han Serif SC", "SimSun", serif;
--font-kai: "Kaiti SC", "KaiTi", "STKaiti", "Songti SC", serif;
--radius-xs: 2px;
--radius-sm: 4px;
--radius-md: 6px;
--radius-lg: 10px;
--ease-out-soft: cubic-bezier(0.16, 1, 0.3, 1);
}
:root {
--bg: #f7f3ea;
--surface: #fffdf8;
--ink: #17140f;
--muted: #5c5449;
--faint: #8c8272;
--line: #e0d8c9;
--accent: #a5342b;
--accent-soft: #f2e3dc;
/* 语义别名 */
--bg: #E2EAED;
--bg-sunken: #DCE6E9;
--surface: #FFFEF9;
--surface-raised: #FFFFFF;
--ink: #141C22;
--ink-soft: #53666F;
--ink-faint: #74878F;
--hairline: #D8D2C2;
--primary: #4F7C8A;
--primary-deep: #244450;
--accent: #8E582B;
--accent-tint: #F3E9D8;
--danger: #8F3323;
--ok: #3F6B55;
/* HexagramSvg 依赖的别名 */
--yao-yang: #141C22;
--yao-yin: #6C94A0;
--yao-moving: #8F3323;
/* 兼容旧令牌 */
--yi-bg: var(--bg);
--yi-surface: var(--surface);
--yi-ink: var(--ink);
--yi-muted: var(--muted);
--yi-faint: var(--faint);
--yi-line: var(--line);
--yi-accent: var(--accent);
--yi-accent-soft: var(--accent-soft);
--yi-muted: var(--ink-soft);
--yi-faint: var(--ink-faint);
--yi-line: var(--hairline);
--yi-accent: var(--danger);
--yi-accent-soft: #F3E4E1;
}
/* 宣纸米皮肤(备选):把"水"也换成纸 */
[data-skin='paper'] {
--color-water-1: #EFEADC;
--color-water-2: #E4DDCB;
--color-water-3: #D6CDB8;
--bg: #EFEADC;
--bg-sunken: #E4DDCB;
}
html,
@@ -43,9 +107,54 @@ body {
}
body {
font-family: "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Segoe UI", sans-serif;
font-family: var(--font-sans-cn);
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
-webkit-tap-highlight-color: transparent;
overscroll-behavior-y: none;
}
/* 手机端细节:安全区、禁双击缩放、滚动惯性 */
.safe-bottom {
padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
}
.safe-top {
padding-top: env(safe-area-inset-top, 0px);
}
.no-scrollbar {
scrollbar-width: none;
-ms-overflow-style: none;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
/* 细分隔线:0.5px 观感,替代卡片描边 */
.hair-t {
border-top: 1px solid var(--hairline);
}
.hair-b {
border-bottom: 1px solid var(--hairline);
}
/* 触控目标下限(Android 无障碍建议 ≥48dp) */
.tap {
min-height: 44px;
min-width: 44px;
}
/* 按压反馈:App 手感,不用 hover 依赖 */
.press {
transition: transform 120ms var(--ease-out-soft), background-color 150ms ease, border-color 150ms ease,
color 150ms ease;
}
.press:active {
transform: scale(0.975);
}
input::placeholder,
@@ -138,19 +247,63 @@ textarea::placeholder {
.hex.stagger .line { animation: none; }
}
/* 一横 / 两短横的吉凶形制(小成图九宫用) */
.verdict-mark {
display: inline-flex;
width: 9px;
gap: 2px;
height: 2px;
flex-shrink: 0;
/* 站名艺术字:马善政毛笔楷书,只子集「野鹤六爻」四字(2.7KB,OFL-1.1,见 public/fonts/OFL-MaShanZheng.txt) */
@font-face {
font-family: 'YeheBrand';
src: url('/fonts/yehe-brand.woff2') format('woff2');
font-weight: 400;
font-style: normal;
font-display: swap;
unicode-range: U+516D, U+723B, U+91CE, U+9E64;
}
.verdict-mark span {
height: 2px;
flex: 1;
border-radius: 1px;
background: currentColor;
.font-brand {
font-family: 'YeheBrand', 'STXingkai', '华文行楷', 'FZShuTi', 'STKaiti', 'KaiTi', serif;
font-weight: 400;
}
/* 案例页卦盘:表头与数据行共用同一套列宽(有伏神时多一列,窄屏收起该列) */
.ex-grid {
display: grid;
column-gap: 4px;
align-items: center;
grid-template-columns: 28px 34px 74px 18px 22px 34px 74px 18px;
}
.ex-grid[data-hidden='1'] {
grid-template-columns: 28px 56px 34px 74px 18px 22px 34px 74px 18px;
}
@media (max-width: 639px) {
.ex-grid[data-hidden='1'] {
grid-template-columns: 28px 34px 74px 18px 22px 34px 74px 18px;
}
}
/* 隐藏原生日期选择器图标(起卦时间改用「修改」文字按钮唤起) */
.no-native-picker::-webkit-calendar-picker-indicator {
display: none;
}
.no-native-picker::-webkit-inner-spin-button {
display: none;
}
/* 研墨中:一滴墨落纸,涟漪两圈(解卦等待态用) */
@keyframes ink-ripple {
0% { transform: scale(0.55); opacity: 0.55; }
70% { transform: scale(1.55); opacity: 0; }
100% { transform: scale(1.55); opacity: 0; }
}
@keyframes ink-drop {
0%, 100% { transform: scale(1); opacity: 0.9; }
50% { transform: scale(1.25); opacity: 0.55; }
}
.ink-ripple {
animation: ink-ripple 1.8s ease-out infinite;
}
.ink-drop {
animation: ink-drop 1.8s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.ink-ripple { animation: none; opacity: 0; }
.ink-drop { animation: none; }
}
/* 基础按钮(CastWorkbench 依赖 .btn / .btn.primary) */
@@ -177,12 +330,13 @@ textarea::placeholder {
.btn:hover { border-color: var(--accent); color: var(--accent); }
.btn.primary {
background: var(--accent);
border-color: var(--accent);
color: #fffdf8;
background: #1F2A30;
border-color: #1F2A30;
color: #FBFBF7;
letter-spacing: 0.06em;
}
.btn.primary:hover { background: #8d2a22; border-color: #8d2a22; color: #fffdf8; }
.btn.primary:hover { background: #2C3A42; border-color: #2C3A42; color: #FBFBF7; }
.btn:disabled,
.btn[aria-disabled='true'] { opacity: 0.45; cursor: default; }
@@ -190,10 +344,74 @@ textarea::placeholder {
.btn.primary:disabled,
.btn.primary[aria-disabled='true'] {
opacity: 1;
background: var(--accent-soft);
color: var(--accent);
background: #E4EBED;
color: #7C9099;
border-color: transparent;
}
.btn.sm { padding: 9px 16px; font-size: 13.5px; }
.btn.block { width: 100%; }
/* --------------------------------------------------------------------------
皮肤:雾蓝(默认)/ 宣纸米(备选)
Tailwind 4 的 bg-* 工具类引用 var(--color-*),所以覆盖这些变量即可整体换肤。
-------------------------------------------------------------------------- */
[data-skin='paper'] {
--color-paper-0: #FDFCF7;
--color-paper-1: #F4F3EE;
--color-paper-2: #EAE8E0;
--color-paper-3: #DFDCD1;
--color-line: #DFD9CB;
--color-line-strong: #C9C1AE;
--color-ink-900: #23201A;
--color-ink-800: #332F27;
--color-ink-700: #4A4438;
--color-ink-600: #5E574B;
--color-ink-500: #7D7565;
--color-mist-300: #C6CBBE;
--color-mist-400: #A8B0A2;
--color-mist-500: #8A9686;
--color-mist-600: #6F7D6E;
--color-mist-700: #5C6A5C;
--color-mist-900: #3D4A3F;
--bg: #F4F3EE;
--bg-sunken: #EAE8E0;
--surface: #FDFCF7;
--hairline: #DFD9CB;
}
/* 铜钱尺寸:与原项目一致(移动 74、宽屏 84);源图 85×85,别再放大以免糊 */
.coin-size {
width: 74px;
height: 74px;
}
@media (min-width: 640px) {
.coin-size {
width: 84px;
height: 84px;
}
}
/* 铜钱翻滚:3D 翻转 + 轻微抛起;时长与落地由组件控制(animationend 后才定格) */
@keyframes coin-toss {
0% { transform: translateY(0) rotateX(0deg) rotateY(0deg); }
28% { transform: translateY(-26px) rotateX(220deg) rotateY(360deg); }
55% { transform: translateY(-6px) rotateX(420deg) rotateY(720deg); }
78% { transform: translateY(-14px) rotateX(560deg) rotateY(980deg); }
100% { transform: translateY(0) rotateX(720deg) rotateY(1080deg); }
}
.coin-spin {
animation: coin-toss 900ms cubic-bezier(0.24, 0.8, 0.28, 1) both;
will-change: transform;
}
@media (prefers-reduced-motion: reduce) {
.coin-spin {
animation: none;
}
}
+27 -9
View File
@@ -1,22 +1,40 @@
import type { Metadata } from 'next';
import type { Metadata, Viewport } from 'next';
import './globals.css';
import ServiceWorkerRegister from '@/components/site/ServiceWorkerRegister';
export const metadata: Metadata = {
title: '六爻 · 小成图 | 确定性排盘',
title: '野鹤六爻 | 确定性排盘',
description:
'六爻纳甲确定性排盘(纳甲装卦、安世应、定六亲、旬空、伏神、天医文昌神煞)与霍氏小成图九宫排盘(四象八断、正推气路)。不含意图推断与大模型解卦。',
'三钱摇卦与纳甲排盘,排盘由确定性引擎计算,解读依盘面事实展开;易学典籍将逐步整理校核。',
applicationName: '野鹤六爻',
appleWebApp: {
capable: true,
title: '野鹤六爻',
statusBarStyle: 'default',
},
icons: {
icon: [
{ url: '/icons/icon-192.png', sizes: '192x192', type: 'image/png' },
{ url: '/icons/icon-512.png', sizes: '512x512', type: 'image/png' },
],
apple: [{ url: '/icons/apple-touch-icon.png', sizes: '180x180', type: 'image/png' }],
},
formatDetection: { telephone: false },
};
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
viewportFit: 'cover',
themeColor: '#F7F4EF',
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="zh-CN" className="h-full">
<body className="flex min-h-full flex-col bg-[#f7f3ea] text-[#22201b] antialiased">
<body className="flex min-h-full flex-col bg-[#F4F1E8] text-[#38423C] antialiased">
<main className="flex flex-1 flex-col">{children}</main>
<footer className="border-t border-[#E4DCCB] px-4 py-6 text-center font-serif text-[10.5px] leading-relaxed text-[#8c8272]">
六爻 · 小成图 —— 仅做确定性排盘:不取用神、不判吉凶、不调大模型
<br />
排盘逻辑移植自 bazi-web(六爻 core.py / 小成图 lib/xct),已裁剪意图引擎与五层 DAG
</footer>
<ServiceWorkerRegister />
</body>
</html>
);
+31
View File
@@ -0,0 +1,31 @@
import type { MetadataRoute } from 'next';
/**
* PWA 清单:不加应用商店,直接用「添加到主屏」的安装体验。
* 图标由 app/icon.svg 渲染而来(public/icons/*),display: standalone 让打开后没有地址栏。
*/
export default function manifest(): MetadataRoute.Manifest {
return {
name: '野鹤六爻',
short_name: '野鹤六爻',
description: '三钱摇卦与纳甲排盘:确定性排盘、四段解读,可离线起卦。',
start_url: '/',
scope: '/',
display: 'standalone',
orientation: 'portrait',
lang: 'zh-CN',
dir: 'ltr',
background_color: '#F7F4EF',
theme_color: '#F7F4EF',
categories: ['lifestyle', 'education'],
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
shortcuts: [
{ name: '案例', short_name: '案例', url: '/examples' },
{ name: '历史排盘', short_name: '历史', url: '/cases' },
],
};
}
+4 -80
View File
@@ -1,87 +1,11 @@
import type { Metadata } from 'next';
import Link from 'next/link';
import CastPage from '@/components/cast/CastPage';
export const metadata: Metadata = {
title: '六爻 · 小成图 | 确定性排盘',
title: '野鹤六爻 · 三钱摇卦',
description: '三钱摇卦或手动指定卦象,纳甲装卦、安世应、定六亲,再依盘面事实作四段解读。',
};
const ENTRIES = [
{
href: '/liuyao',
title: '六爻排盘',
seal: '爻',
lines: ['三钱摇卦 / 大衍筮法 / 手工录入', '纳甲装卦 · 安世应 · 定六亲', '旬空 · 伏神 · 六神 · 天医文昌'],
note: '只排盘,不推断',
},
{
href: '/xct',
title: '小成图',
seal: '图',
lines: ['天地数 / 时间 / 自定选卦', '八宫天盘 · 中宫归藏', '四象八断 · 正推气路'],
note: '只盘面,不解卦',
},
];
export default function HomePage() {
return (
<div className="mx-auto w-full max-w-[720px] px-4 pb-24 pt-14 sm:pt-20">
<header className="text-center">
<div className="mx-auto mb-5 flex h-11 w-11 items-center justify-center rounded-[3px] border border-[#8e3a2c]/45 font-serif text-[19px] text-[#8e3a2c]">
易
</div>
<h1 className="font-serif text-[27px] font-semibold tracking-[0.22em] text-[#22201b] sm:text-[31px]">
六爻 · 小成图
</h1>
<p className="mt-2.5 font-serif text-[12px] tracking-[0.16em] text-[#7c7365]">
确定性排盘 —— 卦象由投掷与时间决定,不由解释决定
</p>
</header>
<div className="mt-9 grid gap-3.5 sm:grid-cols-2">
{ENTRIES.map((e) => (
<Link
key={e.href}
href={e.href}
className="group relative flex flex-col rounded-[4px] border border-[#E0D8C9] bg-[#FFFDF8] p-5 transition-all hover:-translate-y-[1px] hover:border-[#c9b99a] hover:shadow-[0_6px_20px_rgba(23,20,15,0.06)]"
>
<div className="flex items-baseline justify-between">
<h2 className="font-serif text-[17px] font-semibold tracking-[0.12em] text-[#22201b]">{e.title}</h2>
<span className="flex h-7 w-7 items-center justify-center rounded-[2px] border border-[#8e3a2c]/35 font-serif text-[12px] text-[#8e3a2c]">
{e.seal}
</span>
</div>
<ul className="mt-3 space-y-1.5 font-serif text-[11.5px] leading-relaxed text-[#5e5a50]">
{e.lines.map((l) => (
<li key={l} className="flex gap-1.5">
<span className="text-[#cbbfa8]">·</span>
<span>{l}</span>
</li>
))}
</ul>
<div className="mt-4 flex items-center justify-between border-t border-[#EFE7D8] pt-2.5">
<span className="font-serif text-[10.5px] tracking-[0.1em] text-[#9c7a3c]">{e.note}</span>
<span className="font-serif text-[11.5px] text-[#5e5a50] transition-colors group-hover:text-[#8e3a2c]">
进入 →
</span>
</div>
</Link>
))}
</div>
<p className="mx-auto mt-10 max-w-[520px] text-center font-serif text-[10.5px] leading-relaxed text-[#93897a]">
两个工具都只输出可核查的排盘事实:六爻给纳甲与世界应、旬空神煞;小成图给九宫天盘与四象八断。
问句只作记录,不参与任何计算。
</p>
<div className="mt-5 text-center">
<Link
href="/cases"
className="inline-flex items-center gap-1.5 rounded-[2px] border border-[#D9CDB6] px-3 py-1.5 font-serif text-[11.5px] text-[#5e5a50] transition-colors hover:border-[#c9b99a] hover:text-[#22201b]"
>
卦例夹
<span className="text-[10px] text-[#93897a]">本机保存的卦例</span>
</Link>
</div>
</div>
);
return <CastPage />;
}
-12
View File
@@ -1,12 +0,0 @@
import type { Metadata } from 'next';
import XiaoChengTuView from '@/components/xct/XiaoChengTuView';
export const metadata: Metadata = {
title: '小成图排盘 · 四象八断 | 确定性排盘',
description:
'霍氏小成图:天地数 / 梅花时间 / 自定选卦起局,布八宫天盘、立中宫归藏,按阖辟往来与阴阳得配作四象八断,并追踪正推气路。',
};
export default function XctPage() {
return <XiaoChengTuView />;
}
+24
View File
@@ -1,5 +1,21 @@
import { bindings, defineConfig, defineWorker } from "cf/config";
// 本地开发:把 shell 里给出的变量映射成文本绑定,nodejs_compat 会再映射到 process.env。
// 生产环境用 cf/wrangler 的 secret 注入,不经过这里。
// 自有域名:部署时用环境变量指定,例如
// WORKER_DOMAIN=liuyao.example.com WORKER_ZONE=example.com npx cf deploy
// 不设就只挂 *.workers.dev(首次部署时 cf 会问一次子域名)。
// 上游白名单:默认收紧到常用供应商(想加自建网关就改这一行,或用 LLM_ALLOWED_HOSTS 覆盖)
const LLM_ALLOWED_DEFAULT =
"opencode.ai,deepseek.com,api.openai.com,api.moonshot.cn,open.bigmodel.cn,dashscope.aliyuncs.com,openrouter.ai,api.siliconflow.cn";
const workerDomain = process.env.WORKER_DOMAIN;
const devText = (name: string) => {
const value = typeof process !== "undefined" ? process.env[name] : undefined;
return value ? bindings.text(value) : undefined;
};
export default defineConfig({
worker: defineWorker({
name: "liuyao",
@@ -11,9 +27,17 @@ export default defineConfig({
notFoundHandling: "none",
runWorkerFirst: ["/*", "!/_next/static/*", "!/*/_next/static/*"],
},
// 自有域名用 Custom Domain:会自动建 DNS 记录与证书(triggers.fetch 的路由不会自动建 DNS)
...(workerDomain ? { domains: [workerDomain] } : {}),
env: {
ASSETS: bindings.assets(),
DB: bindings.d1({ name: "liuyao-db" }),
ADMIN_PASSWORD: devText("ADMIN_PASSWORD"),
ADMIN_SESSION_SECRET: devText("ADMIN_SESSION_SECRET"),
LLM_API_KEY: devText("LLM_API_KEY"),
LLM_ALLOWED_HOSTS: devText("LLM_ALLOWED_HOSTS") ?? bindings.text(LLM_ALLOWED_DEFAULT),
LLM_BASE_URL: devText("LLM_BASE_URL"),
LLM_MODEL: devText("LLM_MODEL"),
},
}),
});
+25 -18
View File
@@ -1,7 +1,7 @@
'use client';
/**
* 卦例夹:本地保存的卦例列表。
* 历史排盘:本地保存的排盘记录列表。
*
* 现在读的是 localStorage(lib/store 的本地实现);换成 D1 后这个组件不用改,
* 因为 getCaseStore() 返回的接口本来就是异步的。
@@ -10,20 +10,23 @@
import React, { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { Star, Trash2 } from 'lucide-react';
import SiteHeader from '@/components/site/SiteHeader';
import { getCaseStore } from '@/lib/store';
import { caseTimeLabel } from '@/lib/cases/record';
import type { CaseRecord } from '@/lib/store/types';
const KIND_LABEL: Record<CaseRecord['kind'], string> = { liuyao: '六爻', xct: '小成图' };
const KIND_LABEL: Record<CaseRecord['kind'], string> = { liuyao: '六爻' };
export default function CasesView() {
const [items, setItems] = useState<CaseRecord[] | null>(null);
const [mode, setMode] = useState<'local' | 'remote'>('local');
const [error, setError] = useState('');
const load = useCallback(async () => {
try {
const list = await getCaseStore().list();
setItems(list);
const store = await getCaseStore();
setMode(store.mode ?? 'local');
setItems(await store.list());
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
setItems([]);
@@ -35,7 +38,8 @@ export default function CasesView() {
}, [load]);
const toggleFavorite = async (record: CaseRecord) => {
await getCaseStore().setFavorite(record.id, !record.favorite);
const store = await getCaseStore();
await store.setFavorite(record.id, !record.favorite);
await load();
};
@@ -43,25 +47,30 @@ export default function CasesView() {
if (!window.confirm(`删除这条卦例?\n\n${record.summary.primary}${record.summary.changed ? ` → ${record.summary.changed}` : ''}`)) {
return;
}
await getCaseStore().remove(record.id);
const store = await getCaseStore();
await store.remove(record.id);
await load();
};
return (
<div className="mx-auto w-full max-w-[760px] px-3 pb-24 pt-6 font-serif sm:px-5 sm:pt-9">
<div className="min-h-screen bg-[#F4F1E8] text-[#38423C]">
<SiteHeader maxWidthClassName="max-w-[820px]" />
<div className="mx-auto w-full max-w-[760px] px-3 pb-24 pt-7 font-serif sm:px-5 sm:pt-9">
<header className="mb-5 flex items-center justify-between gap-3">
<div className="flex items-baseline gap-2.5">
<span className="inline-block h-[5px] w-[5px] rounded-full bg-[#8E3A2C]" />
<h1 className="text-[19px] font-semibold tracking-[0.16em] text-[#22201b] sm:text-[21px]">卦例夹</h1>
<h1 className="text-[19px] font-semibold tracking-[0.16em] text-[#22201b] sm:text-[21px]">历史排盘</h1>
</div>
<Link href="/" className="shrink-0 text-[11.5px] text-[#5e5a50] underline-offset-4 hover:text-[#8e3a2c] hover:underline">
返回首页
返回起卦
</Link>
</header>
<p className="mb-4 pl-[18px] text-[11.5px] leading-relaxed text-[#7c7365]">
只保存起卦输入(时间 / 投掷 / 起卦法),打开时由引擎重新排出同一卦。
目前存在本机浏览器;以后接 D1 可跨设备同步。
{mode === 'remote'
? '已保存到云端(按本机匿名声明的设备 ID 归属):换浏览器或清除 Cookie 会得到新的历史排盘。'
: '当前保存在本机浏览器;完整云端存储请用 npm run dev:vinext 或线上环境。'}
</p>
{error && (
@@ -74,16 +83,13 @@ export default function CasesView() {
{items && items.length === 0 && (
<div className="rounded-md border border-[#E0D8C9] bg-[#FFFDF8] px-5 py-12 text-center">
<p className="text-[13px] text-[#5e5a50]">还没有保存的卦例。</p>
<p className="text-[13px] text-[#5e5a50]">还没有排盘记录。</p>
<p className="mt-2 text-[11.5px] text-[#8c8272]">
起一卦后,在盘面右上角点「保存卦例」即可收藏到这里。
六爻解卦完成后会自动归档到这里;也可以从盘面右上角「截图」旁的历史入口回看。
</p>
<div className="mt-4 flex items-center justify-center gap-3 text-[12px]">
<Link href="/liuyao" className="rounded-[2px] border border-[#CBBFA8] px-3 py-1.5 text-[#5e5a50] hover:border-[#8a8378] hover:text-[#22201b]">
去起六爻
</Link>
<Link href="/xct" className="rounded-[2px] border border-[#CBBFA8] px-3 py-1.5 text-[#5e5a50] hover:border-[#8a8378] hover:text-[#22201b]">
去起小成图
<Link href="/" className="rounded-[2px] border border-[#CBBFA8] px-3 py-1.5 text-[#5e5a50] hover:border-[#8a8378] hover:text-[#22201b]">
去起一卦
</Link>
</div>
</div>
@@ -145,7 +151,7 @@ export default function CasesView() {
<Trash2 size={13} />
</button>
<Link
href={`/${r.kind === 'liuyao' ? 'liuyao' : 'xct'}?case=${r.id}`}
href={`/liuyao?case=${r.id}`}
className="ml-1 rounded-[2px] border border-[#CBBFA8] px-2.5 py-1.5 text-[11.5px] text-[#5e5a50] transition-colors hover:border-[#8a8378] hover:text-[#22201b]"
>
打开
@@ -156,6 +162,7 @@ export default function CasesView() {
))}
</ul>
)}
</div>
</div>
);
}
+467
View File
@@ -0,0 +1,467 @@
'use client';
/**
* 首页 · 起卦(按用户给的书卷风设计参考重做)
* =================================================
* 视觉:浅宣纸 + 墨色 + 赭金 + 一点黛绿/朱砂;淡墨山水只作背景,不压交互。
* 结构:顶部四入口 → 山水题签 → 一张完整纸笺(求测信息 / 三钱 / 进度 / 爻象 / 主按钮)。
* 移动端自然单列;PC 用宽纸笺与完整留白呈现,不是把手机布局硬拉宽。
*
* 起卦使用真实三枚 Web Crypto 币面。点数 8 显示「背背字」;每次掷钱的显示面就是实际随机面。
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Clock3, PenLine } from 'lucide-react';
import { Coin, type CoinSide } from '@/components/liuyao/Coin';
import GuaCombobox from './GuaCombobox';
import { Button } from '@/components/ui';
import { HexagramSvg } from '@/components/hexagram/HexagramSvg';
import { tossThree } from '@/lib/liuyao/random';
import { encodeCastState } from '@/lib/liuyao/cast-url';
import { castTimeInfo, nowTimeInput, parseTimeInput } from '@/lib/liuyao/ganzhi';
import { masksOf, movingLineNumbers } from '@/lib/hexagram/hex-math';
import type { CoinResult } from '@/components/liuyao/types';
import { SIXTY_FOUR_HEXAGRAMS } from '@/lib/liuyao/najia';
import InkLandscape from '@/components/site/InkLandscape';
import SiteHeader from '@/components/site/SiteHeader';
const POS_NAMES = ['初爻', '二爻', '三爻', '四爻', '五爻', '上爻'];
function lineDescription(sum: CoinResult): string {
switch (sum) {
case 6:
return '老阴 · 交(动)';
case 7:
return '少阳 · 单';
case 8:
return '少阴 · 拆';
case 9:
return '老阳 · 重(动)';
}
}
function facesForValue(sum: CoinResult): CoinSide[] {
switch (sum) {
case 6: return ['字', '字', '字'];
case 7: return ['背', '字', '字'];
case 8: return ['背', '背', '字'];
case 9: return ['背', '背', '背'];
}
}
export default function CastPage() {
const router = useRouter();
const [question, setQuestion] = useState('');
const [gender, setGender] = useState<'男' | '女'>('男');
const [timeInput, setTimeInput] = useState('');
const [autoTime, setAutoTime] = useState(true);
const [values, setValues] = useState<CoinResult[]>([]);
const [coins, setCoins] = useState<CoinSide[]>(['字', '背', '字']);
const [rolling, setRolling] = useState(false);
const [tossKey, setTossKey] = useState(0);
const [lastSum, setLastSum] = useState<CoinResult | null>(null);
const settleTimerRef = useRef<number | null>(null);
const timeInputRef = useRef<HTMLInputElement | null>(null);
const settledRef = useRef(false);
const [sheet, setSheet] = useState<'none' | 'manual' | 'choose'>('none');
const [benBinary, setBenBinary] = useState('111111');
const [zhiBinary, setZhiBinary] = useState('111111');
useEffect(() => {
setTimeInput(nowTimeInput());
return () => {
if (settleTimerRef.current) window.clearTimeout(settleTimerRef.current);
};
}, []);
const timeInfo = useMemo(() => {
if (!timeInput) return null;
try {
return castTimeInfo(parseTimeInput(autoTime ? nowTimeInput() : timeInput));
} catch {
return null;
}
}, [timeInput, autoTime]);
const castCount = values.length;
const complete = castCount === 6;
const last = castCount ? values[castCount - 1] : null;
const { primary, moving: movingMask } = masksOf(values);
const movingList = movingLineNumbers(values);
const baseName = complete
? SIXTY_FOUR_HEXAGRAMS[values.map((v) => (v === 7 || v === 9 ? '1' : '0')).join('')]?.name
: null;
const finishToss = useCallback(
(sum: CoinResult) => {
if (settledRef.current) return;
settledRef.current = true;
if (settleTimerRef.current) window.clearTimeout(settleTimerRef.current);
setRolling(false);
const next = [...values, sum];
setValues(next);
setLastSum(sum);
if (autoTime) setTimeInput(nowTimeInput());
if (next.length === 6) setSheet('choose');
},
[values, autoTime],
);
const doToss = useCallback(() => {
if (rolling || complete) return;
// 直接显示 Web Crypto 实际抽到的三枚币面,不从和值拼代表组合。
const faces = tossThree();
const sum = faces.reduce<number>((total, face) => total + face, 0) as CoinResult;
settledRef.current = false;
setCoins(faces.map((face) => (face === 2 ? '字' : '背')));
setLastSum(sum);
setTossKey((k) => k + 1);
setRolling(true);
// 以最后一枚 animationend 为主路径;reduced-motion/WebView 丢事件时用计时兜底。
settleTimerRef.current = window.setTimeout(() => finishToss(sum), 1250);
}, [rolling, complete, finishToss]);
const reset = () => {
if (settleTimerRef.current) window.clearTimeout(settleTimerRef.current);
settledRef.current = true;
setRolling(false);
setValues([]);
setCoins(['字', '背', '字']);
setLastSum(null);
setTossKey((k) => k + 1);
setSheet('none');
setAutoTime(true);
setTimeInput(nowTimeInput());
};
const manualMoving = useMemo(() => {
const out: number[] = [];
for (let i = 0; i < 6; i += 1) if (benBinary[i] !== zhiBinary[i]) out.push(i + 1);
return out;
}, [benBinary, zhiBinary]);
const manualStatic = manualMoving.length === 0;
const manualCommit = () => {
const bits = benBinary.split('');
const next = bits.map((b, i) => {
const isMoving = manualMoving.includes(i + 1);
const yang = b === '1';
if (!isMoving) return (yang ? 7 : 8) as CoinResult;
return (yang ? 9 : 6) as CoinResult;
});
setCoins(facesForValue(next[5]));
setValues(next);
setLastSum(next[5]);
setSheet('choose');
if (autoTime) setTimeInput(nowTimeInput());
};
const go = () => {
const qs = encodeCastState({
coins: values,
timeInput: autoTime ? nowTimeInput() : timeInput,
gender,
marital: 'unmarried',
question,
});
router.push(`/liuyao?${qs}`);
};
const titleName = complete
? SIXTY_FOUR_HEXAGRAMS[values.map((v) => (v === 7 || v === 9 ? '1' : '0')).join('')]?.name
: null;
return (
<div className="min-h-screen bg-[#F4F1E8] pb-24 text-[#38423C] sm:pb-0">
{/* 顶部导航:易林寻踪 · 六爻 / 古籍 / 历史排盘 */}
<SiteHeader active="liuyao" maxWidthClassName="max-w-[1200px]" />
{/* 山水题签:移动端不占首屏(首屏要放得下整张求测笺),PC 保留 */}
<section className="relative isolate hidden overflow-hidden sm:block">
<InkLandscape />
<div className="relative z-10 mx-auto flex min-h-[118px] w-full max-w-[1200px] flex-col items-center justify-center px-4 pb-5 pt-2 text-center lg:min-h-[136px] lg:pb-6">
<p className="font-kai text-[18px] tracking-[0.24em] text-[#8E6337] sm:text-[19px] lg:text-[22px]">
取象于天地,观变于阴阳
</p>
</div>
</section>
{/* 主纸笺:PC 扩展为宽幅宣纸,内容仍沿中轴排列 */}
<main className="relative z-10 mx-auto mt-3 w-full max-w-[960px] px-3 pb-16 sm:-mt-7 sm:px-5 lg:px-8">
<div
className="relative overflow-hidden bg-[#FCF9F0] px-4 py-5 sm:px-7 sm:py-7 lg:px-12 lg:py-9"
style={{ border: '1px solid rgba(179,160,125,0.52)', borderRadius: 14, boxShadow: '0 8px 30px rgba(64,69,60,0.10)' }}
>
{/* 纸面云纹水印 */}
<span className="pointer-events-none absolute right-5 top-10 select-none font-song text-[56px] text-[#D9CDAF]/25 sm:right-10 sm:text-[74px]" aria-hidden>
☁
</span>
{/* 求测信息 */}
<section className="relative z-10">
<label htmlFor="q" className="flex items-center gap-3 font-song text-[17px] font-semibold tracking-[0.08em] text-[#3C4038]">
<span className="h-6 w-[4px] bg-[#B08A4D]" />
所问何事
</label>
<input
id="q"
value={question}
onChange={(e) => setQuestion(e.target.value)}
maxLength={120}
placeholder="如:这个项目月底前能否落地"
className="mt-1.5 h-12 w-full border-0 border-b border-[#D7CDB8] bg-transparent px-7 font-song text-[16px] text-[#36423A] outline-none placeholder:text-[#A6A092] focus:border-[#8E6337]"
/>
<div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-3 border-b border-[#D7CDB8]/80 px-2 pb-4 sm:gap-x-7">
<div className="flex items-center gap-3">
<span className="font-song text-[13px] text-[#665F52]">性别</span>
<div className="flex items-center overflow-hidden rounded-full border border-[#D0C6B2]">
{(['男', '女'] as const).map((g) => (
<button
key={g}
type="button"
onClick={() => setGender(g)}
className={`press min-h-[36px] min-w-[54px] px-3 font-song text-[13px] transition-colors ${
gender === g ? 'bg-[#DDE4D8] text-[#334B40]' : 'bg-transparent text-[#8A8476]'
}`}
>
{g}
</button>
))}
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 px-2 py-4">
<Clock3 size={16} strokeWidth={1.6} className="text-[#98784A]" />
<span className="font-song text-[13px] text-[#665F52]">起卦</span>
<input
ref={timeInputRef}
type="datetime-local"
value={timeInput}
onChange={(e) => {
setAutoTime(false);
setTimeInput(e.target.value);
}}
className="no-native-picker h-9 max-w-[195px] border-0 bg-transparent p-0 font-mono text-[13px] tabular-nums text-[#534F45] outline-none"
/>
<button
type="button"
onClick={() => {
// 原生选择器图标被隐藏,这里显式唤起;不支持 showPicker 的浏览器退回聚焦
const el = timeInputRef.current;
if (!el) return;
el.focus();
if (typeof el.showPicker === 'function') {
try {
el.showPicker();
} catch {
/* 非用户手势等情况下浏览器会拒绝,忽略 */
}
}
}}
className="press inline-flex h-7 items-center rounded-[3px] border border-[#CBBFA8] px-2 font-song text-[11.5px] text-[#6E6A5C] transition-colors hover:border-[#9A7040] hover:text-[#8E6337]"
>
修改
</button>
{timeInfo && (
<span className="w-full pl-[29px] font-song text-[12px] tracking-[0.08em] text-[#786F5F] sm:w-auto sm:pl-0">
{timeInfo.ganzhiText}
</span>
)}
</div>
</section>
{/* 三钱 */}
<section className="relative z-10 border-t border-[#D7CDB8]/80 pt-4 sm:pt-5">
<div className="flex items-center justify-center gap-3 font-song text-[15px] tracking-[0.26em] text-[#4B5148]">
<span className="h-px w-7 bg-[#B89C6C]/70" />
三钱摇卦
<span className="h-px w-7 bg-[#B89C6C]/70" />
</div>
<div
className={`relative mx-auto mt-1 flex min-h-[112px] max-w-[490px] items-center justify-center gap-5 py-2 sm:min-h-[130px] sm:gap-7 ${!complete && !rolling ? 'cursor-pointer' : ''}`}
onClick={!complete && !rolling ? doToss : undefined}
role={!complete && !rolling ? 'button' : undefined}
aria-label={!complete && !rolling ? '掷钱' : undefined}
>
<svg className="pointer-events-none absolute inset-x-0 top-1/2 h-[118px] w-full -translate-y-1/2 sm:h-[136px]" viewBox="0 0 620 160" fill="none" aria-hidden="true">
<path d="M34 80 C78 22 181 12 307 26 C444 12 543 34 586 79 C552 125 451 146 311 132 C174 145 75 128 34 80Z" stroke="#B7A681" strokeOpacity=".26" strokeWidth="3" strokeDasharray="3 3" />
<path d="M49 82 C96 35 197 28 308 38 C425 27 522 43 570 79 C527 111 429 128 309 120 C192 132 96 115 49 82Z" stroke="#B7A681" strokeOpacity=".18" strokeWidth="1.5" />
</svg>
{coins.map((face, i) => (
<Coin
key={`${tossKey}-${castCount}-${i}`}
side={face}
rolling={rolling}
delayMs={i * 40}
rotateDeg={[-7, 4, -3][i] ?? 0}
onSettled={i === 2 && rolling && lastSum !== null ? () => finishToss(lastSum) : undefined}
/>
))}
</div>
<div className="mx-auto flex max-w-[520px] items-center justify-between gap-3 px-3">
<div className="flex min-w-0 items-center gap-3">
<div className="flex shrink-0 items-center gap-[9px]">
{Array.from({ length: 6 }, (_, i) => {
const v = values[i];
const yang = v === 7 || v === 9;
const isMoving = v === 6 || v === 9;
const filled = v !== undefined;
return (
<span key={i} className="relative flex h-[11px] w-[11px] items-center justify-center rounded-full border" style={{ borderColor: isMoving ? '#A8453C' : filled ? '#3E4640' : '#B8AD96' }} aria-label={`第${i + 1}爻${filled ? (yang ? ' 阳' : ' 阴') : ' 未起'}`}>
{filled && <span className="h-[5px] w-[5px] rounded-full" style={{ background: isMoving ? '#A8453C' : yang ? '#344039' : '#899A9D' }} />}
</span>
);
})}
</div>
<span className="truncate font-song text-[12px] tracking-[0.04em] text-[#577365]">
{last ? `${POS_NAMES[castCount - 1]} ${lineDescription(last)}` : '尚未掷钱'}
</span>
</div>
</div>
{/* 爻象生成台:移到钱下方 */}
<div className="mx-auto mt-4 max-w-[600px] border-t border-[#D7CDB8]/75 pt-3">
<div className="mb-2 flex items-center justify-center gap-3 font-song text-[12.5px] tracking-[0.28em] text-[#575A50]">
<span className="h-px w-6 bg-[#B89C6C]/65" />卦 象<span className="h-px w-6 bg-[#B89C6C]/65" />
</div>
<div className="flex justify-center py-2">
<div className="flex w-[190px] flex-col gap-[8px] sm:w-[230px]">
{Array.from({ length: 6 }, (_, idx) => {
const pos = 6 - idx;
const v = values[pos - 1];
const yang = v === 7 || v === 9;
const moving = v === 6 || v === 9;
const color = !v ? '#D7D1C4' : moving ? '#A8453C' : '#3E4640';
return (
<div key={pos} className="flex h-[6px] items-center justify-center gap-3">
<span className="w-5 text-right font-song text-[9px] text-[#9A8B70]">{POS_NAMES[pos - 1].replace('爻', '')}</span>
{yang ? (
<span className="h-[3px] w-[126px]" style={{ background: color }} />
) : (
<span className="flex w-[126px] justify-between gap-3">
<span className="h-[3px] flex-1" style={{ background: color }} />
<span className="h-[3px] flex-1" style={{ background: color }} />
</span>
)}
<span className="w-4 text-center font-song text-[9px] text-[#A8453C]">{moving ? (yang ? '○' : '×') : ''}</span>
</div>
);
})}
</div>
</div>
<p className="mt-1 text-center font-kai text-[11.5px] tracking-[0.1em] text-[#928774]">
自初爻起,自下而上{movingList.length ? ` · 动 ${movingList.map((p) => POS_NAMES[p - 1]).join('、')}` : ''}
</p>
</div>
{/* 墨绿漆面 + 赭金双边按钮(移动端改由底部悬浮条承载) */}
<div className="mx-auto mt-5 hidden max-w-[360px] items-stretch gap-2.5 sm:flex">
<div className="flex-1 rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_7px_rgba(96,76,43,0.16)]">
<button type="button" disabled={rolling || complete} onClick={doToss} className="press h-[50px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[17px] font-medium tracking-[0.4em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60">
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
</button>
</div>
<button
type="button"
onClick={() => setSheet('manual')}
className="press h-[50px] w-[76px] shrink-0 self-center rounded-[4px] border border-[#9C7A48] bg-[#FBF7EC] font-song text-[13px] tracking-[0.14em] text-[#3F4A42] shadow-[0_2px_7px_rgba(96,76,43,0.14)] transition-colors hover:border-[#8E6337] hover:text-[#8E6337]"
>
指定
</button>
</div>
<div className="mt-3 flex flex-col items-center gap-2.5">
{castCount > 0 && (
<button type="button" onClick={reset} className="press font-song text-[12px] text-[#6D746A] hover:text-[#8E6337]">
重新起卦
</button>
)}
</div>
</section>
</div>
</main>
{/* 手动指定卦 */}
{sheet === 'manual' && (
<div className="fixed inset-0 z-40 flex items-center justify-center overflow-y-auto bg-ink-900/30 px-3 backdrop-blur-[2px] sm:px-5" onClick={() => setSheet('none')}>
<div className="w-full max-w-[620px] overflow-y-auto rounded-md bg-paper-0 px-5 pb-6 pt-4 shadow-[0_0_30px_rgba(53,45,31,0.15)] sm:border sm:border-line-strong" style={{ maxHeight: '90vh' }} onClick={(e) => e.stopPropagation()}>
<div className="mb-4 flex items-center justify-between">
<h3 className="font-song text-[16px] font-semibold tracking-[0.12em] text-ink-900">手动指定卦象</h3>
<button type="button" onClick={() => setSheet('none')} className="press tap text-[12px] text-ink-500">关闭</button>
</div>
<GuaCombobox label="本卦" value={benBinary} onChange={setBenBinary} hint="输入卦名可筛选" />
<div className="mt-4">
<GuaCombobox label="变卦" value={zhiBinary} onChange={setZhiBinary} hint="本卦与变卦相同即静卦" />
</div>
<div className="mt-4 flex flex-wrap items-center justify-between gap-2 bg-[#F2EEE3] px-3 py-2.5 text-[12px] text-ink-700">
<span className="font-song">{SIXTY_FOUR_HEXAGRAMS[benBinary]?.name} 之 {SIXTY_FOUR_HEXAGRAMS[zhiBinary]?.name}</span>
<span className={manualStatic ? 'text-mist-700' : 'text-cinnabar-600'}>{manualStatic ? '静卦 · 宜变法立之卦' : `动爻 ${manualMoving.map((p) => POS_NAMES[p - 1]).join('、')}`}</span>
</div>
<div className="mt-4"><Button size="lg" block onClick={manualCommit} className="!bg-mist-900 hover:!bg-ink-900">确定此卦</Button></div>
</div>
</div>
)}
{/* 移动端:起卦按钮悬浮在底部,单手可及 */}
<div className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-[#D7CDB8] bg-[#F6F2E9]/95 px-4 pt-2.5 backdrop-blur-md sm:hidden">
<div className="mx-auto flex max-w-[420px] items-stretch gap-2.5">
<div className="flex-1 rounded-[6px] border border-[#9C7A48] p-[2px] shadow-[0_2px_10px_rgba(96,76,43,0.18)]">
<button
type="button"
disabled={rolling || complete}
onClick={doToss}
className="press h-[48px] w-full rounded-[4px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] font-song text-[16px] font-medium tracking-[0.36em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:cursor-not-allowed disabled:opacity-60"
>
{rolling ? '铜钱翻落' : complete ? '六爻已备' : '掷钱起爻'}
</button>
</div>
<button
type="button"
onClick={() => setSheet('manual')}
className="press h-[48px] w-[72px] shrink-0 self-center rounded-[4px] border border-[#9C7A48] bg-[#FBF7EC] font-song text-[13px] tracking-[0.14em] text-[#3F4A42] shadow-[0_2px_7px_rgba(96,76,43,0.14)] transition-colors hover:border-[#8E6337] hover:text-[#8E6337]"
>
指定
</button>
</div>
</div>
{/* 卦成:直接进六爻排盘 */}
{sheet === 'choose' && (
<div className="fixed inset-0 z-40 flex items-center justify-center bg-ink-900/30 px-3 backdrop-blur-[2px] sm:px-5" onClick={() => setSheet('none')}>
<div className="w-full max-w-[440px] border border-[#CDBB96] bg-[#FCF8EF] px-5 pb-6 pt-5 shadow-[0_18px_50px_rgba(53,45,31,0.22)]" style={{ borderRadius: 10 }} onClick={(e) => e.stopPropagation()}>
<div className="mb-4 flex items-start justify-between gap-3">
<div>
<p className="font-kai text-[10.5px] tracking-[0.18em] text-[#9A805A]">卦象已成</p>
<h3 className="mt-1 font-song text-[20px] font-semibold tracking-[0.1em] text-ink-900">{baseName ?? '六爻已备'}</h3>
<p className="mt-1 text-[11.5px] text-ink-600">
{movingList.length ? `动爻 ${movingList.map((p) => POS_NAMES[p - 1]).join('、')}` : '六爻安静 · 静卦'}
</p>
</div>
<button type="button" onClick={reset} className="press shrink-0 font-song text-[11.5px] text-ink-500 underline-offset-4 hover:underline">重起</button>
</div>
<Button
variant="line"
size="lg"
block
className="min-h-[52px] flex-col !gap-0.5 border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] !text-[#F5E9CB] hover:border-[#9C7A48] hover:!text-[#F5E9CB]"
onClick={go}
>
<span>排盘解卦</span>
<span className="text-[10.5px] font-normal opacity-70">纳甲 · 世应 · 六亲</span>
</Button>
<p className="mt-3 text-center font-kai text-[11px] tracking-[0.06em] text-[#938873]">
{movingList.length ? '卦已成,动爻已标于盘面' : '静卦以本卦象断,不另立变盘'}
</p>
</div>
</div>
)}
</div>
);
}
+158
View File
@@ -0,0 +1,158 @@
'use client';
/**
* 六十四卦下拉选择(可输入)
* ==========================
* - 输入即过滤:全名(天风姤)、简称(姤)、宫(乾宫)、上下卦(乾上兑下)都能命中;
* - 键盘:↑↓ 移动、Enter 选中、Esc 收起;
* - 选项里带卦画,改起来不靠记名字。
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { guaByBinary, searchGua, type GuaEntry } from '@/lib/liuyao/hexagram-index';
function GuaLines({ binary, tone = 'ink' }: { binary: string; tone?: 'ink' | 'soft' }) {
const bits = binary.split('').reverse(); // 上爻在顶
const color = tone === 'ink' ? 'var(--ink-900)' : 'var(--ink-500)';
return (
<span className="flex shrink-0 flex-col items-center gap-[2px]" aria-hidden>
{bits.map((b, i) => (
<span key={i} className="flex h-[2.5px] w-[22px]" style={{ gap: 2.5 }}>
{b === '1' ? (
<span className="h-full w-full" style={{ background: color }} />
) : (
<>
<span className="h-full flex-1" style={{ background: color }} />
<span className="h-full flex-1" style={{ background: color }} />
</>
)}
</span>
))}
</span>
);
}
export default function GuaCombobox({
label,
value,
onChange,
hint,
}: {
label: string;
value: string;
onChange: (binary: string) => void;
hint?: string;
}) {
const current = guaByBinary(value);
const [open, setOpen] = useState(false);
const [query, setQuery] = useState('');
const [cursor, setCursor] = useState(0);
const boxRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
const options = useMemo(() => searchGua(query), [query]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
if (boxRef.current && !boxRef.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', onDown);
return () => document.removeEventListener('mousedown', onDown);
}, [open]);
useEffect(() => {
setCursor(0);
}, [query]);
const pick = (g: GuaEntry) => {
onChange(g.binary);
setQuery('');
setOpen(false);
};
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
setOpen(true);
setCursor((c) => Math.min(options.length - 1, c + 1));
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setCursor((c) => Math.max(0, c - 1));
} else if (e.key === 'Enter') {
if (open && options[cursor]) {
e.preventDefault();
pick(options[cursor]);
}
} else if (e.key === 'Escape') {
setOpen(false);
}
};
return (
<div ref={boxRef} className="relative">
<div className="mb-1 flex items-baseline justify-between">
<span className="text-[11px] tracking-[0.1em] text-ink-500">{label}</span>
{hint && <span className="text-[10.5px] text-ink-400">{hint}</span>}
</div>
<div
className={`flex h-11 items-center gap-2.5 rounded-xs border bg-paper-0 px-2.5 transition-colors ${
open ? 'border-gold-500' : 'border-line-strong'
}`}
onClick={() => {
setOpen(true);
inputRef.current?.focus();
}}
>
{current && <GuaLines binary={current.binary} />}
<input
ref={inputRef}
value={open ? query : (current?.name ?? '')}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
}}
onFocus={() => setOpen(true)}
onKeyDown={onKeyDown}
placeholder={current ? current.name : '输入卦名,如 姤 / 天风姤'}
className="min-w-0 flex-1 bg-transparent font-song text-[14px] text-ink-900 outline-none placeholder:text-ink-400"
/>
<span className="shrink-0 font-song text-[11px] text-ink-400">{current ? `${current.palace}宫` : ''}</span>
<span aria-hidden className="shrink-0 text-[10px] text-ink-400">
▾
</span>
</div>
{open && (
<div className="absolute inset-x-0 top-full z-50 mt-1 max-h-[248px] overflow-y-auto rounded-xs border border-line-strong bg-paper-0 shadow-[0_8px_24px_rgba(20,28,34,0.14)]">
{options.length === 0 && (
<p className="px-3 py-3 text-[12px] text-ink-500">没有匹配的卦名</p>
)}
{options.map((g, i) => {
const active = g.binary === value;
return (
<button
key={g.binary}
type="button"
onMouseEnter={() => setCursor(i)}
onClick={() => pick(g)}
className={`flex w-full items-center gap-2.5 px-2.5 py-2 text-left transition-colors ${
i === cursor ? 'bg-paper-1' : 'bg-transparent'
}`}
>
<GuaLines binary={g.binary} tone={active ? 'ink' : 'soft'} />
<span className={`font-song text-[13.5px] ${active ? 'font-semibold text-ink-900' : 'text-ink-800'}`}>
{g.name}
</span>
<span className="ml-auto text-[10.5px] text-ink-400">
{g.palace}宫 · {g.upper}上{g.lower}下
</span>
</button>
);
})}
</div>
)}
</div>
);
}
+330
View File
@@ -0,0 +1,330 @@
'use client';
import React, { useState } from 'react';
import { Coin, type CoinSide } from '@/components/liuyao/Coin';
import { tossStats, tossThree } from '@/lib/liuyao/random';
import {
AppBar,
Button,
Panel,
Paper,
ProgressDots,
Tabs,
Tag,
YaoBar,
} from '@/components/ui';
/**
* 设计稿(S0)
* ============
* 不是"组件目录",而是**起卦页的近似稿** + 盘面/九宫/解卦三个真实区块,
* 让评审直接看"打开 App 是什么样"。
*/
const SWATCHES = [
{ name: '页底', value: '#EEF2F3', token: 'paper-1' },
{ name: '纸面', value: '#FBFCFA', token: 'paper-0' },
{ name: '区间底', value: '#E4EBED', token: 'paper-2' },
{ name: '发丝线', value: '#DBE4E7', token: 'line' },
{ name: '墨', value: '#1F2A30', token: 'ink-900' },
{ name: '次墨', value: '#5F7278', token: 'ink-600' },
{ name: '雾蓝', value: '#6E8F9C', token: 'mist-600' },
{ name: '雾蓝深', value: '#3C5661', token: 'mist-900' },
{ name: '赭金', value: '#8A6A3A', token: 'gold-600' },
{ name: '朱砂', value: '#A8453C', token: 'cinnabar-600' },
];
const LINES = [
{ god: '玄武', rel: '父母', najia: '辛未土', role: '世', yang: true, moving: true, ch: '父母 甲子水' },
{ god: '白虎', rel: '兄弟', najia: '辛酉金', role: '应', yang: false, moving: false, ch: '兄弟 甲戌土' },
{ god: '螣蛇', rel: '子孙', najia: '辛亥水', role: '', yang: true, moving: false, ch: '' },
];
export default function DesignPage() {
const [mode, setMode] = useState<'coin' | 'manual'>('coin');
const [marital, setMarital] = useState<'unmarried' | 'married'>('unmarried');
const [dots, setDots] = useState(3);
const [skin, setSkin] = useState<'mist' | 'paper'>('mist');
const [coins, setCoins] = useState<CoinSide[]>(['字', '背', '字']);
const [rolling, setRolling] = useState(false);
const [tossSeq, setTossSeq] = useState(0);
const [stats, setStats] = useState<ReturnType<typeof tossStats> | null>(null);
const doToss = () => {
if (rolling) return;
const [a, b, c] = tossThree();
setRolling(true);
setTossSeq((n) => n + 1);
window.setTimeout(() => {
setCoins([a === 2 ? '字' : '背', b === 2 ? '字' : '背', c === 2 ? '字' : '背']);
setRolling(false);
}, 940);
};
React.useEffect(() => {
setStats(tossStats(2000));
}, []);
React.useEffect(() => {
document.documentElement.dataset.skin = skin;
return () => {
delete document.documentElement.dataset.skin;
};
}, [skin]);
const values = [
{ yang: false, moving: true },
{ yang: false, moving: false },
{ yang: true, moving: false },
{ yang: false, moving: false },
{ yang: true, moving: false },
{ yang: true, moving: false },
];
return (
<div className="min-h-screen bg-paper-1 pb-16">
<AppBar
title="六爻"
subtitle="三钱摇卦 · 一事一占"
right={
<div className="flex items-center gap-2">
{(['mist', 'paper'] as const).map((k) => (
<button
key={k}
type="button"
onClick={() => setSkin(k)}
className={`press text-[11.5px] ${
skin === k ? 'font-medium text-ink-900 underline underline-offset-4' : 'text-ink-500'
}`}
>
{k === 'mist' ? '雾蓝' : '宣纸米'}
</button>
))}
</div>
}
/>
<main className="mx-auto w-full max-w-[520px] px-5 lg:max-w-[1080px] lg:px-8">
{/* PC:案头两页(左起卦与盘面 / 右九宫与解卦),移动:单栏顺序流 */}
<div className="lg:grid lg:grid-cols-[minmax(0,520px)_minmax(0,1fr)] lg:gap-10 lg:items-start">
<div className="min-w-0">
{/* 起卦 */}
<Panel title="起卦" hint="从初爻起,共六次">
<Tabs
value={mode}
onChange={setMode}
options={[
{ id: 'coin', label: '三钱摇卦' },
{ id: 'manual', label: '手动指定' },
]}
/>
<div className="mt-5">
{/* 铜钱:真实照片正反两面,3D 翻滚后停在结果面 */}
<div className="flex items-center justify-center gap-8 py-3">
{coins.map((face, i) => (
<Coin key={`${tossSeq}-${i}`} side={face} rolling={rolling} delayMs={i * 40} rotateDeg={[-9, 6, -4][i] ?? 0} />
))}
</div>
<div className="mt-4 flex items-center justify-between">
<ProgressDots values={values.slice(0, dots)} />
<Tag tone="mist">{dots}/6</Tag>
</div>
<p className="mt-2 text-[12px] leading-relaxed text-ink-500">
字面为 2 · 背面为 3 · 2+2+3 = 7(少阳)
</p>
{stats && (
<p className="mt-1 font-mono text-[10.5px] leading-relaxed text-ink-400">
随机源自检(Web Crypto · 实测 {stats.total} 掷):字 {stats.faceCounts[2]} / 背 {stats.faceCounts[3]},
字面占比 {(stats.faceRatio * 100).toFixed(2)}%(理论 50%),爻值最大偏差 {stats.maxDeviation.toFixed(2)}pp
</p>
)}
<div className="mt-4">
<Button size="lg" block onClick={doToss} disabled={rolling}>
{rolling ? '掷币中…' : dots === 0 ? '起 卦(初爻)' : `摇第 ${dots + 1} 爻`}
</Button>
</div>
<div className="mt-3 flex items-center justify-between">
<button type="button" className="press text-[12.5px] text-ink-600 underline-offset-4">
手动指定卦象
</button>
<span className="text-[11.5px] text-ink-400">癸未日 未时 · 旬空申酉</span>
</div>
{/* 选填:收在主按钮之下,不抢首屏动作 */}
<details className="mt-4 pt-3" style={{ borderTop: '1px solid var(--hairline)' }}>
<summary className="cursor-pointer list-none text-[11.5px] tracking-[0.04em] text-ink-500">
补充(选填)· 性别 / 婚否 / 起卦时间
</summary>
<div className="mt-3 flex flex-wrap items-center gap-x-6 gap-y-3">
<div className="flex items-center gap-2.5">
<span className="text-[11.5px] text-ink-500">性别</span>
{['男', '女'].map((g) => (
<button
key={g}
type="button"
className={`press text-[13.5px] ${g === '女' ? 'font-medium text-ink-900' : 'text-ink-500'}`}
>
{g}
</button>
))}
</div>
<div className="flex items-center gap-2.5">
<span className="text-[11.5px] text-ink-500">婚否</span>
{(['未婚', '已婚'] as const).map((label, i) => {
const id = i === 0 ? 'unmarried' : 'married';
return (
<button
key={id}
type="button"
onClick={() => setMarital(id as 'married' | 'unmarried')}
className={`press text-[13.5px] ${marital === id ? 'font-medium text-ink-900' : 'text-ink-500'}`}
>
{label}
</button>
);
})}
</div>
</div>
<p className="mt-2 text-[11px] leading-relaxed text-ink-400">
婚否只作落款记录,不参与排盘计算。
</p>
</details>
</div>
</Panel>
<div className="hair-t" />
{/* 盘面 */}
<Panel title="盘面" hint="天风姤 之 乾为天">
<Paper>
<div className="mb-2 flex items-baseline justify-between">
<div className="flex items-baseline gap-2">
<span className="font-song text-[20px] font-semibold tracking-[0.08em] text-ink-900">天风姤</span>
<span className="text-[11px] text-ink-500">乾宫 · 金 · 归魂</span>
</div>
<Tag tone="cinnabar" mark="▸">
初爻动
</Tag>
</div>
<div className="mb-1 flex items-center justify-between text-[10.5px] tracking-[0.06em] text-ink-400">
<span>六神 · 六亲纳甲</span>
<span>变卦</span>
</div>
{LINES.map((l, i) => (
<div key={i} className="flex items-center gap-2 py-[9px]">
<span className="w-8 shrink-0 text-[11.5px] text-ink-500">{l.god}</span>
<span className="w-[76px] shrink-0 text-[13px] text-ink-900">
<b className="font-semibold">{l.rel}</b>
<span className="ml-0.5 font-mono text-[12px] tabular-nums">{l.najia}</span>
</span>
<YaoBar yang={l.yang} moving={l.moving} width={46} height={6} />
<span
className={`w-4 shrink-0 text-center font-song text-[12px] ${
l.role === '世' ? 'text-cinnabar-600' : 'text-mist-700'
}`}
>
{l.role}
</span>
<span className="min-w-0 flex-1 truncate text-right text-[11.5px] text-ink-500">{l.ch}</span>
</div>
))}
<div className="mt-3 flex items-center gap-3 pt-2.5 text-[11px] text-ink-500" style={{ borderTop: '1px solid var(--hairline)' }}>
<Tag tone="ink" mark="○">
用神 父母丑土
</Tag>
<Tag tone="ink" mark="◌">
静卦可用宜变法
</Tag>
</div>
</Paper>
</Panel>
</div>
<div className="min-w-0">
<div className="hair-t lg:hidden" />
{/* 解卦 */}
<Panel title="解卦" hint="四段 · 400–550 字">
<p className="indent-8 font-song text-[15.5px] leading-[1.95] text-ink-800">
所问为丈夫升职,取官鬼为用——官鬼持世而动,得日辰生扶,是事在我手之象。
世应之间无冲无合,进神未成,先立在一个「缓」字上。
</p>
<p className="mt-3 text-[11.5px] text-ink-500">
正文用宋体、字号 15.5、行高 1.95;不加粗、不加色块,只有段落与空行。
</p>
</Panel>
<div className="hair-t" />
{/* 控件对照 */}
<Panel title="控件" hint="触控 ≥44px">
<div className="space-y-3">
<div className="flex gap-2">
<Button block>主按钮</Button>
<Button variant="line" block>
次按钮
</Button>
<Button variant="text" block>
文字
</Button>
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<Tag tone="gold">用神</Tag>
<Tag tone="cinnabar">动爻</Tag>
<Tag tone="mist">4/6</Tag>
<Tag tone="ink">静卦</Tag>
</div>
</div>
</Panel>
<div className="hair-t" />
{/* 色板与字号 */}
<Panel title="色板" hint="点按复制">
<div className="grid grid-cols-2 gap-x-4 gap-y-2">
{SWATCHES.map((s) => (
<button
key={s.token}
type="button"
onClick={() => navigator.clipboard?.writeText(s.value)}
className="press flex items-center gap-2.5 py-1 text-left"
>
<span
className="h-7 w-7 shrink-0"
style={{ background: s.value, border: '1px solid var(--hairline)' }}
aria-hidden
/>
<span className="min-w-0">
<span className="block truncate text-[12px] text-ink-800">{s.name}</span>
<span className="block truncate font-mono text-[10px] text-ink-500">{s.value}</span>
</span>
</button>
))}
</div>
</Panel>
<Panel title="字号" hint="正文无衬线 · 卦名/解卦用宋">
<div className="space-y-2">
<div className="font-song text-[26px] font-semibold tracking-[0.08em] text-ink-900">天风姤</div>
<div className="font-song text-[16px] text-ink-800">一、取用 · 父母丑土持世</div>
<div className="text-[15px] leading-[1.8] text-ink-800">界面正文 15px:按钮、标签、说明文字用无衬线。</div>
<div className="font-song text-[15.5px] leading-[1.95] text-ink-800">解卦正文 15.5px:宋体,行高 1.95。</div>
<div className="font-mono text-[11.5px] tabular-nums text-ink-500">丙午年 戊戌月 癸未日 · 0/6 → 6/6</div>
</div>
</Panel>
</div>
</div>
</main>
</div>
);
}
+472
View File
@@ -0,0 +1,472 @@
'use client';
/**
* 案例 · 《增删卜易》卦例
* ======================
* 一例一个大框,框内照书的次序读:
* 例N 古筮知识:…
* 酉月辛亥日,占谒贵求财,得「兑之解」
* 干支:酉月 辛亥日 (旬空:寅卯)
* 兑宫:兑为泽(六冲)    震宫:雷水解
* 六神 【本  卦】     【变  卦】
* 螣蛇 ▅▅ ▅▅ 父母未土 世   ▅▅ ▅▅ 父母戌土
* …
* 原注:… / 1、选取用神:… / 2、吉凶判断:… / 3、应期细节:…
*
* 卦盘是本页的视觉中心,但不再拆成小卡片:只用一层浅底把六行托住。
* 数据:public/data/zengshan-cases.json;卦盘由同一引擎按「投掷值 + 同月建同日辰」重排。
*/
import React, { useEffect, useMemo, useState } from 'react';
import SiteHeader from '@/components/site/SiteHeader';
import { encodeCastState } from '@/lib/liuyao/cast-url';
import type { CoinResult } from '@/components/liuyao/types';
import { buildLiuyaoInput, castTimeInfo, parseTimeInput } from '@/lib/liuyao/ganzhi';
import { castLiuyao, type LiuyaoChart, type LiuyaoLine } from '@/lib/liuyao/najia';
interface ExampleCase {
id: number;
topic: string;
question: string;
ganzhi: string;
void: string;
guaPair: string;
ben: string;
benPalace: string;
benTag: string;
zhi: string;
zhiPalace: string;
zhiTag: string;
note: string;
yong: string;
luck: string;
timing: string;
coins: number[];
solar: string | null;
}
interface Payload {
source: string;
count: number;
cases: ExampleCase[];
}
const INK = '#242422';
const BODY = '#33322E';
const MUTED = '#6F6A60';
const HAIR = '#E1D8C8';
const CARD = '#FCFAF5';
const SOFT = '#F4EFE5';
const ACCENT = '#C23A2B';
const PER_PAGE = 6;
const FILTERS = ['全部', '六冲', '六合', '游魂', '归魂'] as const;
type Filter = (typeof FILTERS)[number];
function chartHref(c: ExampleCase): string | null {
if (!c.solar || c.coins.length !== 6) return null;
const qs = encodeCastState({
coins: c.coins as CoinResult[],
timeInput: c.solar,
gender: '男',
marital: 'unmarried',
question: c.question,
});
return `/liuyao?${qs}`;
}
function buildChart(c: ExampleCase): LiuyaoChart | null {
if (!c.solar || c.coins.length !== 6) return null;
try {
return castLiuyao(buildLiuyaoInput(castTimeInfo(parseTimeInput(c.solar)), c.coins));
} catch {
return null;
}
}
/** 爻画:实心块,跨字体对齐 */
function YaoBar({ yang, tone }: { yang: boolean; tone: string }) {
if (yang) return <span style={{ display: 'block', width: 36, height: 4, background: tone, borderRadius: 1 }} />;
return (
<span style={{ display: 'flex', width: 36, height: 4, gap: 8 }}>
<i style={{ flex: 1, background: tone, borderRadius: 1 }} />
<i style={{ flex: 1, background: tone, borderRadius: 1 }} />
</span>
);
}
/** 卦盘:照书的列次排(六神 / 伏神 / 本卦 / 世应 / 动 / 变卦 / 世应)
* 用 CSS grid 统一列宽,表头的「本卦 / 变卦」正好压在自己那两列(爻画 + 纳甲)之上。 */
function CaseChart({ chart }: { chart: LiuyaoChart }) {
const lines = useMemo(() => [...chart.lines].sort((a, b) => b.position - a.position), [chart.lines]);
const changed = chart.changedLines;
const changedWorld = chart.changed?.generation ?? null;
const changedResponse = changedWorld ? ((changedWorld + 2) % 6) + 1 : null;
const hiddenList = lines
.filter((l) => l.hiddenSpirit)
.map((l) => ({ position: l.position, text: `${l.hiddenSpirit?.relation}${l.hiddenSpirit?.stemBranch}` }));
const hasHidden = hiddenList.length > 0;
const gridClass = 'ex-grid';
const hiddenAttr = hasHidden ? '1' : '0';
const row = (l: LiuyaoLine) => {
const ch = changed?.[l.position - 1];
const h = l.hiddenSpirit;
return (
<div
key={l.position}
className={`${gridClass} py-[5px]`}
data-hidden={hiddenAttr}
style={l.isMoving ? { background: 'rgba(194,58,43,0.05)' } : undefined}
>
<span style={{ color: MUTED }} className="text-[11px]">
{l.sixGod}
</span>
{hasHidden && (
<span style={{ color: '#A9793F' }} className="hidden truncate text-[10.5px] sm:block">
{h ? `${h.relation}${h.stemBranch}` : ''}
</span>
)}
<span className="flex justify-start">
<YaoBar yang={l.isYang} tone={INK} />
</span>
<span style={{ color: INK }} className="text-[12px]">
{`${l.relation}${l.stem}${l.branch}${l.element}`}
</span>
<span style={{ color: ACCENT }} className="text-center text-[11px]">
{l.isWorld ? '世' : l.isResponse ? '应' : ''}
</span>
<span style={{ color: ACCENT }} className="text-center text-[11px]">
{l.isMoving ? (l.isYang ? '○→' : '×→') : ''}
</span>
<span className="flex justify-start">
{ch ? <YaoBar yang={l.isMoving ? !l.isYang : l.isYang} tone="#5E564D" /> : null}
</span>
<span style={{ color: BODY }} className="text-[12px]">
{ch ? `${ch.relation}${ch.stem}${ch.branch}${ch.element}` : ''}
</span>
<span style={{ color: ACCENT }} className="text-center text-[11px]">
{ch ? (l.position === changedWorld ? '世' : l.position === changedResponse ? '应' : '') : ''}
</span>
</div>
);
};
return (
<div className="mt-2.5 overflow-x-auto">
<div className="min-w-[322px]">
{/* 宫位与卦名 */}
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-0.5 text-[11.5px]" style={{ color: MUTED }}>
<span>
{chart.base.palace}宫:{chart.base.name}
{chart.base.tags.length ? `(${chart.base.tags.join('、')})` : ''}
</span>
{chart.changed && (
<span>
{chart.changed.palace}宫:{chart.changed.name}
{chart.changed.tags.length ? `(${chart.changed.tags.join('、')})` : ''}
</span>
)}
</div>
{/* 列名:本卦 / 变卦 各压在「爻画 + 纳甲」两列之上 */}
<div className={`${gridClass} pb-1 text-[10.5px]`} data-hidden={hiddenAttr} style={{ color: MUTED }}>
<span>六神</span>
{hasHidden && <span className="hidden sm:block">伏神</span>}
<span className="col-span-2 text-center">【本  卦】</span>
<span className="col-span-2" />
<span className="col-span-2 text-center">【变  卦】</span>
<span />
</div>
<div className="border-t pt-1" style={{ borderColor: `${INK}55` }}>
{lines.map(row)}
</div>
{/* 窄屏收起伏神列,改在表下注一行 */}
{hasHidden && (
<p className="mt-1.5 text-[10.5px] leading-relaxed sm:hidden" style={{ color: '#A9793F' }}>
伏神:{hiddenList.map((x) => `${x.text}(${x.position}爻)`).join(' ')}
</p>
)}
</div>
</div>
);
}
function CaseCard({ c }: { c: ExampleCase }) {
const chart = useMemo(() => buildChart(c), [c]);
const href = chartHref(c);
return (
<article className="rounded-[14px] border px-4 py-4 sm:px-5 sm:py-5" style={{ borderColor: HAIR, background: CARD }}>
{/* 例N + 古筮知识 */}
<h2 className="font-song text-[13px] leading-[1.95]" style={{ color: BODY }}>
<span className="mr-2 font-kai text-[12.5px]" style={{ color: ACCENT }}>
例{c.id}
</span>
<span style={{ color: MUTED }}>古筮知识:</span>
{c.topic}
</h2>
{/* 占问与干支 */}
<p className="mt-1 font-song text-[13px] leading-[1.95]" style={{ color: BODY }}>
{c.ganzhi && `${c.ganzhi.replace(/\s+/g, '')},`}
{c.question}
{c.guaPair && `,得「${c.guaPair}」`}
</p>
<p className="mt-0.5 font-kai text-[11.5px] tabular-nums" style={{ color: MUTED }}>
干支:{c.ganzhi || '原文未记'}
{c.void && ` (旬空:${c.void})`}
</p>
{/* 卦盘:一层浅底托住六行 */}
{chart ? (
<div className="mt-2.5 rounded-[10px] border px-3 py-2.5" style={{ borderColor: HAIR, background: SOFT }}>
<CaseChart chart={chart} />
</div>
) : (
<p className="mt-2.5 text-[11.5px]" style={{ color: MUTED }}>
原例未记月建或干支,无法还原卦盘。
</p>
)}
{/* 原注与三段评述:照书的顺序,不拆卡 */}
<div className="mt-3 space-y-1.5 font-song text-[13px] leading-[2]" style={{ color: BODY }}>
{c.note && (
<p>
<span style={{ color: MUTED }}>原注:</span>
{c.note}
</p>
)}
{c.yong && (
<p>
<span style={{ color: MUTED }}>1、选取用神:</span>
{c.yong}
</p>
)}
{c.luck && (
<p>
<span style={{ color: MUTED }}>2、吉凶判断:</span>
{c.luck}
</p>
)}
{c.timing && (
<p>
<span style={{ color: MUTED }}>3、应期细节:</span>
{c.timing}
</p>
)}
</div>
{/* 操作 */}
<div className="mt-3 flex flex-wrap items-center gap-2.5">
{href ? (
<a
href={href}
target="_blank"
rel="noreferrer"
className="press inline-flex h-9 items-center justify-center rounded-[8px] px-4 text-[12.5px] tracking-[0.04em]"
style={{ background: ACCENT, color: '#FFF9F3' }}
>
排出此卦 · 看完整盘面
</a>
) : null}
{c.solar && (
<span className="text-[10.5px]" style={{ color: MUTED }}>
对应公历 {c.solar.replace('T', ' ')}(同月建、同日辰)
</span>
)}
</div>
</article>
);
}
export default function ExamplesView() {
const [data, setData] = useState<Payload | null>(null);
const [error, setError] = useState('');
const [query, setQuery] = useState('');
const [filter, setFilter] = useState<Filter>('全部');
const [page, setPage] = useState(1);
useEffect(() => {
let alive = true;
void fetch('/data/zengshan-cases.json')
.then((r) => (r.ok ? (r.json() as Promise<Payload>) : Promise.reject(new Error(`读取失败(${r.status})`))))
.then((json) => {
if (alive) setData(json);
})
.catch((e) => {
if (alive) setError((e as Error).message);
});
return () => {
alive = false;
};
}, []);
const filtered = useMemo(() => {
const list = data?.cases ?? [];
const q = query.trim();
return list.filter((c) => {
if (filter !== '全部' && !`${c.benTag}${c.zhiTag}`.includes(filter)) return false;
if (!q) return true;
return [c.question, c.ben, c.zhi, c.benTag, c.topic, c.note, c.yong, c.luck, c.timing, String(c.id)].some((v) =>
(v ?? '').includes(q),
);
});
}, [data, query, filter]);
const totalPages = Math.max(1, Math.ceil(filtered.length / PER_PAGE));
const current = Math.min(page, totalPages);
const visible = filtered.slice((current - 1) * PER_PAGE, current * PER_PAGE);
return (
<div className="min-h-screen" style={{ background: '#F7F4EF', color: INK }}>
<SiteHeader active="examples" />
<main className="mx-auto w-full max-w-[1180px] px-4 pb-24 pt-8 sm:px-6 sm:pt-10">
<header className="text-center lg:text-left">
<div className="mb-2.5 flex items-center justify-center gap-3 lg:justify-start" aria-hidden>
<span className="h-px w-8" style={{ background: HAIR }} />
<span className="text-[10px]" style={{ color: HAIR }}>❖</span>
<span className="h-px w-8" style={{ background: HAIR }} />
</div>
<h1 className="font-song text-[30px] font-semibold leading-none tracking-[0.16em] sm:text-[34px]" style={{ color: INK }}>
案例
</h1>
<p className="mt-2.5 text-[11.5px]" style={{ color: MUTED }}>
来源:《增删卜易》卦例 · 朱辰彬《增删卜易卦例初探》
</p>
</header>
<div className="mt-6 lg:grid lg:grid-cols-[minmax(0,1fr)_272px] lg:items-start lg:gap-7">
{/* 侧栏:桌面固定在右,移动端在列表上方 */}
<aside className="order-1 mb-5 space-y-3 lg:order-2 lg:mb-0 lg:sticky lg:top-[70px]">
<div className="rounded-[12px] border px-3.5 py-3.5" style={{ borderColor: HAIR, background: CARD }}>
<label className="flex items-center gap-2 rounded-[8px] border px-2.5 py-2" style={{ borderColor: HAIR }}>
<span className="shrink-0 whitespace-nowrap text-[11.5px]" style={{ color: MUTED }}>
检索
</span>
<input
value={query}
onChange={(e) => {
setQuery(e.target.value);
setPage(1);
}}
placeholder="卦名 / 占问 / 断语"
className="h-6 w-full min-w-0 border-0 bg-transparent text-[12.5px] outline-none placeholder:text-[#B3AA9B]"
style={{ color: INK }}
/>
{query && (
<button type="button" onClick={() => setQuery('')} className="shrink-0 text-[11px]" style={{ color: MUTED }}>
清空
</button>
)}
</label>
<div className="mt-2.5 flex flex-wrap gap-1.5">
{FILTERS.map((f) => {
const active = filter === f;
return (
<button
key={f}
type="button"
onClick={() => {
setFilter(f);
setPage(1);
}}
className="press inline-flex h-7 items-center rounded-full border px-2.5 text-[11.5px] transition-colors"
style={{
borderColor: active ? 'rgba(194,58,43,0.45)' : HAIR,
background: active ? 'rgba(194,58,43,0.08)' : 'transparent',
color: active ? ACCENT : MUTED,
}}
>
{f}
</button>
);
})}
</div>
<p className="mt-3 border-t pt-2.5 text-[11px] tabular-nums" style={{ borderColor: HAIR, color: MUTED }}>
{data ? `${filtered.length} / ${data.count} 例` : error ? '读取失败' : '读取中…'}
{data && filtered.length > 0 && ` · 第 ${current} / ${totalPages} 页`}
</p>
</div>
<div className="rounded-[12px] border px-3.5 py-3" style={{ borderColor: HAIR, background: CARD }}>
<h2 className="text-[11.5px] font-semibold tracking-[0.06em]" style={{ color: MUTED }}>
读法
</h2>
<p className="mt-1.5 text-[11px] leading-[1.95]" style={{ color: MUTED }}>
卦盘按原例的月建、日辰重排,六神与世应可与原书对照。
「排出此卦」打开完整卦单(含神煞、旬空、伏神与四段解卦)。
</p>
</div>
</aside>
{/* 主内容 */}
<div className="order-2 lg:order-1">
{error && (
<p
className="rounded-[10px] border px-3.5 py-2.5 text-[12px]"
style={{ borderColor: '#E4B9AE', background: '#FDF2EF', color: ACCENT }}
>
{error}
</p>
)}
{!data && !error && (
<p className="py-16 text-center text-[12.5px]" style={{ color: MUTED }}>
读取中…
</p>
)}
<div className="space-y-3.5">
{visible.map((c) => (
<CaseCard key={c.id} c={c} />
))}
</div>
{data && filtered.length === 0 && (
<p className="py-14 text-center text-[12.5px]" style={{ color: MUTED }}>
没有匹配的卦例。
</p>
)}
{data && filtered.length > 0 && (
<nav className="mt-5 flex items-center justify-center gap-2.5">
<button
type="button"
onClick={() => setPage((v) => Math.max(1, v - 1))}
disabled={current <= 1}
className="press inline-flex h-9 items-center rounded-[8px] border px-4 text-[12.5px] disabled:opacity-40"
style={{ borderColor: HAIR, color: BODY }}
>
上一页
</button>
<span className="px-1 text-[12px] tabular-nums" style={{ color: MUTED }}>
{current} / {totalPages}
</span>
<button
type="button"
onClick={() => setPage((v) => Math.min(totalPages, v + 1))}
disabled={current >= totalPages}
className="press inline-flex h-9 items-center rounded-[8px] border px-4 text-[12.5px] disabled:opacity-40"
style={{ borderColor: HAIR, color: BODY }}
>
下一页
</button>
</nav>
)}
<p className="mt-8 text-center text-[10.5px] leading-relaxed" style={{ color: MUTED }}>
古法口径不等于现代结论;案例仅作研读参照。
</p>
</div>
</div>
</main>
</div>
);
}
+45 -28
View File
@@ -6,6 +6,8 @@ import type { CoinResult } from './types';
import { HexagramSvg } from '@/components/hexagram/HexagramSvg';
import { masksOf, movingPositions, lineTitle } from '@/lib/hexagram/hex-math';
import { lookupByMask, resolveHexagramInfo } from '@/lib/hexagram/lookup';
import { tossLines, tossThree } from '@/lib/liuyao/random';
import { Coin } from './Coin';
import {
advance,
initialState as yarrowInitial,
@@ -31,6 +33,28 @@ export interface CastWorkbenchProps {
export type CoinFace = 2 | 3; // 2=字(阴), 3=背(阳)
/**
* 爻值 → 三枚币面(仅用于展示;真实结果由 random.ts 的加密随机决定)
*
* 字 = 2、背 = 3,三枚之和即爻值:
* 6 老阴 = 字字字(0 背)· 7 少阳 = 背字字(1 背)
* 8 少阴 = 背背字(2 背)· 9 老阳 = 背背背(3 背)
*/
export function coinFacesOf(value: number): [CoinFace, CoinFace, CoinFace] {
switch (value) {
case 6:
return [2, 2, 2];
case 7:
return [3, 2, 2];
case 8:
return [3, 3, 2];
case 9:
return [3, 3, 3];
default:
return [2, 2, 2];
}
}
/** 一变四步之间的推进节奏(ms),与 l1_tk.py 的 after() 链一致 */
const STEP_MS = 320;
@@ -134,14 +158,12 @@ export default function CastWorkbench({
const handleToss = () => {
if (isTossing || isComplete || disabled) return;
// 随机三枚硬币: 每枚 2 (字/阴) 或 3 (背/阳)
const c1: CoinFace = Math.random() < 0.5 ? 2 : 3;
const c2: CoinFace = Math.random() < 0.5 ? 2 : 3;
const c3: CoinFace = Math.random() < 0.5 ? 2 : 3;
const sum = (c1 + c2 + c3) as CoinResult;
// 三枚铜钱:显示真实 Web Crypto 抽到的三枚面,不从和值拼示意组合。
const faces = tossThree();
const sum = faces.reduce<number>((total, face) => total + face, 0) as CoinResult;
// 立即写入硬币与成爻数据,确保点击第 1 爻即刻跳出爻线与反馈
setCurrentCoins([c1, c2, c3]);
setCurrentCoins(faces);
setValues((prev) => [...prev, sum]);
setIsTossing(true);
@@ -157,12 +179,10 @@ export default function CastWorkbench({
const remaining = 6 - values.length;
const newVals: CoinResult[] = [...values];
let lastCoins: [CoinFace, CoinFace, CoinFace] = currentCoins;
for (let i = 0; i < remaining; i++) {
const c1: CoinFace = Math.random() < 0.5 ? 2 : 3;
const c2: CoinFace = Math.random() < 0.5 ? 2 : 3;
const c3: CoinFace = Math.random() < 0.5 ? 2 : 3;
newVals.push((c1 + c2 + c3) as CoinResult);
lastCoins = [c1, c2, c3];
for (let i = 0; i < remaining; i += 1) {
const faces = tossThree();
lastCoins = faces;
newVals.push(faces.reduce<number>((total, face) => total + face, 0) as CoinResult);
}
setCurrentCoins(lastCoins);
setValues(newVals);
@@ -473,7 +493,7 @@ export default function CastWorkbench({
onClick={() => onComplete(activeValues)}
className="btn primary sm w-full font-serif tracking-widest cursor-pointer shadow-md active:scale-95 transition-all touch-manipulation"
>
确立卦象 · 查看卦辞爻辞 →
六爻已齐 · 起局 →
</button>
) : (
castCount > 0 && (
@@ -504,7 +524,7 @@ export default function CastWorkbench({
}
return (
<div className="w-full rounded-xl border border-[#E0D8C9] bg-[#FFFDF8] p-5 sm:p-7 shadow-xs font-serif text-[#17140F]">
<div className="w-full rounded-md border border-line bg-paper-0 p-5 shadow-[0_1px_2px_rgba(31,42,48,0.05)] sm:p-7 font-serif text-ink-900">
<div className="grid grid-cols-1 md:grid-cols-12 gap-6 items-stretch">
{/* 左侧:起筮操作台 (7/12) */}
<div className="md:col-span-7 flex flex-col justify-between items-center text-center space-y-4">
@@ -532,23 +552,20 @@ export default function CastWorkbench({
{/* 三枚物理铜钱展示区 */}
<div
onClick={!isComplete && !isTossing && !disabled ? handleToss : undefined}
className={`coins flex items-center justify-center gap-4 py-3 select-none ${
className={`coins flex min-h-[118px] items-center justify-center gap-6 py-3 select-none ${
!isComplete && !isTossing && !disabled ? 'cursor-pointer' : ''
}`}
title={!isComplete && !isTossing ? '点击掷钱' : undefined}
>
{currentCoins.map((face, idx) => {
const isYang = face === 3;
return (
<div
key={idx}
className={`coin ${isYang ? 'y' : 'n'} ${isTossing ? 'tossing' : ''}`}
style={{ '--d': `${idx * 0.08}s` } as React.CSSProperties}
>
<span>{isYang ? '背' : '字'}</span>
</div>
);
})}
{currentCoins.map((face, idx) => (
<Coin
key={`${castCount}-${idx}`}
side={face === 3 ? '背' : '字'}
rolling={isTossing}
delayMs={idx * 40}
rotateDeg={[-9, 6, -4][idx] ?? 0}
/>
))}
</div>
{/* 投掷数学与爻象公式 */}
@@ -558,7 +575,7 @@ export default function CastWorkbench({
字面为 2(阴)· 背面为 3(阳)· 2+2+2=6(老阴) · 3+3+3=9(老阳)
</p>
) : (
<div className="inline-flex items-center gap-2 rounded-md bg-[#FAF8F1] border border-[#E0D8C9] px-3 py-1 text-xs">
<div className="inline-flex max-w-full flex-wrap items-center justify-center gap-x-2 gap-y-1 rounded-md border border-[#E0D8C9] bg-[#FAF8F1] px-3 py-1.5 text-[11.5px] leading-tight">
<span className="font-bold text-[#17140F]">
第 {castCount} 爻({lineTitle(castCount, latestYang)})
</span>
+118
View File
@@ -0,0 +1,118 @@
'use client';
import React, { useEffect, useState } from 'react';
/**
* 铜钱:正反两面的真实照片(字面 coin-4 / 背面 coin-3),用 3D 翻转落地。
*
* 设计要点:
* - 不是"换图",而是真翻转:正面 0°,背面 180°,`backface-visibility: hidden`;
* - 结果由调用方给定(来自 `lib/liuyao/random.ts` 的加密随机),
* 组件只负责「掷出后停在哪一面」,不参与任何随机;
* - 翻滚时长与落定时机统一走 `animationend`,避免"动画没停结果先出"。
*/
export type CoinSide = '字' | '背';
/**
* 正反面照片。源图只有 85×85,直接放大到 148 设备像素会发虚,
* 所以预生成 2x(170×170,Lanczos)并用 srcSet 交给浏览器按 DPR 选择。
*
* 文件名不要带 `@`:Workers Assets 会把 `@2x` 重写成 `%402x` 再 307 回 `@2x`,
* 线上就成了无限重定向(本地 dev 看不出来,手机 DPR 3 直接裂图)。用 `-2x` / `-3x`。
*/
const FACE_SRC: Record<CoinSide, { x1: string; x2: string; x3: string }> = {
字: { x1: '/images/coin-4.png', x2: '/images/coin-4-2x.png', x3: '/images/coin-4-3x.png' },
背: { x1: '/images/coin-3.png', x2: '/images/coin-3-2x.png', x3: '/images/coin-3-3x.png' },
};
export function Coin({
side,
rolling,
delayMs = 0,
rotateDeg = 0,
onSettled,
}: {
side: CoinSide;
rolling: boolean;
delayMs?: number;
/** 静置时的轻微倾斜,避免三枚"站军姿"般整齐 */
rotateDeg?: number;
onSettled?: () => void;
}) {
const [phase, setPhase] = useState<'idle' | 'rolling' | 'settling'>('idle');
useEffect(() => {
if (rolling) {
setPhase('rolling');
return;
}
if (phase === 'rolling') setPhase('settling');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [rolling]);
const rotation = side === '字' ? 0 : 180;
return (
<div
className="coin-size relative select-none"
style={{
perspective: 600,
transform: rolling ? undefined : `rotate(${rotateDeg}deg)`,
transition: 'transform 400ms cubic-bezier(0.16,1,0.3,1)',
}}
aria-label={`铜钱 ${side}面`}
role="img"
>
{/* 底面:铜钱侧到 90° 时照片会变成一条看不见的边,
用一圈静态薄环 + 落地阴影表示"它仍在那儿转",三枚始终可数。 */}
<span
aria-hidden
style={{
position: 'absolute',
inset: 0,
borderRadius: '50%',
border: '1px solid rgba(31,42,48,0.16)',
background: 'radial-gradient(circle at 50% 62%, rgba(31,42,48,0.10), rgba(31,42,48,0) 68%)',
}}
/>
<div
className={phase === 'rolling' ? 'coin-spin' : ''}
style={{
position: 'absolute',
inset: 0,
transformStyle: 'preserve-3d',
// 落地:滚完直接停在结果那一面;非滚动状态也保持该面
transform: phase === 'rolling' ? undefined : `rotateY(${rotation}deg)`,
transition: phase === 'settling' ? 'transform 320ms cubic-bezier(0.16,1,0.3,1)' : undefined,
animationDelay: phase === 'rolling' ? `${delayMs}ms` : undefined,
}}
onAnimationEnd={() => {
setPhase('settling');
onSettled?.();
}}
>
{(['字', '背'] as CoinSide[]).map((face) => (
<img
key={face}
src={FACE_SRC[face].x1}
srcSet={`${FACE_SRC[face].x1} 1x, ${FACE_SRC[face].x2} 2x, ${FACE_SRC[face].x3} 3x`}
alt=""
draggable={false}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
objectFit: 'contain',
backfaceVisibility: 'hidden',
transform: face === '字' ? 'rotateY(0deg)' : 'rotateY(180deg)',
// 去掉外发光/重投影:85px 源图经放大后,阴影反而加重"糊"的感觉
filter: 'none',
}}
/>
))}
</div>
</div>
);
}
+52 -15
View File
@@ -18,6 +18,9 @@ import { getChangedHexagramLinesMap } from './hexagram-changed-lines';
import { calcGuShiShenSha, extractLiuyaoTimeInfo, SHENSHA_ORDER, type GuShiShenSha } from '@/lib/zhanbu/shensha';
import { BRANCH_ELEMENTS, formatSolarDateDisplay, getMutatedRelationTags, type BoardViewProps } from '@/lib/liuyao/board-view';
/** 古籍盘面的设计基准宽度:低于此宽度按比例整体缩放,版式关系不变 */
export const BOARD_BASE_WIDTH = 390;
/** 爻画:阳爻一整条,阴爻两段(与原版同一几何:宽 46 / 高 9.5 / 阴爻 gap 8) */
export function MobileYaoBar({
isYang,
@@ -103,9 +106,16 @@ export function getSanitizedHiddenSpirit(hidden?: BoardViewProps['lines'][number
return s.length >= 2 ? s : '';
}
const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function HexagramBoard(props, ref) {
const { question, gender, datetime_info, hexagram_info, lines } = props;
const barColor = '#2C2723';
export interface HexagramBoardProps extends BoardViewProps {
/** 需要高亮的爻位(1..6),用于标出「用神」 */
highlightPosition?: number | null;
/** 高亮标签,默认「用神」 */
highlightLabel?: string;
}
const HexagramBoard = forwardRef<HTMLDivElement, HexagramBoardProps>(function HexagramBoard(props, ref) {
const { question, gender, datetime_info, hexagram_info, lines, highlightPosition, highlightLabel = '用神' } = props;
const barColor = '#141C22';
// 上爻(6) → 初爻(1)
const sortedLines = useMemo(() => [...lines].sort((a, b) => b.position - a.position), [lines]);
@@ -206,13 +216,13 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '2px 8px', marginTop: 2 }}>
<span style={{ color: '#7A7165' }}>干支:</span>
<span style={{ color: '#B91C1C', fontWeight: 700 }}>{timeInfo.monthDisplay}</span>
<span style={{ color: '#B91C1C', fontWeight: 700 }}>{timeInfo.dayDisplay}</span>
<span style={{ color: '#B91C1C', fontWeight: 700, marginLeft: 2 }}>(旬空 {timeInfo.voidStr})</span>
<span style={{ color: '#8F3323', fontWeight: 700 }}>{timeInfo.monthDisplay}</span>
<span style={{ color: '#8F3323', fontWeight: 700 }}>{timeInfo.dayDisplay}</span>
<span style={{ color: '#8E582B', fontWeight: 700, marginLeft: 2 }}>(旬空 {timeInfo.voidStr})</span>
</div>
{/* 十三实用星煞 */}
<div style={{ marginTop: 6, display: 'flex', alignItems: 'flex-start', gap: 6, fontSize: 12.5, lineHeight: 1.6 }}>
<div style={{ marginTop: 6, display: 'flex', alignItems: 'flex-start', gap: 6, fontSize: 12.5, lineHeight: 1.75 }}>
<span style={{ color: '#7A7165', fontWeight: 600, flexShrink: 0, whiteSpace: 'nowrap' }}>神煞:</span>
<div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '2px 8px', flex: 1 }}>
{SHENSHA_ORDER.map(({ key, label }) => {
@@ -262,7 +272,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
<div style={{ width: 6, flexShrink: 0 }} />
<div style={{ width: 144, display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
<span style={{ color: '#1E40AF', fontSize: 16, fontWeight: 800 }}>{hexagram_info.base_name}</span>
<span style={{ color: '#244450', fontSize: 17, fontWeight: 800, letterSpacing: 1 }}>{hexagram_info.base_name}</span>
<span style={{ fontSize: 12, fontWeight: 600, color: '#5C5449' }}>({baseAttrTag})</span>
</div>
@@ -270,7 +280,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
<>
<div style={{ width: 30, flexShrink: 0 }} />
<div style={{ width: 178, display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
<span style={{ color: '#1E40AF', fontSize: 16, fontWeight: 800 }}>{changedTitle}</span>
<span style={{ color: '#3D6673', fontSize: 16, fontWeight: 800, letterSpacing: 0.5 }}>{changedTitle}</span>
<span style={{ fontSize: 12, fontWeight: 600, color: '#5C5449' }}>({changedAttrTag})</span>
</div>
</>
@@ -314,17 +324,44 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
key={line.position}
style={{
position: 'relative',
height: 35,
height: 37,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
paddingTop: 3,
boxSizing: 'border-box',
borderBottom: '1px solid #EAE5D4',
backgroundColor: 'transparent',
backgroundColor: highlightPosition === line.position ? 'rgba(138,106,58,0.07)' : 'transparent',
minWidth: changedTitle ? 390 : undefined,
}}
>
{highlightPosition === line.position && (
<>
<span
aria-hidden
style={{
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
width: 2,
background: '#8A6A3A',
}}
/>
<span
style={{
position: 'absolute',
right: 0,
top: 2,
fontSize: 9.5,
letterSpacing: 1,
color: '#8A6A3A',
}}
>
{highlightLabel}
</span>
</>
)}
<div style={{ display: 'flex', alignItems: 'center', height: 20 }}>
{/* 1. 六神 */}
<span style={{ width: 32, textAlign: 'center', fontSize: 12.5, fontWeight: 700, color: '#4B443B', flexShrink: 0 }}>
@@ -361,7 +398,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
textAlign: 'center',
fontSize: 12,
fontWeight: 800,
color: line.is_world ? '#B91C1C' : line.is_response ? '#059669' : 'transparent',
color: line.is_world ? '#8F3323' : line.is_response ? '#3F6B55' : 'transparent',
flexShrink: 0,
}}
>
@@ -380,7 +417,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
alignItems: 'center',
justifyContent: 'center',
gap: 2,
color: line.is_moving ? '#B91C1C' : 'transparent',
color: line.is_moving ? '#8F3323' : 'transparent',
flexShrink: 0,
userSelect: 'none',
}}
@@ -412,7 +449,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
width: 68,
fontSize: 13,
fontWeight: line.is_moving ? 700 : 500,
color: line.is_moving ? '#B91C1C' : '#4B443B',
color: line.is_moving ? '#8F3323' : '#33424A',
letterSpacing: 0.2,
flexShrink: 0,
}}
@@ -430,7 +467,7 @@ const HexagramBoard = forwardRef<HTMLDivElement, BoardViewProps>(function Hexagr
<div style={{ width: 52, flexShrink: 0, display: 'flex', alignItems: 'center' }}>
{relationTags.length > 0 && (
<span style={{ fontSize: 11.5, fontWeight: 700, color: '#B91C1C', whiteSpace: 'nowrap' }}>
<span style={{ fontSize: 11, fontWeight: 700, color: '#8E582B', whiteSpace: 'nowrap' }}>
[{relationTags.join('')}]
</span>
)}
+242
View File
@@ -0,0 +1,242 @@
'use client';
/**
* 六爻结果页(S2 · 单列居中)
* ==========================
* 一块纸、一条中轴:卦名 → 公历干支 → 盘面(居中,按容器等比缩放)→ 四段解卦。
*
* 设计口径(与首页同一套语言:宣纸 + 松墨绿 + 淡金线):
* - 右上角只留「历史排盘」与「截图」,不铺全站导航;
* - 顶部工具条:历史排盘 / 重新起卦 / 截图;底部只放当前动作(解卦 / 停止);
* - 盘面只呈现确定性排盘,不标用神(断语属于解读层,不压在版面上);
* - 不再有「保存」按钮:解卦完成即静默归档进历史排盘,少一个要点的东西。
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { Camera } from 'lucide-react';
import ResponsiveBoard from './ResponsiveBoard';
import ReadingPanel, { type ReadingPanelHandle } from './ReadingPanel';
import SiteHeader from '@/components/site/SiteHeader';
import InkLandscape from '@/components/site/InkLandscape';
import { formatSolarDateDisplay, type BoardViewProps } from '@/lib/liuyao/board-view';
import type { LiuyaoReadingFacts } from '@/lib/readings/types';
export type ReadingPhase = 'idle' | 'streaming' | 'done' | 'error';
const PRIMARY_BTN =
'press inline-flex h-12 items-center justify-center rounded-[3px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] px-4 font-song text-[14px] tracking-[0.16em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)] transition-colors hover:bg-[#223D34] disabled:opacity-60';
const HEADER_LINK =
'font-song text-[11.5px] tracking-[0.05em] text-[#5E5A50] underline-offset-4 transition-colors hover:text-[#8E6337] hover:underline sm:text-[12.5px]';
export default function LiuyaoResult({
boardProps,
facts,
question,
onReset,
onSave,
}: {
boardProps: BoardViewProps;
facts: LiuyaoReadingFacts;
question: string;
onReset: () => void;
/** 解卦完成后的静默归档(历史排盘) */
onSave: () => Promise<void> | void;
}) {
const panelRef = useRef<ReadingPanelHandle | null>(null);
const shotRef = useRef<HTMLDivElement | null>(null);
const [phase, setPhase] = useState<ReadingPhase>('idle');
const [shooting, setShooting] = useState(false);
const archivedRef = useRef(false);
const streaming = phase === 'streaming';
/** 底栏只在「还没解 / 正在解」时出现;读完(或出错)就收起 */
const showActionBar = phase === 'idle' || streaming;
// 解卦读完即归档(用户不再需要点「保存」)
useEffect(() => {
if (phase !== 'done' || archivedRef.current) return;
archivedRef.current = true;
void onSave();
}, [phase, onSave]);
/** 截图:只截盘面那张纸(确定性排盘),不含解卦文字 */
const handleShot = async () => {
const node = shotRef.current;
if (!node || shooting) return;
setShooting(true);
try {
const { toPng } = await import('html-to-image');
// 注意:捕获节点的 `mx-auto` 在克隆里会按**外层容器**重新居中,
// 宽屏下(卡片比容器窄)就会整体右移、右侧被裁掉。这里把外边距钉成 0,
// 并把宽高写死,导出的图才和屏幕上这块纸一致。
const dataUrl = await toPng(node, {
pixelRatio: 3,
backgroundColor: '#FCFAF3',
cacheBust: true,
width: node.offsetWidth,
height: node.offsetHeight,
style: { margin: '0', transform: 'none' },
});
const name = `六爻_${boardProps.hexagram_info.base_name}_${boardProps.datetime_info.solar_date.replace(/[^\d]/g, '').slice(0, 12)}.png`;
const a = document.createElement('a');
a.href = dataUrl;
a.download = name;
a.click();
} catch {
/* 隐私模式/跨域字体失败时静默,不弹窗打扰 */
} finally {
window.setTimeout(() => setShooting(false), 600);
}
};
const changedName =
boardProps.hexagram_info.changed_name &&
boardProps.hexagram_info.changed_name !== boardProps.hexagram_info.base_name
? boardProps.hexagram_info.changed_name
: '';
const solar = formatSolarDateDisplay(boardProps.datetime_info.solar_date, boardProps.datetime_info.ganzhi);
return (
<div className={`relative min-h-screen bg-[#F4F1E8] text-[#38423C] ${showActionBar ? 'pb-28 lg:pb-16' : 'pb-12 lg:pb-16'}`}>
<div aria-hidden className="pointer-events-none absolute inset-x-0 top-0 h-[260px] overflow-hidden opacity-80">
<InkLandscape />
</div>
<SiteHeader
sticky
showNav={false}
maxWidthClassName="max-w-[1120px]"
actions={
<>
<Link href="/cases" className={HEADER_LINK}>
历史排盘
</Link>
<span aria-hidden className="h-4 w-px bg-[#C8BEA8]" />
<button
type="button"
onClick={() => void handleShot()}
disabled={shooting}
aria-label="截图确定性排盘"
title="截图(确定性排盘)"
className="press flex h-8 items-center gap-1.5 rounded-full border border-[#C3B79E] bg-[#FCF9F0]/70 px-3 font-song text-[12px] text-[#4A4438] transition-colors hover:border-[#9A7040] hover:text-[#8E6337] disabled:opacity-50"
>
<Camera size={13} strokeWidth={1.7} />
{shooting ? '生成中' : '截图'}
</button>
</>
}
/>
<main className="relative z-10 mx-auto w-full max-w-[1120px] px-4 sm:px-6 lg:px-8">
{/* PC:左盘面(吸顶)+ 右解卦;移动端仍是单列中轴 */}
<div className="grid gap-7 lg:grid-cols-[440px_minmax(0,1fr)] lg:items-start lg:gap-12">
{/* 左:卦名 + 盘面(尺寸不变:卡片 440 / 爻盘 390 基准) */}
<div className="lg:sticky lg:top-[86px]">
<div className="pb-1 pt-5 text-center lg:pt-10">
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1">
<h1 className="font-song text-[26px] font-semibold leading-tight tracking-[0.16em] text-[#2F4438] sm:text-[32px] lg:text-[34px]">
{boardProps.hexagram_info.base_name}
</h1>
{changedName && (
<>
<span aria-hidden className="font-song text-[15px] text-[#8E6337]">
⇌
</span>
<span className="font-song text-[21px] font-semibold tracking-[0.14em] text-[#2F4438] sm:text-[26px] lg:text-[28px]">
{changedName}
</span>
</>
)}
</div>
<p className="mt-2 font-song text-[11.5px] tabular-nums tracking-[0.04em] text-[#7C7668] lg:text-[12.5px]">
公历:{solar} · {boardProps.datetime_info.ganzhi}
</p>
{/* 问事只在盘面里出现一次(卦单落款),页首不重复 */}
</div>
{/* 太极分隔 */}
<div aria-hidden className="my-3 flex items-center justify-center gap-3">
<span className="h-px w-10 bg-[#CBBFA8]/80" />
<span className="font-song text-[13px] text-[#8E6337]">☯</span>
<span className="h-px w-10 bg-[#CBBFA8]/80" />
</div>
{/* 盘面 */}
<div
ref={shotRef}
className="mx-auto w-full max-w-[440px] bg-[#FBF7EC] px-4 py-4 sm:px-5"
style={{
borderRadius: 10,
border: '1px solid rgba(179,160,125,0.55)',
boxShadow: '0 8px 24px rgba(64,69,60,0.08)',
}}
>
<ResponsiveBoard {...boardProps} />
</div>
{/* PC:动作按钮就在盘面下方(不再悬浮);移动端见底部悬浮条 */}
{showActionBar && (
<div className="mx-auto mt-5 hidden w-full max-w-[440px] lg:block">
<button
type="button"
onClick={streaming ? () => panelRef.current?.stop() : () => panelRef.current?.start()}
className={`${PRIMARY_BTN} w-full`}
>
{streaming ? '停 止' : '解 卦'}
</button>
</div>
)}
</div>
{/* 右:解卦正文(一张纸,读完像一页批注) */}
<div className="min-w-0 lg:mt-6">
<div
className={`lg:min-h-[620px] lg:bg-[#FBF7EC]/70 lg:px-8 lg:py-8 ${
phase === 'idle' ? 'lg:flex lg:flex-col lg:items-center lg:justify-center' : ''
}`}
style={{ borderRadius: 10, border: '1px solid rgba(179,160,125,0.38)' }}
>
<ReadingPanel
ref={panelRef}
facts={facts}
hideIdleButton
className="mt-5 lg:mt-0"
onPhaseChange={setPhase}
/>
{phase === 'idle' && (
<div className="hidden flex-col items-center justify-center gap-3 py-16 text-center lg:flex lg:py-0">
<span aria-hidden className="font-song text-[15px] text-[#C0B49B]">
☯
</span>
<p className="font-song text-[13.5px] leading-[2.2] tracking-[0.04em] text-[#8C8272]">
盘面已定,卦气在纸。
<br />
点盘面下方「解 卦」,依盘面事实作四段解读。
</p>
</div>
)}
</div>
</div>
</div>
</main>
{/* 底栏只承载「此刻唯一的动作」:解卦 / 停止;读完之后收起,让页面回到纯阅读 */}
{showActionBar && (
<div className="safe-bottom fixed inset-x-0 bottom-0 z-20 bg-[#F4F1E8]/95 backdrop-blur-md lg:hidden">
<div className="mx-auto w-full max-w-[640px] px-4 pt-2.5 sm:px-6" style={{ borderTop: '1px solid #DDD4BE' }}>
<button
type="button"
onClick={streaming ? () => panelRef.current?.stop() : () => panelRef.current?.start()}
className={`${PRIMARY_BTN} w-full`}
>
{streaming ? '停 止' : '解 卦'}
</button>
</div>
</div>
)}
</div>
);
}
+91 -115
View File
@@ -1,20 +1,28 @@
'use client';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { RotateCcw, Star } from 'lucide-react';
import { useRouter } from 'next/navigation';
import CastWorkbench from './CastWorkbench';
import ManualCast from './ManualCast';
import HexagramBoard from './HexagramBoard';
import LiuyaoResult from './LiuyaoResult';
import type { CoinResult } from './types';
import { castLiuyao, type LiuyaoChart } from '@/lib/liuyao/najia';
import { buildLiuyaoInput, castTimeInfo, nowTimeInput, parseTimeInput, type CastTimeInfo } from '@/lib/liuyao/ganzhi';
import { boardToText, chartToBoardProps, type BoardViewProps } from '@/lib/liuyao/board-view';
import { chartToBoardProps, type BoardViewProps } from '@/lib/liuyao/board-view';
import { buildLiuyaoReadingFacts } from '@/lib/readings/facts';
import { decodeCastState } from '@/lib/liuyao/cast-url';
import { getCaseStore } from '@/lib/store';
import { buildLiuyaoRecord } from '@/lib/cases/record';
type CastMode = 'coin' | 'yarrow' | 'manual';
/**
* 服务端渲染时 useLayoutEffect 会告警,这里降级成 useEffect。
* 浏览器里用 layout effect:复原占位能在首帧前挂上,不会先闪一下表单。
*/
const useIsoLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
const MODES: { id: CastMode; label: string; hint: string }[] = [
{ id: 'coin', label: '三钱摇卦', hint: '六次掷币,每次三枚' },
{ id: 'yarrow', label: '大衍筮法', hint: '五十蓍草,十八变' },
@@ -30,6 +38,7 @@ const emptyManual = (): (CoinResult | null)[] => [null, null, null, null, null,
* 问句与性别只作落款记录,**不参与任何计算**:本仓库不搬用神推断与五层 DAG。
*/
export default function LiuyaoView() {
const router = useRouter();
const [question, setQuestion] = useState('');
const [gender, setGender] = useState<'男' | '女'>('男');
const [method, setMethod] = useState<CastMode>('coin');
@@ -45,8 +54,9 @@ export default function LiuyaoView() {
timeInput: string;
} | null>(null);
const [error, setError] = useState('');
const [copied, setCopied] = useState(false);
const [savedId, setSavedId] = useState<string | null>(null);
/** 复原(?c= / ?case=)是否已经跑完:决定要不要显示「排盘中」占位 */
const [restoreSettled, setRestoreSettled] = useState(false);
const paperRef = useRef<HTMLDivElement | null>(null);
const restoredRef = useRef(false);
@@ -82,27 +92,51 @@ export default function LiuyaoView() {
[autoTime, timeInput, method, applyCast],
);
// 从卦例夹打开:?case=<id> —— 用记录里的输入重排同一卦
// 从历史排盘打开:?case=<id> —— 用记录里的输入重排同一卦
useEffect(() => {
if (restoredRef.current) return;
restoredRef.current = true;
const id = new URLSearchParams(window.location.search).get('case');
if (!id) return;
void (async () => {
const record = await getCaseStore().get(id);
if (!record || record.kind !== 'liuyao' || record.input.kind !== 'liuyao') {
setError('卦例不存在或类型不符');
return;
}
setQuestion(record.input.question ?? '');
setGender(record.input.gender ?? '男');
setMethod(record.input.method);
setTimeInput(record.timeInput);
const params = new URLSearchParams(window.location.search);
// 起卦页传来的同一卦:?c=011011&t=...&g=女&m=1&q=...
const cast = decodeCastState(params);
if (cast) {
setQuestion(cast.question);
setGender(cast.gender);
setMethod('coin');
setTimeInput(cast.timeInput);
setAutoTime(false);
applyCast(record.input.coins, record.timeInput, record.input.method);
applyCast(cast.coins, cast.timeInput, 'coin');
setRestoreSettled(true);
return;
}
const id = params.get('case');
if (!id) {
setRestoreSettled(true);
return;
}
void (async () => {
try {
const store = await getCaseStore();
const record = await store.get(id);
if (!record || record.kind !== 'liuyao' || record.input.kind !== 'liuyao') {
setError('卦例不存在或类型不符');
return;
}
setQuestion(record.input.question ?? '');
setGender(record.input.gender ?? '男');
setMethod(record.input.method);
setTimeInput(record.timeInput);
setAutoTime(false);
applyCast(record.input.coins, record.timeInput, record.input.method);
} finally {
setRestoreSettled(true);
}
})();
}, [applyCast]);
// 重起 = 回到首页的起卦台(本页表单是旧版备用入口,不再作为默认起点)
const handleReset = () => {
setResult(null);
setManual(emptyManual());
@@ -112,11 +146,11 @@ export default function LiuyaoView() {
setAutoTime(true);
setTimeInput(nowTimeInput());
setSavedId(null);
window.scrollTo({ top: 0, behavior: 'smooth' });
router.replace('/');
};
const handleSave = async () => {
if (!result) return;
if (!result || savedId) return;
try {
const record = buildLiuyaoRecord({
chart: result.chart,
@@ -127,7 +161,8 @@ export default function LiuyaoView() {
method: result.method,
coins: result.coins,
});
await getCaseStore().save(record);
const store = await getCaseStore();
await store.save(record);
setSavedId(record.id);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
@@ -138,104 +173,45 @@ export default function LiuyaoView() {
? chartToBoardProps(result.chart, result.time, question, gender)
: null;
const handleCopy = async () => {
if (!boardProps) return;
try {
await navigator.clipboard.writeText(boardToText(boardProps));
setCopied(true);
setTimeout(() => setCopied(false), 1800);
} catch {
/* 隐私模式或未授权:静默 */
}
};
const readingFacts = useMemo(
() => (result ? buildLiuyaoReadingFacts(result.chart, result.time, question) : null),
[result, question],
);
const manualComplete = manual.every((v): v is CoinResult => v !== null);
/**
* 三态门:boot(首帧,静态页 SSR 出来的就是它)→ restoring(带参数,正在复原)/ form(无参数,旧表单)。
*
* 为什么要有 boot:本页是静态预渲染,SSR 出来的 HTML 只能是「起卦表单」;
* 从案例 / 历史排盘带 ?c=… 进来时,若不先挡一层,会先闪一下那张过期表单再跳到盘面。
* 判定放在 layout effect 里(不在 render 里读 window),SSR 与客户端首帧因此一致,不会 hydration 报错。
*/
const [phase, setPhase] = useState<'boot' | 'restoring' | 'form'>('boot');
useIsoLayoutEffect(() => {
const p = new URLSearchParams(window.location.search);
setPhase(p.has('c') || p.has('case') ? 'restoring' : 'form');
}, []);
const awaitingRestore = !result && !restoreSettled && phase === 'restoring';
// ───────────────────────── 盘面(原项目结果页版式) ─────────────────────────
if (boardProps) {
if (boardProps && readingFacts) {
return (
<div className="flex min-h-screen flex-col items-center justify-start bg-[#F7F3EA] px-3 py-6 font-serif text-[#17140F] sm:px-6 sm:py-12">
{/* 顶部极简快捷操作栏 */}
<div className="mb-4 flex w-full max-w-3xl items-center justify-between px-2 text-xs text-[#7A6F62] sm:mb-6">
<div className="flex items-center gap-2">
<span className="inline-block h-2 w-2 rounded-full bg-[#9E2A2B]/70" />
<span className="text-sm font-bold tracking-widest text-[#4A4238]">古筮排盘</span>
</div>
<div className="flex items-center gap-2 sm:gap-3">
<Link
href="/cases"
className="hidden text-[11.5px] text-[#7A6F62] underline-offset-4 hover:text-[#9E2A2B] hover:underline sm:inline"
>
卦例夹
</Link>
<button
type="button"
onClick={() => void handleSave()}
disabled={Boolean(savedId)}
title={savedId ? '已保存到卦例夹' : '保存起卦输入,随时重排'}
className={`flex cursor-pointer items-center gap-1.5 rounded-lg border px-3 py-1.5 shadow-xs transition-all active:scale-95 disabled:cursor-default ${
savedId
? 'border-[#DCD6C5] bg-[#F3F0E4] text-[#8C7E6D]'
: 'border-[#DCD6C5] bg-[#F3F0E4] text-[#4A4238] hover:bg-[#EAE5D4]'
}`}
>
<Star size={13} fill={savedId ? 'currentColor' : 'none'} />
<span>{savedId ? '已保存' : '保存卦例'}</span>
</button>
<button
type="button"
onClick={handleCopy}
className="flex cursor-pointer items-center gap-1.5 rounded-lg border border-[#DCD6C5] bg-[#F3F0E4] px-3 py-1.5 text-[#4A4238] shadow-xs transition-all hover:bg-[#EAE5D4] active:scale-95"
>
{copied ? '已复制' : '复制盘面'}
</button>
<button
type="button"
onClick={handleReset}
className="flex cursor-pointer items-center gap-1.5 rounded-lg border border-[#9E2A2B]/30 bg-[#9E2A2B]/10 px-3 py-1.5 font-medium text-[#9E2A2B] shadow-xs transition-all hover:bg-[#9E2A2B]/15 active:scale-95"
>
<RotateCcw size={13} />
<span>重起一卦</span>
</button>
</div>
</div>
<LiuyaoResult
boardProps={boardProps}
facts={readingFacts}
question={question}
onReset={handleReset}
onSave={handleSave}
/>
);
}
{/* 宣纸画卷卡片 */}
<div
ref={paperRef}
className="relative w-full max-w-3xl space-y-7 rounded-md border border-[#E0D8C9] bg-[#FFFDF8] p-5 shadow-[0_2px_12px_rgba(23,20,15,0.05)] transition-all sm:p-9"
>
{/* 上卷:古法卦单 */}
<section className="w-full">
<HexagramBoard {...boardProps} />
</section>
{/* 下卷:裁剪说明(原项目此处为解卦手札,本仓库不含大模型解卦) */}
<section className="space-y-3 border-t border-[#E8DFC9] pt-4">
<div className="flex items-center gap-2 text-xs font-bold tracking-[0.25em] text-[#6E6355]">
<span className="inline-block h-[5px] w-[5px] rounded-full bg-[#9E2A2B]/70" />
<span>收 盘 说 明</span>
</div>
<p className="text-[12.5px] leading-relaxed text-[#7D7060]">
本页只做确定性排盘:纳甲装卦 · 安世应 · 定六亲 · 旬空 · 伏神 · 六神 · 月卦身 · 十三神煞。
不含用神取舍、生克旺衰、吉凶断语与应期,也不调用大模型解卦。
</p>
<p className="text-[12px] leading-relaxed text-[#9C907F]">
所问与性别只作落款记录,未参与任何计算。
</p>
</section>
</div>
{/* 底部极简知照 */}
<div className="mt-4 w-full max-w-3xl text-center text-[11px] text-[#9C907F]">
<span>易象昭然,以卦观事;谋事在人,成事在天。关键决策请结合客观现实明察审断。</span>
</div>
{error && (
<div className="mt-3 w-full max-w-3xl rounded-[3px] border border-[#d9a99f] bg-[#fdf2ef] px-3 py-2 text-center text-[11.5px] text-[#8e3a2c]">
{error}
</div>
)}
// 首帧 / 复原中:给一张空白纸,绝不先闪出旧表单
if (phase === 'boot' || awaitingRestore) {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-2 bg-[#F4F1E8] font-song text-[12.5px] tracking-[0.2em] text-[#8C8272]">
<span>{phase === 'boot' ? '载入中…' : '排盘中…'}</span>
</div>
);
}
@@ -253,7 +229,7 @@ export default function LiuyaoView() {
</div>
<div className="flex shrink-0 items-center gap-3 font-serif text-[11.5px] text-[#5e5a50]">
<Link href="/cases" className="underline-offset-4 transition-colors hover:text-[#8e3a2c] hover:underline">
卦例夹
历史排盘
</Link>
<Link href="/" className="underline-offset-4 transition-colors hover:text-[#8e3a2c] hover:underline">
返回首页
+345
View File
@@ -0,0 +1,345 @@
'use client';
/**
* 解卦面板(禅意版)
* ==================
* - 只在六爻盘面下方出现一个「解 卦」入口,默认不占版面;
* - 点击后把**盘面事实**发到服务端(密钥只在服务端),流式接收,逐字落下;
* - 四段口径:取用 / 盘面 / 走势 / 应期(prompt 在 app/api/read/prompt.ts);
* - 排版取「纸上批注」:窄栏、宽行距、竖排小标、朱砂光标,不写报告体;
* - 事实抽屉:可以看见到底发送了什么(不含任何密钥)。
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { ReadingFacts } from '@/lib/readings/types';
import { isLlmConfigured, llmRequestPayload, loadLlmSettings } from '@/lib/llm/settings';
type Phase = 'idle' | 'streaming' | 'done' | 'error';
interface Block {
type: 'h' | 'p';
text: string;
/** 标题的序号(一 / 二 / 三…),仅 type === 'h' 时有 */
numeral?: string;
}
const HEADING_LINE =
/^(?:[【〔]\s*([一二三四五六七八九十]+)\s*[】〕]|([一二三四五六七八九十]+)\s*[、..])\s*(.+)$/;
/** 按行解析:短标题行单独成段,其余行合并成段落(处理「标题+正文同一段」) */
function parseBlocks(text: string): Block[] {
const out: Block[] = [];
let buf: string[] = [];
const flush = () => {
const s = buf.join('').trim();
if (s) out.push({ type: 'p', text: s });
buf = [];
};
for (const raw of text.replace(/\r/g, '').split('\n')) {
const line = raw.replace(/\*\*/g, '').replace(/^#+\s*/, '').trim();
if (!line) {
flush();
continue;
}
const m = line.match(HEADING_LINE);
const numeral = m ? (m[1] ?? m[2]) : null;
const title = m ? m[3].trim() : '';
if (numeral && title && title.length <= 18) {
flush();
out.push({ type: 'h', text: title, numeral });
continue;
}
buf.push(line);
}
flush();
return out;
}
/**
* 四段式排版:① 取用 → ② 盘面 → ③ 走势 → ④ 应期
* 序号入圆标,标题后接一根发丝线,正文窄栏宽行距,不用报告体。
*/
function renderBlocks(text: string) {
return parseBlocks(text).map((block, i) =>
block.type === 'h' ? (
<h3 key={i} data-block="h" className="mb-3 mt-7 flex items-center gap-2.5 first:mt-0">
<span className="flex h-[21px] w-[21px] shrink-0 items-center justify-center rounded-full bg-[#3E5148] font-song text-[11.5px] leading-none text-[#F6EFDC]">
{block.numeral}
</span>
<span className="shrink-0 font-song text-[14.5px] font-semibold tracking-[0.14em] text-[#2E3B33] lg:text-[15.5px]">
{block.text}
</span>
<span aria-hidden className="h-px flex-1 bg-[#D9CFB8]" />
</h3>
) : (
<p
key={i}
data-block="p"
className="mb-4 indent-8 text-justify text-[14.5px] leading-[2.05] tracking-[0.01em] text-[#3B372F] last:mb-0 lg:text-[15.5px] lg:leading-[2.15]"
>
{block.text}
</p>
),
);
}
export interface ReadingPanelHandle {
start: () => void;
stop: () => void;
}
export interface ReadingPanelProps {
/** 六爻盘面事实(kind='liuyao') */
facts: ReadingFacts;
/** 正文增量回调(用于解析用神、底部按钮状态) */
onTextChange?: (text: string) => void;
onPhaseChange?: (phase: Phase) => void;
/** 是否隐藏面板自带的入口按钮(页面底部已有主按钮时用) */
hideIdleButton?: boolean;
/** 外层间距(PC 两栏时右侧不需要 mt-7) */
className?: string;
}
const ReadingPanel = React.forwardRef<ReadingPanelHandle, ReadingPanelProps>(function ReadingPanel(
{ facts, onTextChange, onPhaseChange, hideIdleButton, className = 'mt-7' },
ref,
) {
const [phase, setPhase] = useState<Phase>('idle');
const [text, setText] = useState('');
const [error, setError] = useState('');
const [showFacts, setShowFacts] = useState(false);
const [copied, setCopied] = useState(false);
const [elapsed, setElapsed] = useState(0);
const sectionRef = useRef<HTMLElement | null>(null);
const abortRef = useRef<AbortController | null>(null);
const stickRef = useRef(true);
const startedAtRef = useRef(0);
// 换一卦就重置
useEffect(() => {
abortRef.current?.abort();
setPhase('idle');
setText('');
setError('');
setShowFacts(false);
}, [facts]);
useEffect(() => {
return () => abortRef.current?.abort();
}, []);
useEffect(() => {
const onScroll = () => {
stickRef.current = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 160;
};
window.addEventListener('scroll', onScroll, { passive: true });
return () => window.removeEventListener('scroll', onScroll);
}, []);
useEffect(() => {
if (phase === 'streaming' && stickRef.current) {
window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'auto' });
}
}, [text, phase]);
useEffect(() => {
if (phase !== 'streaming') return;
const id = window.setInterval(() => {
setElapsed(Math.floor((Date.now() - startedAtRef.current) / 1000));
}, 1000);
return () => window.clearInterval(id);
}, [phase]);
const run = useCallback(async () => {
// 大模型配置只在用户本机浏览器里;没配就先让去右上角「设置」,别发空请求
const settings = loadLlmSettings();
if (!isLlmConfigured(settings)) {
setError('还没有配置大模型:点右上角「设置」,填入接口地址、模型与 API Key(只保存在本机浏览器)。');
setPhase('error');
return;
}
abortRef.current?.abort();
const ctrl = new AbortController();
abortRef.current = ctrl;
startedAtRef.current = Date.now();
setElapsed(0);
setPhase('streaming');
setText('');
setError('');
// 起解即把「解卦位置」带到视野里(移动端底部有固定动作条,留一点上边距)
sectionRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
try {
const res = await fetch('/api/read', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ facts, llm: settings ? llmRequestPayload(settings) : undefined }),
signal: ctrl.signal,
});
if (!res.ok) {
const json = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(json.error || `解卦服务不可用(${res.status})`);
}
if (!res.body) throw new Error('解卦响应为空');
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let idx = buffer.indexOf('\n\n');
while (idx >= 0) {
const chunk = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
idx = buffer.indexOf('\n\n');
for (const line of chunk.split('\n')) {
if (!line.startsWith('data:')) continue;
const payload = line.slice(5).trim();
if (!payload || payload === '[DONE]') continue;
const evt = JSON.parse(payload) as { content?: string; error?: string; done?: boolean };
if (typeof evt.error === 'string') throw new Error(evt.error);
if (typeof evt.content === 'string') setText((prev) => prev + evt.content);
if (evt.done) setPhase('done');
}
}
}
setPhase((p) => (p === 'streaming' ? 'done' : p));
} catch (e) {
if ((e as Error).name === 'AbortError') {
setPhase((p) => (p === 'streaming' ? 'done' : p));
return;
}
setError((e as Error).message);
setPhase('error');
}
}, [facts]);
const stop = () => {
abortRef.current?.abort();
setPhase('done');
};
const copy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
window.setTimeout(() => setCopied(false), 1800);
} catch {
/* 忽略 */
}
};
const blocks = useMemo(() => renderBlocks(text), [text]);
useEffect(() => {
onTextChange?.(text);
}, [text, onTextChange]);
useEffect(() => {
onPhaseChange?.(phase);
}, [phase, onPhaseChange]);
React.useImperativeHandle(ref, () => ({ start: () => void run(), stop }), [run]);
if (phase === 'idle' && hideIdleButton) {
return null;
}
if (phase === 'idle') {
return (
<section className={`border-t border-[#E8DFC9] pt-6 ${className}`}>
<div className="flex flex-col items-center gap-2.5 py-2">
<button
type="button"
onClick={() => void run()}
className="group inline-flex h-10 items-center justify-center border border-[#C9BCA6] px-9 font-serif text-[12.5px] tracking-[0.45em] text-[#5E5A50] transition-colors hover:border-[#8A8378] hover:text-[#22201B]"
>
解 卦
</button>
<p className="font-serif text-[10.5px] tracking-[0.08em] text-[#9C907F]">
以盘面事实为凭 · 不作吉凶承诺
</p>
</div>
</section>
);
}
return (
<section ref={sectionRef} className={`scroll-mt-20 ${className}`}>
<div className="relative mx-auto max-w-[680px]">
{phase === 'streaming' && !text && (
<div className="flex flex-col items-center gap-3 py-9">
<span className="relative flex h-9 w-9 items-center justify-center" aria-hidden>
<span className="ink-ripple absolute inset-0 rounded-full border border-[#B08A5E]/60" />
<span className="ink-ripple absolute inset-0 rounded-full border border-[#B08A5E]/40 [animation-delay:900ms]" />
<span className="ink-drop h-2.5 w-2.5 rounded-full bg-[#8E6337]" />
</span>
<p className="font-song text-[12.5px] tracking-[0.22em] text-[#8A7A60]">
研墨中{elapsed >= 2 ? ` · ${elapsed}s` : ''}
</p>
<p className="font-kai text-[11px] tracking-[0.06em] text-[#A79C8A]">
{elapsed >= 20 ? '正在依盘面事实推演,思考模式首字稍慢' : '依盘面事实起卦辞,请稍候'}
</p>
</div>
)}
{text && (
<div aria-live="polite">
{blocks}
{phase === 'streaming' && (
<span className="ml-[2px] inline-block h-[0.95em] w-[1px] translate-y-[0.12em] animate-pulse bg-[#8E3A2C]/60" />
)}
</div>
)}
{error && (
<div className="mt-4 space-y-1.5 font-serif text-[12px] leading-relaxed text-[#8e3a2c]">
<p>{error}</p>
<p className="text-[11px] text-[#9C907F]">
{/繁忙|429|overloaded|capacity/i.test(error)
? '上游瞬时繁忙,服务端已自动重试过;稍等几秒点「重 试」即可,不会重复计费。'
: '检查右上角「设置」里的接口地址、模型名与 API Key;「测试连接」能直接看到上游返回。'}
</p>
</div>
)}
<div className="mt-6 flex flex-wrap items-center justify-center gap-x-4 gap-y-2 border-t border-dashed border-[#E4DCCB] pt-3 font-serif text-[11px] text-[#8C8272]">
{phase === 'streaming' ? (
<button type="button" onClick={stop} className="cursor-pointer tracking-[0.2em] hover:text-[#22201B]">
停 止
</button>
) : phase === 'error' ? (
<button type="button" onClick={() => void run()} className="cursor-pointer tracking-[0.2em] hover:text-[#22201B]">
重 试
</button>
) : null}
{text && (
<button type="button" onClick={() => void copy()} className="cursor-pointer hover:text-[#22201B]">
{copied ? '已复制' : '复制'}
</button>
)}
<button type="button" onClick={() => setShowFacts((v) => !v)} className="cursor-pointer hover:text-[#22201B]">
所呈事实
</button>
</div>
{/* 事实抽屉:隐藏展开,能看见到底发送了什么(不含任何密钥) */}
{showFacts && (
<pre className="mt-3 max-h-[260px] overflow-auto whitespace-pre-wrap border border-[#E4DCCB] bg-[#FBF8F1] p-3 font-mono text-[10.5px] leading-relaxed text-[#7C7365]">
{JSON.stringify(facts, null, 2)}
</pre>
)}
</div>
</section>
);
});
export default ReadingPanel;
+57
View File
@@ -0,0 +1,57 @@
'use client';
import React, { useEffect, useRef, useState } from 'react';
import HexagramBoard, { BOARD_BASE_WIDTH, type HexagramBoardProps } from './HexagramBoard';
/**
* 盘面自适应容器
* ==============
* 古籍盘面是一套定宽栅格(六神 32 / 纳甲 68 / 爻画 46 / 世应 18 / 动爻 22 / 变卦 68 / 46 / 52),
* 合计约 390。手机可用宽度只有 ~350,早先版本直接裁切变卦列。
*
* 这里的做法不是重排版式,而是**整体等比缩放**:版式关系与字号相对关系保持原样,
* 390 是基准,窄屏按容器宽度缩到 0.8 左右,宽屏不放大(避免字太大失古意)。
*/
export default function ResponsiveBoard(props: HexagramBoardProps) {
const wrapRef = useRef<HTMLDivElement | null>(null);
const [scale, setScale] = useState(1);
const [height, setHeight] = useState<number | undefined>(undefined);
const innerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const wrap = wrapRef.current;
if (!wrap) return;
const measure = () => {
const available = wrap.clientWidth;
const next = Math.min(1, Math.max(0.7, available / BOARD_BASE_WIDTH));
setScale(next);
// 缩放后实际占位高度要同步,否则下方会留一大块空白
const natural = innerRef.current?.offsetHeight ?? 0;
setHeight(natural ? natural * next : undefined);
};
measure();
const ro = new ResizeObserver(measure);
ro.observe(wrap);
if (innerRef.current) ro.observe(innerRef.current);
return () => ro.disconnect();
}, []);
return (
<div ref={wrapRef} className="w-full" style={{ height }}>
<div
ref={innerRef}
style={{
width: BOARD_BASE_WIDTH,
transform: `scale(${scale})`,
transformOrigin: 'top left',
// 让缩放后的盘面在容器里居中
marginLeft: `calc(50% - ${(BOARD_BASE_WIDTH * scale) / 2}px)`,
}}
>
<HexagramBoard {...props} />
</div>
</div>
);
}
+75
View File
@@ -0,0 +1,75 @@
'use client';
import React from 'react';
/**
* 山水页景(轻 SVG,不依赖图片资源)
* ================================
* 只做浅墨的空间氛围,不抢交互;移动端宽度变窄时两侧自然裁边。
*/
export default function InkLandscape() {
return (
<svg
aria-hidden="true"
viewBox="0 0 1440 440"
preserveAspectRatio="none"
className="pointer-events-none absolute inset-x-0 top-0 h-[235px] w-full sm:h-[260px] lg:h-[285px]"
>
<defs>
<linearGradient id="mistWash" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#AFC2C7" stopOpacity="0.20" />
<stop offset="1" stopColor="#AFC2C7" stopOpacity="0.02" />
</linearGradient>
<linearGradient id="mountainWash" x1="0" y1="0" x2="0.8" y2="1">
<stop offset="0" stopColor="#81989B" stopOpacity="0.10" />
<stop offset="1" stopColor="#687C80" stopOpacity="0.22" />
</linearGradient>
</defs>
{/* 山雾铺底 */}
<path d="M0 260 C180 205 260 300 420 258 C570 218 650 292 790 264 C970 220 1090 270 1230 220 C1320 190 1380 205 1440 175 L1440 440 L0 440Z" fill="url(#mistWash)" />
{/* 左上:老枝与疏叶 */}
<g fill="none" stroke="#657875" strokeLinecap="round" strokeLinejoin="round" opacity="0.30">
<path d="M-30 105 C70 90 104 126 176 112 C230 100 252 60 324 50" strokeWidth="3" />
<path d="M48 98 C72 63 90 38 111 13 M88 111 C116 77 139 65 160 47 M160 113 C187 87 215 82 244 69 M237 79 C264 53 286 38 316 34" strokeWidth="1.8" />
<path d="M72 67 C59 51 45 47 31 48 M91 47 C79 31 69 25 56 24 M113 78 C99 62 87 57 73 58 M138 64 C132 45 122 35 108 31 M184 91 C175 70 164 63 149 60 M213 83 C207 65 197 55 185 50 M264 53 C252 39 241 34 228 33 M288 40 C285 26 280 16 270 8" strokeWidth="1.3" />
</g>
<g fill="#657875" opacity="0.22">
<ellipse cx="34" cy="48" rx="10" ry="4" transform="rotate(28 34 48)" />
<ellipse cx="57" cy="24" rx="10" ry="4" transform="rotate(35 57 24)" />
<ellipse cx="75" cy="58" rx="10" ry="4" transform="rotate(22 75 58)" />
<ellipse cx="109" cy="31" rx="11" ry="4" transform="rotate(40 109 31)" />
<ellipse cx="151" cy="60" rx="11" ry="4" transform="rotate(18 151 60)" />
<ellipse cx="187" cy="50" rx="10" ry="4" transform="rotate(24 187 50)" />
<ellipse cx="230" cy="33" rx="10" ry="4" transform="rotate(30 230 33)" />
<ellipse cx="271" cy="8" rx="10" ry="4" transform="rotate(55 271 8)" />
</g>
{/* 右侧:远山 */}
<g fill="none" stroke="#627A7F" strokeLinecap="round" strokeLinejoin="round" opacity="0.25">
<path d="M770 282 C860 242 888 178 948 137 C1003 100 1035 145 1074 170 C1120 115 1151 50 1213 37 C1271 24 1308 112 1340 142 C1375 125 1400 94 1460 83" strokeWidth="2" />
<path d="M794 291 C877 257 910 205 954 173 C1000 141 1029 174 1065 197 M1082 185 C1125 141 1164 80 1214 68 C1260 58 1294 139 1332 170 M1260 230 C1322 193 1368 167 1442 158" strokeWidth="1.2" />
<path d="M914 229 C938 214 951 209 970 206 M1172 112 C1197 97 1218 95 1237 99 M1338 187 C1374 172 1405 172 1429 177" strokeWidth="1" />
</g>
<path d="M770 282 C860 242 888 178 948 137 C1003 100 1035 145 1074 170 C1120 115 1151 50 1213 37 C1271 24 1308 112 1340 142 C1375 125 1400 94 1460 83 L1460 310 C1320 320 1190 294 1050 310 C930 323 850 314 770 330Z" fill="url(#mountainWash)" />
{/* 山巅小亭:细线,不做写实插画抢视觉 */}
<g fill="none" stroke="#596D70" strokeLinecap="round" strokeLinejoin="round" opacity="0.32" strokeWidth="1.5">
<path d="M1280 130 L1354 130 M1288 130 L1296 114 L1315 103 L1333 114 L1345 130 M1296 114 L1320 114 L1340 114 M1300 130 L1300 158 M1338 130 L1338 158 M1297 158 L1341 158 M1308 114 L1308 158 M1327 114 L1327 158" />
<path d="M1285 111 L1320 92 L1350 111 M1291 109 L1320 97 L1345 109 M1305 101 L1305 94 M1320 93 L1320 86 M1334 101 L1334 94" />
</g>
{/* 飞鸟 */}
<g fill="none" stroke="#53676B" strokeLinecap="round" opacity="0.28" strokeWidth="1.4">
<path d="M1058 82 q8 -7 15 0 q7 -7 15 0 M1093 98 q6 -5 12 0 q6 -5 12 0 M1017 105 q5 -4 10 0 q5 -4 10 0" />
</g>
{/* 远岸 / 小舟 */}
<g fill="none" stroke="#657875" strokeLinecap="round" strokeLinejoin="round" opacity="0.23" strokeWidth="1.3">
<path d="M72 405 C134 395 205 411 278 401 M90 414 C160 407 213 420 300 411" />
<path d="M164 392 L214 392 L202 400 L174 400 Z M187 377 L187 392 M188 378 L204 389 L188 389" />
</g>
</svg>
);
}
+34
View File
@@ -0,0 +1,34 @@
'use client';
/**
* 注册 Service Worker。
*
* 只在**非本机域名**上注册:本地(localhost / 127.0.0.1 / *.local)改代码时,
* SW 缓存会把旧 chunk 留在浏览器里,排查问题很费劲;若之前装过,这里顺手注销。
*/
import { useEffect } from 'react';
export default function ServiceWorkerRegister() {
useEffect(() => {
if (typeof window === 'undefined' || !('serviceWorker' in navigator)) return;
const host = window.location.hostname;
const isLocal =
host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]' || host.endsWith('.local');
if (isLocal) {
void navigator.serviceWorker.getRegistrations().then((rs) => rs.forEach((r) => void r.unregister()));
return;
}
const register = () => {
void navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => {
/* 隐私模式或浏览器禁用:不影响正常使用 */
});
};
if (document.readyState === 'complete') register();
else window.addEventListener('load', register, { once: true });
}, []);
return null;
}
+299
View File
@@ -0,0 +1,299 @@
'use client';
/**
* 设置 · 大模型
* ==============
* 全站只有这一处设置:解卦用的大模型。
* 只存**本机浏览器** localStorage(`liuyao.llm.v1`),不上传、不入库;
* 每次解卦时随请求发给本站 `/api/read`,服务端只做一次转发。
*
* 通用性:按「OpenAI 兼容 /chat/completions」做,预置常见供应商,也能自己填任意网关。
*/
import React, { useEffect, useState } from 'react';
import { Eye, EyeOff, X } from 'lucide-react';
import {
LLM_PROVIDERS,
clearLlmSettings,
findProvider,
isLlmConfigured,
llmRequestPayload,
loadLlmSettings,
saveLlmSettings,
validateLlmSettings,
type LlmSettings,
} from '@/lib/llm/settings';
const EMPTY: LlmSettings = { provider: 'deepseek', baseUrl: 'https://api.deepseek.com/v1', model: 'deepseek-chat', apiKey: '', thinking: 'disabled' };
const FIELD =
'h-10 w-full rounded-[3px] border border-[#D9CDB6] bg-white px-2.5 font-mono text-[12.5px] text-[#2F4438] outline-none transition-colors focus:border-[#9A7040]';
export default function SettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const [draft, setDraft] = useState<LlmSettings>(EMPTY);
const [showKey, setShowKey] = useState(false);
const [error, setError] = useState('');
const [notice, setNotice] = useState('');
const [testing, setTesting] = useState(false);
const [saved, setSaved] = useState(false);
useEffect(() => {
if (!open) return;
setDraft(loadLlmSettings() ?? EMPTY);
setError('');
setNotice('');
setSaved(isLlmConfigured(loadLlmSettings()));
}, [open]);
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', onKey);
return () => document.removeEventListener('keydown', onKey);
}, [open, onClose]);
if (!open) return null;
const preset = findProvider(draft.provider);
const pickProvider = (id: string) => {
const p = findProvider(id);
setDraft((d) => ({
...d,
provider: id,
baseUrl: p?.baseUrl ?? '',
model: p?.models[0] ?? '',
thinking: id === 'deepseek' ? d.thinking : undefined,
}));
setNotice('');
setError('');
};
const onSave = () => {
const msg = validateLlmSettings(draft);
if (msg) {
setError(msg);
return;
}
saveLlmSettings(draft);
setError('');
setSaved(true);
setNotice('已保存到本机浏览器');
};
const onClear = () => {
clearLlmSettings();
setDraft(EMPTY);
setSaved(false);
setNotice('已清除本机保存的设置');
setError('');
};
const onTest = async () => {
const msg = validateLlmSettings(draft);
if (msg) {
setError(msg);
return;
}
setTesting(true);
setError('');
setNotice('');
try {
const res = await fetch('/api/llm-test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(llmRequestPayload(draft)),
});
const json = (await res.json()) as { ok?: boolean; error?: string; sample?: string };
if (json.ok) setNotice(`连接正常${json.sample ? `:${json.sample}` : ''}`);
else setError(json.error || '连接失败');
} catch (e) {
setError((e as Error).message);
} finally {
setTesting(false);
}
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-ink-900/35 px-3 backdrop-blur-[2px] sm:px-5"
onClick={onClose}
role="dialog"
aria-modal="true"
aria-label="设置"
>
<div
className="max-h-[92vh] w-full max-w-[560px] overflow-y-auto border border-[#CDBB96] bg-[#FCF8EF] px-5 pb-5 pt-4 shadow-[0_18px_50px_rgba(53,45,31,0.22)]"
style={{ borderRadius: 10 }}
onClick={(e) => e.stopPropagation()}
>
<div className="mb-1 flex items-start justify-between gap-3">
<div>
<p className="font-kai text-[10.5px] tracking-[0.18em] text-[#9A805A]">设置</p>
<h2 className="mt-1 font-song text-[19px] font-semibold tracking-[0.1em] text-[#2F4438]">大模型解读</h2>
</div>
<button
type="button"
onClick={onClose}
aria-label="关闭设置"
className="press flex h-8 w-8 items-center justify-center rounded-full text-[#8C8272] hover:bg-[#F1EBDE] hover:text-[#2F4438]"
>
<X size={16} strokeWidth={1.8} />
</button>
</div>
<p className="mb-4 font-song text-[11.5px] leading-[1.9] text-[#7C7668]">
解卦需要一个大模型。填好后<strong className="font-semibold text-[#3F4A42]">只保存在本机浏览器</strong>
(localStorage),不上传服务器、不入库;每次解卦时随请求转发一次。
支持任意「OpenAI 兼容」接口,换供应商只要改这里。
</p>
<div className="space-y-3">
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">供应商</label>
<select
value={draft.provider}
onChange={(e) => pickProvider(e.target.value)}
className="h-10 w-full rounded-[3px] border border-[#D9CDB6] bg-white px-2.5 font-song text-[13px] text-[#2F4438] outline-none focus:border-[#9A7040]"
>
{LLM_PROVIDERS.map((p) => (
<option key={p.id} value={p.id}>
{p.label}
</option>
))}
</select>
{preset?.hint && <p className="mt-1 font-song text-[10.5px] text-[#A79C8A]">{preset.hint}</p>}
</div>
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">
接口地址 <span className="text-[#A79C8A]">(Base URL,填到 /v1 为止)</span>
</label>
<input
value={draft.baseUrl}
onChange={(e) => setDraft({ ...draft, baseUrl: e.target.value })}
placeholder="https://api.deepseek.com/v1"
spellCheck={false}
className={FIELD}
/>
</div>
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">模型</label>
<input
value={draft.model}
onChange={(e) => setDraft({ ...draft, model: e.target.value })}
placeholder="deepseek-chat"
spellCheck={false}
list="llm-models"
className={FIELD}
/>
<datalist id="llm-models">
{(preset?.models ?? []).map((m) => (
<option key={m} value={m} />
))}
</datalist>
</div>
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">API Key</label>
<div className="flex items-center gap-1.5">
<input
type={showKey ? 'text' : 'password'}
value={draft.apiKey}
onChange={(e) => setDraft({ ...draft, apiKey: e.target.value })}
placeholder={preset && !preset.needsKey ? '本地模型可留空' : 'sk-...'}
spellCheck={false}
autoComplete="off"
className={FIELD}
/>
<button
type="button"
onClick={() => setShowKey((v) => !v)}
aria-label={showKey ? '隐藏密钥' : '显示密钥'}
className="press flex h-10 w-10 shrink-0 items-center justify-center rounded-[3px] border border-[#D9CDB6] text-[#7C7668] hover:text-[#2F4438]"
>
{showKey ? <EyeOff size={15} strokeWidth={1.7} /> : <Eye size={15} strokeWidth={1.7} />}
</button>
</div>
</div>
{draft.provider === 'deepseek' && (
<div className="grid grid-cols-2 gap-2">
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">思考模式</label>
<select
value={draft.thinking ?? 'default'}
onChange={(e) =>
setDraft({
...draft,
thinking: e.target.value === 'default' ? undefined : (e.target.value as 'enabled' | 'disabled'),
})
}
className="h-10 w-full rounded-[3px] border border-[#D9CDB6] bg-white px-2.5 font-song text-[12.5px] text-[#2F4438] outline-none focus:border-[#9A7040]"
>
<option value="default">默认</option>
<option value="enabled">开启</option>
<option value="disabled">关闭</option>
</select>
</div>
<div>
<label className="mb-1 block font-song text-[12px] text-[#665F52]">思考强度</label>
<select
value={draft.reasoningEffort ?? ''}
onChange={(e) =>
setDraft({
...draft,
reasoningEffort: e.target.value ? (e.target.value as 'low' | 'high' | 'max') : undefined,
})
}
className="h-10 w-full rounded-[3px] border border-[#D9CDB6] bg-white px-2.5 font-song text-[12.5px] text-[#2F4438] outline-none focus:border-[#9A7040]"
>
<option value="">不指定</option>
<option value="low">low</option>
<option value="high">high</option>
<option value="max">max</option>
</select>
</div>
</div>
)}
</div>
{error && <p className="mt-3 font-song text-[11.5px] leading-relaxed text-[#8E3A2C]">{error}</p>}
{notice && !error && <p className="mt-3 font-song text-[11.5px] text-[#3F6B55]">{notice}</p>}
<div className="mt-4 flex flex-wrap items-center gap-2">
<button
type="button"
onClick={onSave}
className="press inline-flex h-10 flex-1 items-center justify-center rounded-[3px] border border-[#D8C392]/50 bg-[linear-gradient(180deg,#456557_0%,#29453B_100%)] px-4 font-song text-[13.5px] tracking-[0.14em] text-[#F5E9CB] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"
>
保存到本机
</button>
<button
type="button"
onClick={() => void onTest()}
disabled={testing}
className="press inline-flex h-10 items-center justify-center rounded-[3px] border border-[#C3B79E] bg-[#FBF7EC] px-3.5 font-song text-[12.5px] text-[#3F4A42] disabled:opacity-60"
>
{testing ? '测试中…' : '测试连接'}
</button>
<button
type="button"
onClick={onClear}
className="press inline-flex h-10 items-center justify-center rounded-[3px] px-2.5 font-song text-[12px] text-[#8C8272] hover:text-[#8E3A2C]"
>
清除
</button>
</div>
<p className="mt-3 font-song text-[10.5px] leading-relaxed text-[#A79C8A]">
{saved ? '当前已保存配置:解卦可直接使用。' : '尚未保存:解卦前需要先在这里填好。'}
 密钥不会写入服务器数据库,也不会出现在任何日志里。
</p>
</div>
</div>
);
}
+140
View File
@@ -0,0 +1,140 @@
'use client';
/**
* 全站页头
* =========
* 左:站名「野鹤六爻」(毛笔艺术字);右:案例 / 历史排盘 + 设置(首页即六爻,不再单列入口)。
* 「设置」只管一件事:解卦用的大模型(存在本机浏览器)。
* 页面特有的动作(历史排盘、截图、保存卦例…)通过 `actions` 插到导航右侧,
* 保证「同一块牌子」出现在所有页面,而不用各页各写一套 header。
*/
import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import { createPortal } from 'react-dom';
import { Settings } from 'lucide-react';
import SettingsDialog from './SettingsDialog';
export type SiteSection = 'liuyao' | 'examples' | 'history' | 'classics';
const NAV: { id: SiteSection; label: string; href: string }[] = [
{ id: 'examples', label: '案例', href: '/examples' },
{ id: 'history', label: '历史排盘', href: '/cases' },
];
export interface SiteHeaderProps {
/** 当前所在栏目(高亮用),不传则都不高亮 */
active?: SiteSection;
/** 右侧附加动作(页面专属) */
actions?: React.ReactNode;
/** 是否显示三入口导航,默认显示 */
showNav?: boolean;
/** 吸顶(结果页用) */
sticky?: boolean;
/** 额外容器类名(如结果页的窄版式) */
className?: string;
/** 内容最大宽度,默认 1120 */
maxWidthClassName?: string;
/** 页头色调:默认暖纸;cool 用于冷白阅读页 */
tone?: 'warm' | 'cool';
}
export default function SiteHeader({
active,
actions,
showNav = true,
sticky = false,
className = '',
maxWidthClassName = 'max-w-[1120px]',
tone = 'warm',
}: SiteHeaderProps) {
const cool = tone === 'cool';
const [settingsOpen, setSettingsOpen] = useState(false);
const [mounted, setMounted] = useState(false);
// 页头有 backdrop-blur(会成为 fixed 后代的包含块),弹窗必须挂到 body 上
useEffect(() => setMounted(true), []);
return (
<header
className={[
sticky ? 'safe-top sticky top-0 z-30' : 'relative z-20',
cool ? 'border-b border-[#DCE3E5] bg-[#F7F9FA]/92 backdrop-blur-sm' : 'border-b border-[#C8BEA8]/60 bg-[#F6F2E9]/92 backdrop-blur-sm',
className,
]
.filter(Boolean)
.join(' ')}
>
<div
className={`mx-auto flex h-[54px] w-full ${maxWidthClassName} items-center justify-between gap-3 px-4 sm:px-6 lg:px-8`}
>
<Link href="/" className="flex shrink-0 items-center text-[#35443D] no-underline">
<span
className="font-brand text-[21px] leading-none tracking-[0.1em] sm:text-[23px]"
style={{ color: cool ? '#1D2326' : '#2F4438' }}
>
野鹤六爻
</span>
</Link>
<div className="flex min-w-0 items-center gap-3 sm:gap-5">
{showNav && (
<nav
aria-label="主导航"
className="flex items-center gap-3.5 whitespace-nowrap font-song text-[15px] text-[#5A564C] sm:gap-6 sm:text-[16px]"
>
{NAV.map((item) =>
item.id === active ? (
<Link
key={item.id}
href={item.href}
aria-current="page"
className="border-b-2 border-[#49675B] pb-1 font-medium text-[#34483E]"
>
{item.label}
</Link>
) : (
<Link key={item.id} href={item.href} className="hover:text-[#8E6337]">
{item.label}
</Link>
),
)}
</nav>
)}
<div className="flex shrink-0 items-center gap-2.5 whitespace-nowrap sm:gap-3">
{actions && (
<>
{showNav && <span aria-hidden className="hidden h-4 w-px bg-[#C8BEA8] sm:block" />}
{actions}
</>
)}
<span aria-hidden className="hidden h-4 w-px bg-[#C8BEA8] sm:block" />
<a
href="https://github.com/woniu336/liuyao"
target="_blank"
rel="noreferrer noopener"
aria-label="项目主页(GitHub)"
title="项目主页"
className="press flex h-8 items-center rounded-full border border-[#C3B79E] bg-[#FCF9F0]/70 px-3 font-song text-[12px] text-[#4A4438] no-underline transition-colors hover:border-[#9A7040] hover:text-[#8E6337]"
>
项目
</a>
<button
type="button"
onClick={() => setSettingsOpen(true)}
aria-label="设置大模型"
title="设置(大模型解读)"
className="press flex h-8 items-center gap-1.5 rounded-full border border-[#C3B79E] bg-[#FCF9F0]/70 px-3 font-song text-[12px] text-[#4A4438] transition-colors hover:border-[#9A7040] hover:text-[#8E6337]"
>
<Settings size={13} strokeWidth={1.7} />
设置
</button>
</div>
</div>
</div>
{mounted && createPortal(
<SettingsDialog open={settingsOpen} onClose={() => setSettingsOpen(false)} />,
document.body,
)}
</header>
);
}
+270
View File
@@ -0,0 +1,270 @@
'use client';
import React from 'react';
/**
* 设计系统 v2 基础件
* ==================
* 采纳的设计意见:
* 1. 主色(雾霾蓝)只做细线、选中态、次级强调,不做大面积填充;
* 主按钮改墨色,避免"理财 App"观感。
* 2. 控件去圆角化(3px),少色块、多描边与文字。
* 3. 分段控件改下划线式,不再用 iOS 胶囊。
* 4. 状态标签去胶囊底,用前置符号 + 字色区分。
* 5. 区块用留白 + 细分隔线,不靠"卡片套卡片"。
*/
type ButtonVariant = 'ink' | 'line' | 'text' | 'danger';
type ButtonSize = 'sm' | 'md' | 'lg';
const VARIANT: Record<ButtonVariant, string> = {
ink: 'bg-ink-900 text-paper-0 border border-ink-900 shadow-[inset_0_0_0_1px_rgba(255,255,255,0.10)] hover:bg-ink-800',
line: 'bg-transparent text-ink-800 border border-line-strong hover:border-ink-600 hover:text-ink-900',
text: 'bg-transparent text-ink-600 border border-transparent hover:text-ink-900',
danger: 'bg-transparent text-cinnabar-600 border border-cinnabar-500/50 hover:border-cinnabar-600',
};
const SIZE: Record<ButtonSize, string> = {
sm: 'h-9 px-3 text-[13px]',
md: 'h-11 px-5 text-[15px]',
lg: 'h-12 px-6 text-[16px]',
};
export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: ButtonVariant;
size?: ButtonSize;
block?: boolean;
}
export function Button({
variant = 'ink',
size = 'md',
block,
className = '',
children,
...rest
}: ButtonProps) {
return (
<button
type="button"
{...rest}
style={{ borderRadius: 2 }}
className={[
'press tap inline-flex select-none items-center justify-center gap-1.5 font-sans-cn font-medium',
'tracking-[0.04em] disabled:cursor-not-allowed disabled:opacity-40',
VARIANT[variant],
SIZE[size],
block ? 'w-full' : '',
className,
]
.filter(Boolean)
.join(' ')}
>
{children}
</button>
);
}
/** 版面分区:靠留白与细分隔线,不用描边卡片 */
export function Panel({
children,
className = '',
title,
hint,
}: {
children: React.ReactNode;
className?: string;
title?: React.ReactNode;
hint?: React.ReactNode;
}) {
return (
<section className={['py-5', className].filter(Boolean).join(' ')}>
{(title || hint) && (
<div className="mb-3 flex items-baseline justify-between gap-3">
{title && (
<h2 className="font-song text-[13.5px] font-semibold tracking-[0.2em] text-ink-900">{title}</h2>
)}
{hint && <span className="text-[11px] tracking-[0.04em] text-ink-500">{hint}</span>}
</div>
)}
{children}
</section>
);
}
/** 纸面:唯一"像个容器"的东西,仅用于盘面与解卦正文 */
export function Paper({
children,
className = '',
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div
className={['bg-paper-0 px-4 py-4', className].filter(Boolean).join(' ')}
style={{ borderRadius: 4, border: '1px solid var(--hairline)' }}
>
{children}
</div>
);
}
/** 状态标签:去胶囊,符号 + 字色 */
export function Tag({
children,
tone = 'mist',
mark = '·',
}: {
children: React.ReactNode;
tone?: 'mist' | 'gold' | 'cinnabar' | 'ink';
mark?: string;
}) {
const tones = {
mist: 'text-mist-700',
gold: 'text-gold-600',
cinnabar: 'text-cinnabar-600',
ink: 'text-ink-600',
} as const;
return (
<span className={`inline-flex items-baseline gap-1 text-[11.5px] tracking-[0.04em] ${tones[tone]}`}>
<span aria-hidden className="opacity-70">
{mark}
</span>
<span className="tabular-nums">{children}</span>
</span>
);
}
/** 分段:下划线式,像书页上的标签 */
export function Tabs<T extends string>({
value,
options,
onChange,
}: {
value: T;
options: { id: T; label: string }[];
onChange: (v: T) => void;
}) {
return (
<div className="flex items-end gap-6" role="tablist">
{options.map((o) => {
const active = o.id === value;
return (
<button
key={o.id}
type="button"
role="tab"
aria-selected={active}
onClick={() => onChange(o.id)}
className={[
'press relative pb-2 text-[14.5px] transition-colors',
active ? 'font-medium text-ink-900' : 'text-ink-500',
].join(' ')}
>
{o.label}
<span
aria-hidden
className={[
'absolute inset-x-0 -bottom-px h-px transition-colors opacity-80',
active ? 'bg-ink-900' : 'bg-transparent',
].join(' ')}
/>
</button>
);
})}
</div>
);
}
/**
* 进度点:初爻在下、上爻在上。
* 阳:实心墨点;阴:空心细环;动:朱砂空心环 + 中点。
* 刻意做得小而细,避免像"信号格"。
*/
export function ProgressDots({ values }: { values: { yang: boolean; moving?: boolean }[] }) {
return (
<div className="flex items-center gap-2">
{values.map((v, i) => (
<span
key={i}
className="relative inline-flex h-[11px] w-[11px] items-center justify-center"
aria-label={`第${i + 1}爻 ${v.yang ? '阳' : '阴'}${v.moving ? ' 动' : ''}`}
>
<span
className="absolute inset-0 rounded-full border"
style={{
borderColor: v.moving ? 'var(--yao-moving)' : v.yang ? 'var(--yao-yang)' : 'var(--mist-500)',
borderWidth: 1,
}}
/>
{v.yang && !v.moving && (
<span className="h-[5px] w-[5px] rounded-full" style={{ background: 'var(--yao-yang)' }} />
)}
{v.moving && <span className="h-[4px] w-[4px] rounded-full" style={{ background: 'var(--yao-moving)' }} />}
</span>
))}
</div>
);
}
/**
* 爻画:遵循古法盘面——阳一横、阴两段,粗实为常。
* 动爻改朱砂,但不加圆角、不加阴影。
*/
export function YaoBar({
yang,
moving,
width = 46,
height = 8,
}: {
yang: boolean;
moving?: boolean;
width?: number;
height?: number;
}) {
const color = moving ? 'var(--yao-moving)' : 'var(--yao-yang)';
if (yang) {
return <span style={{ width, height, background: color, display: 'block' }} />;
}
const seg = Math.floor((width - 8) / 2);
return (
<span style={{ display: 'flex', width, height, gap: 8 }}>
<span style={{ width: seg, height, background: color }} />
<span style={{ width: seg, height, background: color }} />
</span>
);
}
/** 顶部栏:不吸顶太重,滚过即融 */
export function AppBar({
title,
subtitle,
right,
}: {
title: React.ReactNode;
subtitle?: React.ReactNode;
right?: React.ReactNode;
}) {
return (
<header className="safe-top sticky top-0 z-20 bg-water-1/85 backdrop-blur-md">
<div className="mx-auto flex h-[52px] w-full max-w-[520px] items-center justify-between gap-3 px-5">
<div className="min-w-0">
<div className="truncate font-song text-[16.5px] font-semibold tracking-[0.1em] text-ink-900">{title}</div>
{subtitle && <div className="truncate text-[11px] text-ink-500">{subtitle}</div>}
</div>
{right}
</div>
</header>
);
}
export function BottomBar({ children }: { children: React.ReactNode }) {
return (
<div className="safe-bottom fixed inset-x-0 bottom-0 z-20 bg-water-1/92 backdrop-blur-md">
<div className="mx-auto w-full max-w-[520px] px-5 pt-2.5" style={{ borderTop: '1px solid var(--hairline)' }}>
{children}
</div>
</div>
);
}
-30
View File
@@ -1,30 +0,0 @@
'use client';
import React from 'react';
interface FoldSectionProps {
title: string;
/** 收起时也显示的一行摘要,让读者不必展开就知道里面是什么 */
summary?: string;
children: React.ReactNode;
}
/**
* 折叠段:正推演化、盘面详录这类「要看时才看」的内容。
*
* 早先它们是两张与九宫同规格的卡,视觉上和主盘平起平坐,
* 六张同宽同底色的卡摞下来,读者分不出哪块该先看。
* 收起成一行后,首屏只剩「象 → 结论 → 宫」三件事。
*/
export default function FoldSection({ title, summary, children }: FoldSectionProps) {
return (
<details className="group border-t border-[#DED6C6]">
<summary className="flex cursor-pointer list-none items-center gap-2.5 py-3 text-[11.5px] text-[#5E5A50] transition-colors hover:text-[#22201B]">
<span className="w-2 text-[8px] transition-transform group-open:rotate-90">▸</span>
<b className="font-serif text-[11.5px] font-semibold tracking-[0.12em] text-[#22201B]">{title}</b>
{summary && <span className="truncate">{summary}</span>}
</summary>
<div className="pb-4">{children}</div>
</details>
);
}
-84
View File
@@ -1,84 +0,0 @@
'use client';
import React from 'react';
import type { HexagramPair, Trigram } from '@/lib/xct/types';
import { SIXTY_FOUR_HEXAGRAMS, TRIGRAM_BITS } from '@/lib/xct/constants';
/**
* 卦象图:六爻自下而上排(初爻在下),上卦三爻在上、下卦三爻在下。
*
* 小成图的盘面本来只有八宫天盘,看不到「本卦/变卦」的整体形象;
* 这里把它补在九宫上方——先看象,再看宫,读盘的次序才顺。
* 副标直接取六十四卦名表(如「火风鼎」=离上巽下),不另造简称。
*
* 爻线尺寸走内联 style 而非 Tailwind 任意值:爻是这张图的骨架,
* 不该因为样式表漏扫一个 h-[8px] 就整幅图塌成空白。
*/
interface HexagramFigureProps {
hex: HexagramPair;
/** 本卦 / 变卦 */
label: string;
/** 变卦用淡赭收一下,克制到只是一点点色差 */
accent?: boolean;
}
const YAO_H = 8;
const YAO_GAP = 8;
const FIG_W = 112;
/** 一爻:阳爻整条,阴爻中断 */
function Yao({ yang, ink }: { yang: boolean; ink: string }) {
if (yang) {
return <div style={{ height: YAO_H, width: '100%', background: ink, borderRadius: 1 }} />;
}
return (
<div style={{ display: 'flex', height: YAO_H, width: '100%', gap: '25%' }}>
<div style={{ height: '100%', flex: 1, background: ink, borderRadius: 1 }} />
<div style={{ height: '100%', flex: 1, background: ink, borderRadius: 1 }} />
</div>
);
}
export default function HexagramFigure({ hex, label, accent }: HexagramFigureProps) {
const name = SIXTY_FOUR_HEXAGRAMS[hex.upper]?.[hex.lower] ?? `${hex.upper}之${hex.lower}`;
// 初爻在下:先排下卦三爻(初、二、三),再排上卦三爻(四、五、上),渲染时整体反转
const bits = [...TRIGRAM_BITS[hex.lower as Trigram], ...TRIGRAM_BITS[hex.upper as Trigram]];
const ink = accent ? '#5A3B31' : '#22201B';
return (
<div className="flex flex-col items-center" style={{ gap: 9 }}>
<span
className="font-serif"
style={{
fontSize: 11,
letterSpacing: '0.4em',
paddingLeft: '0.4em',
color: accent ? 'rgba(142,58,44,0.85)' : '#5E5A50',
}}
>
{label}
</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: YAO_GAP, width: FIG_W }}>
{bits
.slice()
.reverse()
.map((b, i) => (
<Yao key={i} yang={b === 1} ink={ink} />
))}
</div>
<span
className="font-serif"
style={{
fontSize: 15,
letterSpacing: '0.1em',
paddingLeft: '0.1em',
color: accent ? '#5A3B31' : '#22201B',
fontFamily: '"Kaiti SC", "KaiTi", "STKaiti", "Noto Serif SC", serif',
}}
>
{name}
</span>
</div>
);
}
-103
View File
@@ -1,103 +0,0 @@
'use client';
import React from 'react';
import { PalaceNumber, PalaceJudgment } from '@/lib/xct/types';
import { PALACE_NAMES } from '@/lib/xct/constants';
interface NinePalaceBoardProps {
judgments: Record<PalaceNumber, PalaceJudgment>;
activePalace: PalaceNumber;
onSelectPalace: (p: PalaceNumber) => void;
}
// 洛书九宫标准排布 (3x3)
// 4 9 2
// 3 5 7
// 8 1 6
const GRID_PALACES: PalaceNumber[][] = [
[4, 9, 2],
[3, 5, 7],
[8, 1, 6],
];
/** 吉类 / 凶类断语:借爻形做标记(吉一横、凶两短横),不引入彩虹配色 */
const GOOD_VERDICTS = new Set(['吉', '亨', '利', '贞']);
function VerdictMark({ verdict }: { verdict: string }) {
if (!GOOD_VERDICTS.has(verdict) && !['凶', '害', '悔', '吝'].includes(verdict)) return null;
const good = GOOD_VERDICTS.has(verdict);
return (
<span className="verdict-mark" aria-hidden>
<span />
{!good && <span />}
</span>
);
}
export default function NinePalaceBoard({ judgments, activePalace, onSelectPalace }: NinePalaceBoardProps) {
return (
<div className="w-full select-none overflow-hidden rounded-[3px] border border-[#DED6C6] bg-[#FAF7F0]">
<div className="flex items-baseline justify-between border-b border-[#DED6C6] px-4 py-2.5">
<h2 className="font-serif text-[12.5px] font-semibold tracking-[0.22em] text-[#22201B]">九 宫 分 布</h2>
<span className="text-[11px] text-[#5E5A50]">点击宫位切换</span>
</div>
<div className="grid grid-cols-3 gap-px bg-[#DED6C6]">
{GRID_PALACES.flat().map((p) => {
const j = judgments[p];
const isSelected = activePalace === p;
const statusLine =
p === 5
? '归藏之枢'
: [j.verdict, j.mode ? `${j.mode}式` : null, j.matched !== null ? (j.matched ? '得配' : '失配') : null]
.filter(Boolean)
.join(' · ');
const hexName = p === 5 ? '' : j.hexName || `${j.heaven}之${j.earth}`;
return (
<button
key={p}
type="button"
onClick={() => onSelectPalace(p)}
aria-pressed={isSelected}
className={`relative flex min-h-[96px] cursor-pointer flex-col items-center justify-center gap-1.5 px-2.5 pb-3 pt-4 text-center transition-colors ${
isSelected ? 'bg-[#22201B]' : 'bg-[#F6F2EA] hover:bg-[#F1ECE1]'
}`}
>
<span
className={`absolute left-2.5 top-2 font-serif text-[11px] tracking-[0.06em] ${
isSelected ? 'text-[#FAF7F0]/60' : 'text-[#5E5A50]'
}`}
>
{PALACE_NAMES[p].slice(0, 2)}
</span>
<span className={`font-serif text-[25px] leading-none ${isSelected ? 'text-[#FAF7F0]' : 'text-[#22201B]'}`}>
{j.heaven}
</span>
<span
className={`max-w-full truncate font-serif text-[11px] ${
isSelected ? 'text-[#FAF7F0]/70' : 'text-[#5E5A50]'
}`}
>
{hexName || '\u00A0'}
</span>
<span
className={`flex items-center gap-1.5 font-serif text-[11px] ${
isSelected ? 'text-[#FAF7F0]/85' : 'text-[#5E5A50]'
}`}
>
{p !== 5 && <VerdictMark verdict={j.verdict} />}
<span className="truncate">{statusLine}</span>
</span>
</button>
);
})}
</div>
</div>
);
}
-117
View File
@@ -1,117 +0,0 @@
'use client';
import React, { useState } from 'react';
import { PalaceJudgment, PalaceNumber, BoardState, ZhengTuiChain } from '@/lib/xct/types';
import { PALACE_NAMES } from '@/lib/xct/constants';
interface ReportViewProps {
board: BoardState;
selectedJudgment: PalaceJudgment;
chain: ZhengTuiChain;
divineTimeInfo?: {
solarDateStr: string;
lunarDateStr: string;
ganzhiStr: string;
} | null;
}
/**
* 盘面详录:宫位释义 + 可复制的盘面提要(纯事实,不含用神与结论)。
*/
export default function ReportView({ board, selectedJudgment, chain, divineTimeInfo }: ReportViewProps) {
const [activeTab, setActiveTab] = useState<'xct' | 'prompt'>('xct');
const [copied, setCopied] = useState(false);
const generatePrompt = () => {
let prompt = '【小成图盘面事实层】';
if (divineTimeInfo) {
prompt += `\n起卦天时:公历 ${divineTimeInfo.solarDateStr} · 干支 ${divineTimeInfo.ganzhiStr} · ${divineTimeInfo.lunarDateStr}`;
}
prompt += `\n本卦:${board.ben.upper}上${board.ben.lower}下 变卦:${board.zhi.upper}上${board.zhi.lower}下`;
prompt += `\n\n一、当前宫位(基础事实):
• 宫位:${selectedJudgment.palaceName},天盘【${selectedJudgment.heaven}】,地盘【${selectedJudgment.earth}】
• 合成重卦:${selectedJudgment.hexName || `${selectedJudgment.heaven}之${selectedJudgment.earth}`},成「${selectedJudgment.mode || '中立'}」式,阴阳${selectedJudgment.matched === null ? '—' : selectedJudgment.matched ? '得配' : '失配'}
• 八断决断:断为「${selectedJudgment.verdict}」
• 中五极枢:天地归藏得「${board.heaven[5]}」
二、气路正推流转(因果事实):
• 演化路径:${chain.path.map((p) => PALACE_NAMES[p]).join(' ➔ ')}
• 因果链条:${chain.summary}`;
prompt += '\n\n━━━━━━━━━━━━━━━━━━━━\n以上为盘面事实摘要(不含用神与吉凶判断),可直接粘到任意大模型继续推演。';
return prompt;
};
const handleCopyPrompt = () => {
navigator.clipboard.writeText(generatePrompt());
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="space-y-3">
<div className="flex items-center gap-5 border-b border-[#DED6C6]">
{(
[
['xct', '宫位释义'],
['prompt', '盘面提要'],
] as const
).map(([key, label]) => (
<button
key={key}
type="button"
onClick={() => setActiveTab(key)}
className={`cursor-pointer border-b pb-2 font-serif text-[11.5px] tracking-[0.12em] transition-colors ${
activeTab === key
? 'border-[#22201B] text-[#22201B]'
: 'border-transparent text-[#5E5A50] hover:text-[#22201B]'
}`}
>
{label}
</button>
))}
</div>
{activeTab === 'xct' && (
<div className="space-y-2.5 font-serif text-[12.5px] leading-relaxed text-[#22201B]">
<p>{selectedJudgment.meaning}</p>
<div className="space-y-1 border-t border-[#DED6C6] pt-2 text-[11.5px] text-[#5E5A50]">
<p>
<strong className="font-semibold text-[#22201B]">中宫枢纽:</strong>
中五宫得「{board.heaven[5]}」,为天地全盘归藏之宗,统摄八方事态基调。
</p>
<p>
<strong className="font-semibold text-[#22201B]">正推终止:</strong>
{chain.endReason === 'guiwei'
? '归位,气止得位'
: chain.hasCycle
? '闭环,气路循环'
: chain.endReason === 'center'
? '入中宫,气归本质'
: '链止于末站'}
。
</p>
</div>
</div>
)}
{activeTab === 'prompt' && (
<div className="space-y-2.5">
<div className="flex items-center justify-between gap-3">
<span className="font-serif text-[11.5px] text-[#5E5A50]">九宫事实层与气路正推链(纯事实,不含用神)</span>
<button
type="button"
onClick={handleCopyPrompt}
className="shrink-0 cursor-pointer rounded-[2px] border border-[#CBBFA8] px-2.5 py-1 font-serif text-[11.5px] text-[#5E5A50] transition-colors hover:border-[#8A8378] hover:text-[#22201B]"
>
{copied ? '已复制' : '复制提要'}
</button>
</div>
<pre className="max-h-[300px] overflow-y-auto whitespace-pre-wrap rounded-[2px] border border-[#DED6C6] bg-[#F6F2EA] p-3 font-mono text-[11px] leading-relaxed text-[#22201B]">
{generatePrompt()}
</pre>
</div>
)}
</div>
);
}
-64
View File
@@ -1,64 +0,0 @@
'use client';
import React from 'react';
import type { PalaceJudgment } from '@/lib/xct/types';
interface VerdictCardProps {
judgment: PalaceJudgment;
/** 正推气路,如「乾六 → 兑七 → 乾六」;无链时传空 */
chainPath?: string;
/** 链末状态:闭环 / 归位 / 归藏 / 无 */
chainEnd?: string;
}
/**
* 结论卡:当前宫位 + 四象八断。
*
* 原版这里右侧还有一个「解盘」按钮(调大模型写卦断)。裁剪版只保留确定性断语,
* 断语本身来自 judgeEngine 的四象(阖辟往来)× 阴阳得配失配查表,不是大模型生成。
*/
export default function VerdictCard({ judgment, chainPath, chainEnd }: VerdictCardProps) {
const subLine =
judgment.mode || judgment.matched !== null
? [
judgment.mode ? `${judgment.mode}式` : null,
judgment.matched !== null ? (judgment.matched ? '得配' : '失配') : null,
]
.filter(Boolean)
.join(' · ')
: '';
return (
<div className="mt-4 rounded-[3px] border border-[#CBBFA8] bg-[#F8F3E9] px-5 py-3.5">
<div className="flex items-baseline gap-2.5 text-[11px] tracking-[0.04em] text-[#5E5A50]">
<span>当前宫位</span>
<b className="font-serif text-[12.5px] font-semibold tracking-[0.1em] text-[#22201B]">
{judgment.palaceName.slice(0, 2)}
</b>
<span>
天盘{judgment.heaven}
{judgment.earth ? ` · ${judgment.hexName || `${judgment.heaven}之${judgment.earth}`}` : ''}
</span>
</div>
<div className="mt-1.5 flex items-center gap-2 sm:gap-2.5">
<span className="shrink-0 whitespace-nowrap pb-1 font-serif text-[12px] tracking-[0.14em] text-[#5E5A50]">
断为
</span>
<span className="whitespace-nowrap font-serif text-[32px] leading-none tracking-[0.02em] text-[#22201B] sm:text-[40px]">
「{judgment.verdict}」
</span>
</div>
<div className="mt-2.5 flex items-baseline justify-between gap-3 border-t border-[#DED6C6] pt-2.5 text-[11px] tracking-[0.03em] text-[#5E5A50]">
<span>{subLine || ' '}</span>
{chainPath && (
<span>
正推气路 <span className="text-[#22201B]">{chainPath}</span>
{chainEnd ? ` ${chainEnd}` : ''}
</span>
)}
</div>
</div>
);
}
-698
View File
@@ -1,698 +0,0 @@
'use client';
/**
* 小成图排盘(裁剪版)
* ======================
* 从 bazi-web `components/xct/XiaoChengTuView.tsx` 提取,保留:
* 三种起卦(天地数 / 梅花时间 / 自定选卦)→ 八宫天盘 → 九宫四象八断 → 正推气路 → 盘面详录。
* 移除:
* 问句输入、类象用神选择、LLM 意图识别、专事公理、LLM 解盘(XctReadingPanel)、
* 以及一切把「问什么」翻译成「用神在哪一宫」的链路。
*
* 正推起点因此改为**读者点选的宫位**(默认中宫立极),不再由用神决定。
*/
import React, { useEffect, useMemo, useRef, useState } from 'react';
import Link from 'next/link';
import { RotateCcw, Star } from 'lucide-react';
import { Lunar } from 'lunar-javascript';
import NinePalaceBoard from './NinePalaceBoard';
import HexagramFigure from './HexagramFigure';
import ZhengTuiPathView from './ZhengTuiPathView';
import ReportView from './ReportView';
import VerdictCard from './VerdictCard';
import FoldSection from './FoldSection';
import type { BoardState, PalaceJudgment, PalaceNumber, Trigram, ZhengTuiChain } from '@/lib/xct/types';
import {
buildBoardFromManualTrigrams,
buildBoardFromMeihuaTime,
buildBoardFromTianDiNumbers,
getDivinationTimeInfo,
} from '@/lib/xct/boardBuilder';
import { judgeFullBoard } from '@/lib/xct/judgeEngine';
import { traceZhengTuiChain } from '@/lib/xct/dagTracker';
import { ALL_TRIGRAMS, PALACE_NAMES, SIXTY_FOUR_HEXAGRAMS, XIAN_TIAN_NUMBER } from '@/lib/xct/constants';
import { getCaseStore } from '@/lib/store';
import { buildXctRecord } from '@/lib/cases/record';
type CastMode = 'four' | 'time' | 'self';
const MODES: { id: CastMode; label: string }[] = [
{ id: 'four', label: '天地数起卦' },
{ id: 'time', label: '时间起卦' },
{ id: 'self', label: '自定选卦' },
];
function pad(n: number) {
return String(n).padStart(2, '0');
}
function nowLocalInput(): string {
const d = new Date();
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
export default function XiaoChengTuView() {
const [method, setMethod] = useState<CastMode>('four');
// 天地数起卦
const [tianDiNums, setTianDiNums] = useState<[string, string, string, string]>(['', '', '', '']);
const tianDiRefs = useRef<(HTMLInputElement | null)[]>([]);
const [isRolling, setIsRolling] = useState(false);
const rollingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
// 时间起卦
const [selectedTime, setSelectedTime] = useState<string>(() => nowLocalInput());
// 自定选卦
const [manualBenUpper, setManualBenUpper] = useState<Trigram>('乾');
const [manualBenLower, setManualBenLower] = useState<Trigram>('兑');
const [manualZhiUpper, setManualZhiUpper] = useState<Trigram>('离');
const [manualZhiLower, setManualZhiLower] = useState<Trigram>('坤');
const [board, setBoard] = useState<BoardState | null>(null);
const [judgments, setJudgments] = useState<Record<PalaceNumber, PalaceJudgment> | null>(null);
const [chain, setChain] = useState<ZhengTuiChain | null>(null);
const [activePalace, setActivePalace] = useState<PalaceNumber>(5);
const [movingYao, setMovingYao] = useState<number | null>(null);
const [timeDisplay, setTimeDisplay] = useState<ReturnType<typeof getDivinationTimeInfo> | null>(null);
const [notice, setNotice] = useState('');
const [castSnapshot, setCastSnapshot] = useState<{
method: CastMode;
tianDiNums?: [string, string, string, string];
timeDate?: string;
manual?: { benUpper: Trigram; benLower: Trigram; zhiUpper: Trigram; zhiLower: Trigram };
timeInput: string;
} | null>(null);
const [savedId, setSavedId] = useState<string | null>(null);
const resultRef = useRef<HTMLDivElement | null>(null);
const restoredRef = useRef(false);
useEffect(() => {
return () => {
if (rollingIntervalRef.current) clearInterval(rollingIntervalRef.current);
};
}, []);
const timePreview = useMemo(() => {
try {
const d = selectedTime ? new Date(selectedTime) : new Date();
const validDate = isNaN(d.getTime()) ? new Date() : d;
const lunar = Lunar.fromDate(validDate) as any;
const YEAR_ZHI = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
const yearZhi = lunar.getYearZhiExact();
const yearZhiNum = YEAR_ZHI.indexOf(yearZhi) + 1;
const lunarMonth = Math.abs(lunar.getMonth());
const lunarDay = lunar.getDay();
const hourZhi = lunar.getTimeZhi();
const hourZhiNum = YEAR_ZHI.indexOf(hourZhi) + 1;
const upperSum = yearZhiNum + lunarMonth + lunarDay;
const upperRem = upperSum % 8 === 0 ? 8 : upperSum % 8;
const lowerSum = upperSum + hourZhiNum;
const lowerRem = lowerSum % 8 === 0 ? 8 : lowerSum % 8;
const moving = lowerSum % 6 === 0 ? 6 : lowerSum % 6;
return {
solarDateStr: `${validDate.getFullYear()}年${validDate.getMonth() + 1}月${validDate.getDate()}日 ${pad(validDate.getHours())}:${pad(validDate.getMinutes())}`,
ganzhiStr: `${lunar.getYearInGanZhiExact()}年 ${lunar.getMonthInGanZhiExact()}月 ${lunar.getDayInGanZhiExact()}日 ${lunar.getTimeInGanZhi()}时`,
lunarStr: `${lunar.getYearInChinese()}年 农历${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}`,
yearZhi,
yearZhiNum,
lunarMonth,
lunarDay,
hourZhi,
hourZhiNum,
upperRem,
lowerRem,
movingYao: moving,
};
} catch {
return null;
}
}, [selectedTime]);
// 天地数输入
const handleTianDiKeyDown = (idx: number, e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Backspace') {
e.preventDefault();
const next = [...tianDiNums] as [string, string, string, string];
if (next[idx]) next[idx] = '';
else if (idx > 0) {
next[idx - 1] = '';
tianDiRefs.current[idx - 1]?.focus();
}
setTianDiNums(next);
return;
}
if (e.key === 'ArrowLeft' && idx > 0) {
e.preventDefault();
tianDiRefs.current[idx - 1]?.focus();
return;
}
if (e.key === 'ArrowRight' && idx < 3) {
e.preventDefault();
tianDiRefs.current[idx + 1]?.focus();
return;
}
if (/^[0-9]$/.test(e.key)) {
e.preventDefault();
const next = [...tianDiNums] as [string, string, string, string];
next[idx] = e.key;
setTianDiNums(next);
if (idx < 3) tianDiRefs.current[idx + 1]?.focus();
}
};
const handleTianDiPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
e.preventDefault();
const text = e.clipboardData.getData('text').trim();
let tokens: string[] = [];
if (/[\s,,、/|-]/.test(text)) tokens = text.split(/[\s,,、/|-]+/).filter(Boolean);
else {
for (let i = 0; i < text.length && tokens.length < 4; i += 1) {
if (/^[0-9]$/.test(text[i])) tokens.push(text[i]);
}
}
if (!tokens.length) return;
const next = [...tianDiNums] as [string, string, string, string];
for (let i = 0; i < Math.min(4, tokens.length); i += 1) {
const num = Number(tokens[i]);
if (!Number.isNaN(num) && num >= 0 && num <= 9) next[i] = String(num);
}
setTianDiNums(next);
tianDiRefs.current[Math.min(3, tokens.length)]?.focus();
};
const handleStartRolling = () => {
setIsRolling(true);
if (rollingIntervalRef.current) clearInterval(rollingIntervalRef.current);
rollingIntervalRef.current = setInterval(() => {
setTianDiNums([
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
]);
}, 50);
};
const handleStopRolling = () => {
if (rollingIntervalRef.current) clearInterval(rollingIntervalRef.current);
rollingIntervalRef.current = null;
setTianDiNums([
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
String(Math.floor(Math.random() * 10)),
]);
setIsRolling(false);
};
const selectPalace = (p: PalaceNumber) => {
if (!board) return;
setActivePalace(p);
setChain(traceZhengTuiChain(board, p));
};
interface CastOverride {
method?: CastMode;
tianDiNums?: [string, string, string, string];
timeDate?: string;
manual?: { benUpper: Trigram; benLower: Trigram; zhiUpper: Trigram; zhiLower: Trigram };
}
/** 起盘;从卦例夹复原时用 override 直接给值(setState 是异步的,不能读完再算) */
const runCast = (override?: CastOverride) => {
setNotice('');
try {
const curMethod = override?.method ?? method;
const curNums = override?.tianDiNums ?? tianDiNums;
const curTime = override?.timeDate ?? selectedTime;
const curManual =
override?.manual ?? {
benUpper: manualBenUpper,
benLower: manualBenLower,
zhiUpper: manualZhiUpper,
zhiLower: manualZhiLower,
};
const castTimeInput = curMethod === 'time' ? curTime || nowLocalInput() : nowLocalInput();
let nextBoard: BoardState;
let nextMoving: number | null = null;
if (curMethod === 'four') {
if (curNums.some((v) => v === '' || !/^[0-9]$/.test(v))) {
setNotice('请先报入天地四数(各 0–9),或点击「一键随机报数」');
return;
}
nextBoard = buildBoardFromTianDiNumbers(curNums.map((v) => Number(v)) as [number, number, number, number]);
} else if (curMethod === 'time') {
const res = buildBoardFromMeihuaTime(castTimeInput);
nextBoard = res.board;
nextMoving = res.movingYao;
} else {
nextBoard = buildBoardFromManualTrigrams(
curManual.benUpper,
curManual.benLower,
curManual.zhiUpper,
curManual.zhiLower,
);
}
const nextJudgments = judgeFullBoard(nextBoard);
const startPalace: PalaceNumber = 5;
setBoard(nextBoard);
setJudgments(nextJudgments);
setMovingYao(nextMoving);
setActivePalace(startPalace);
setChain(traceZhengTuiChain(nextBoard, startPalace));
setTimeDisplay(getDivinationTimeInfo(castTimeInput));
setCastSnapshot({
method: curMethod,
...(curMethod === 'four' ? { tianDiNums: curNums } : {}),
...(curMethod === 'time' ? { timeDate: castTimeInput } : {}),
...(curMethod === 'self' ? { manual: curManual } : {}),
timeInput: castTimeInput,
});
setSavedId(null);
requestAnimationFrame(() => resultRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
} catch (e) {
setNotice(e instanceof Error ? e.message : String(e));
}
};
// 从卦例夹打开:?case=<id>
useEffect(() => {
if (restoredRef.current) return;
restoredRef.current = true;
const id = new URLSearchParams(window.location.search).get('case');
if (!id) return;
void (async () => {
const record = await getCaseStore().get(id);
if (!record || record.kind !== 'xct' || record.input.kind !== 'xct') {
setNotice('卦例不存在或类型不符');
return;
}
const inp = record.input;
if (inp.timeDate) setSelectedTime(inp.timeDate);
if (inp.tianDiNums) setTianDiNums(inp.tianDiNums);
if (inp.manual) {
setManualBenUpper(inp.manual.benUpper as Trigram);
setManualBenLower(inp.manual.benLower as Trigram);
setManualZhiUpper(inp.manual.zhiUpper as Trigram);
setManualZhiLower(inp.manual.zhiLower as Trigram);
}
setMethod(inp.method);
runCast({
method: inp.method,
tianDiNums: inp.tianDiNums,
timeDate: inp.timeDate,
manual: inp.manual
? {
benUpper: inp.manual.benUpper as Trigram,
benLower: inp.manual.benLower as Trigram,
zhiUpper: inp.manual.zhiUpper as Trigram,
zhiLower: inp.manual.zhiLower as Trigram,
}
: undefined,
});
})();
// runCast 每次渲染都是新函数,靠 restoredRef 保证只跑一次
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const handleSave = async () => {
if (!board || !castSnapshot) return;
try {
const record = buildXctRecord({
benName: SIXTY_FOUR_HEXAGRAMS[board.ben.upper][board.ben.lower],
zhiName: SIXTY_FOUR_HEXAGRAMS[board.zhi.upper][board.zhi.lower],
center: board.center,
timeInput: castSnapshot.timeInput,
method: castSnapshot.method,
tianDiNums: castSnapshot.tianDiNums,
timeDate: castSnapshot.timeDate,
manual: castSnapshot.manual,
});
await getCaseStore().save(record);
setSavedId(record.id);
} catch (e) {
setNotice(e instanceof Error ? e.message : String(e));
}
};
const handleReset = () => {
setBoard(null);
setJudgments(null);
setChain(null);
setNotice('');
setTianDiNums(['', '', '', '']);
setIsRolling(false);
setCastSnapshot(null);
setSavedId(null);
window.scrollTo({ top: 0, behavior: 'smooth' });
};
// ───────────────────────── 结果页 ─────────────────────────
if (board && judgments) {
const chainPath = chain ? chain.path.map((p) => PALACE_NAMES[p].slice(0, 2)).join(' → ') : '';
const chainEnd = chain
? chain.endReason === 'guiwei'
? '归位'
: chain.hasCycle
? '闭环'
: chain.endReason === 'center'
? '归藏'
: ''
: '';
return (
<div ref={resultRef} className="mx-auto w-full max-w-[760px] px-3 pb-24 pt-5 sm:px-5 sm:pt-7">
<div className="flex items-center justify-between gap-3 pb-3.5">
<div className="flex items-center gap-2">
<span className="inline-block h-[5px] w-[5px] rounded-full bg-[#8E3A2C]" />
<span className="font-serif text-[13px] font-semibold tracking-[0.18em] text-[#22201B]">小成图 · 排盘</span>
</div>
<div className="flex items-center gap-2">
<Link
href="/cases"
className="hidden font-serif text-[11px] text-[#5e5a50] underline-offset-4 hover:text-[#8e3a2c] hover:underline sm:inline"
>
卦例夹
</Link>
<button
type="button"
onClick={() => void handleSave()}
disabled={Boolean(savedId)}
title={savedId ? '已保存到卦例夹' : '保存起卦输入,随时重排'}
className={`flex cursor-pointer items-center gap-1.5 rounded-[2px] border px-2.5 py-1.5 font-serif text-[11.5px] transition-colors ${
savedId
? 'cursor-default border-[#DED6C6] text-[#8c8272]'
: 'border-[#CBBFA8] text-[#5E5A50] hover:border-[#8A8378] hover:text-[#22201B]'
}`}
>
<Star size={12} fill={savedId ? 'currentColor' : 'none'} />
<span>{savedId ? '已保存' : '保存卦例'}</span>
</button>
<Link
href="/"
className="font-serif text-[11px] text-[#5e5a50] underline-offset-4 hover:text-[#8e3a2c] hover:underline"
>
首页
</Link>
<button
type="button"
onClick={handleReset}
className="flex cursor-pointer items-center gap-1.5 rounded-[2px] border border-[#CBBFA8] px-2.5 py-1.5 font-serif text-[11.5px] text-[#5E5A50] transition-colors hover:border-[#8A8378] hover:text-[#22201B]"
>
<RotateCcw size={12} />
<span>重新起卦</span>
</button>
</div>
</div>
{/* 起卦天时 */}
<div className="border-y border-[#DED6C6] py-3">
{timeDisplay && (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 font-serif text-[11.5px] text-[#5E5A50]">
<span className="tracking-wide text-[#22201B]">{timeDisplay.ganzhiStr}</span>
<span className="text-[#CBBFA8]">|</span>
<span>{timeDisplay.solarDateStr}</span>
<span className="text-[#CBBFA8]">|</span>
<span>{timeDisplay.lunarDateStr}</span>
{movingYao && (
<>
<span className="text-[#CBBFA8]">|</span>
<span>动爻 第 {movingYao} 爻</span>
</>
)}
</div>
)}
</div>
{/* 卦象 */}
<div className="flex select-none items-start justify-center gap-7 pb-1 pt-5 sm:gap-10">
<HexagramFigure hex={board.ben} label="本卦" />
<div className="flex flex-col items-center gap-2 pt-[42px]">
<span className="h-6 w-px bg-[#DED6C6]" />
<span className="font-serif text-[12px] tracking-[0.1em] text-[#5E5A50]">之</span>
<span className="h-6 w-px bg-[#DED6C6]" />
</div>
<HexagramFigure hex={board.zhi} label="变卦" accent />
</div>
{/* 结论(当前宫位四象八断) */}
<VerdictCard judgment={judgments[activePalace]} chainPath={chainPath} chainEnd={chainEnd} />
{/* 九宫 */}
<div className="mt-4">
<NinePalaceBoard judgments={judgments} activePalace={activePalace} onSelectPalace={selectPalace} />
</div>
<p className="mt-2 font-serif text-[11px] text-[#8c8272]">
点击任一宫位,即以该宫为起点重算正推气路(无问句、无自动取用)。
</p>
{/* 折叠:正推与详录 */}
{chain && (
<div className="mt-5">
<FoldSection title="正推演化" summary={chainPath}>
<ZhengTuiPathView chain={chain} board={board} activePalace={activePalace} onSelectPalace={selectPalace} />
</FoldSection>
<FoldSection title="盘面详录" summary={`八宫判毕 · 中五归藏${board.heaven[5] || ''}`}>
<ReportView
board={board}
selectedJudgment={judgments[activePalace]}
chain={chain}
divineTimeInfo={timeDisplay}
/>
</FoldSection>
</div>
)}
</div>
);
}
// ───────────────────────── 起卦表单 ─────────────────────────
return (
<div className="mx-auto w-full max-w-[600px] px-4 pb-24 pt-8 sm:pt-12">
<header className="space-y-1.5 pb-1 text-center">
<div className="flex items-center justify-center gap-3">
<h1 className="font-serif text-[26px] font-bold leading-tight tracking-[0.2em] text-[#1E2520] sm:text-[30px]">
小成图
</h1>
<Link
href="/cases"
className="font-serif text-[11px] text-[#5e5a50] underline-offset-4 hover:text-[#8e3a2c] hover:underline"
>
卦例夹
</Link>
<Link
href="/"
className="font-serif text-[11px] text-[#5e5a50] underline-offset-4 hover:text-[#8e3a2c] hover:underline"
>
首页
</Link>
</div>
<div className="flex items-center justify-center gap-2.5 font-serif text-[11px] tracking-[0.16em] text-[#556453]">
<span className="h-px w-8 bg-[#C8D6C6] sm:w-12" />
<span>阖辟往来 · 四象八断 · 正推因果</span>
<span className="h-px w-8 bg-[#C8D6C6] sm:w-12" />
</div>
</header>
{notice && (
<div className="mt-4 w-full rounded-[3px] border border-[#d9a99f] bg-[#fdf2ef] p-2.5 text-center font-serif text-[11.5px] text-[#8e3a2c]">
{notice}
</div>
)}
<div className="mt-5 w-full space-y-4 rounded-[4px] border border-[#CCD8CB] bg-[#FDFCF7] p-4 shadow-[0_1px_6px_rgba(23,20,15,0.04)] sm:p-5">
{/* 起卦法门 */}
<div className="space-y-2.5">
<div className="flex items-center justify-between">
<span className="font-serif text-[12px] font-bold text-[#1E2520]">起卦方式</span>
<span className="font-serif text-[11px] text-[#7A8A78]">
{method === 'four' ? '随口四数成卦' : method === 'time' ? '梅花时空成卦' : '直选八卦成卦'}
</span>
</div>
<div className="grid grid-cols-3 gap-1.5 rounded-[4px] border border-[#CCD8CB]/80 bg-[#F0EBE1]/70 p-1">
{MODES.map((m) => (
<button
key={m.id}
type="button"
onClick={() => setMethod(m.id)}
className={`h-9 cursor-pointer rounded-[3px] font-serif text-[12px] transition-colors ${
method === m.id
? 'bg-[#3F5B4B] font-semibold text-white shadow-sm'
: 'text-[#4A4237] hover:bg-[#FAF8F1]/80 hover:text-[#1E2520]'
}`}
>
{m.label}
</button>
))}
</div>
</div>
{/* 天地数 */}
{method === 'four' && (
<div className="space-y-3 border-t border-[#EDF2EB] pt-3">
<span className="block font-serif text-[11px] text-[#7A8A78]">随口报四数(0 至 9):</span>
<div className="grid grid-cols-4 gap-2 sm:gap-2.5">
{(['本卦上', '本卦下', '之卦上', '之卦下'] as const).map((label, idx) => (
<div key={label} className="text-center">
<input
ref={(el) => {
tianDiRefs.current[idx] = el;
}}
type="text"
inputMode="numeric"
pattern="[0-9]*"
maxLength={1}
value={tianDiNums[idx]}
onKeyDown={(e) => handleTianDiKeyDown(idx, e)}
onPaste={handleTianDiPaste}
onChange={() => {}}
aria-label={label}
className={`h-12 w-full select-all rounded-[3px] border bg-white py-1.5 text-center font-serif text-lg font-bold text-[#1E2520] outline-none transition-all ${
isRolling
? 'scale-[1.02] border-[#3F5B4B] bg-[#F4F8F3] text-[#3F5B4B]'
: 'border-[#CCD8CB] focus:border-[#3F5B4B]'
}`}
/>
<span className="mt-1 block font-serif text-[10px] text-[#6B7B69] sm:text-[11px]">{label}</span>
</div>
))}
</div>
<div className="flex justify-center pt-1">
{!isRolling ? (
<button
type="button"
onClick={handleStartRolling}
className="cursor-pointer rounded-[4px] border border-[#CCD8CB] bg-[#F7FAF6] px-4 py-1.5 font-serif text-[12px] tracking-wider text-[#2F3E30] shadow-sm transition-all hover:bg-[#EDF2EB] hover:text-[#1E2520] active:scale-95"
>
一键随机报数
</button>
) : (
<div className="flex flex-col items-center justify-center gap-1.5">
<button
type="button"
onClick={handleStopRolling}
className="relative flex h-14 w-14 cursor-pointer items-center justify-center rounded-full border-2 border-[#8E302D]/60 bg-[#FDFBF7] font-serif text-2xl font-bold text-[#8E302D] shadow-md transition-transform hover:scale-105 active:scale-95 sm:h-16 sm:w-16"
title="点击定格四数"
>
<span>停</span>
</button>
<span className="font-serif text-[11px] tracking-wider text-[#8E302D]/70">数字翻滚中 · 点击「停」定格</span>
</div>
)}
</div>
</div>
)}
{/* 时间起卦 */}
{method === 'time' && (
<div className="space-y-3 border-t border-[#EDF2EB] pt-3">
<div className="flex items-center justify-between">
<span className="font-serif text-[11px] text-[#7A8A78]">以天时通神,依农历年月日时推衍成卦:</span>
<button
type="button"
onClick={() => setSelectedTime(nowLocalInput())}
className="cursor-pointer font-serif text-[11px] text-[#3F5B4B] underline hover:text-[#1E2520]"
>
取当前系统时刻
</button>
</div>
<input
type="datetime-local"
value={selectedTime}
onChange={(e) => setSelectedTime(e.target.value)}
aria-label="起卦时间"
className="h-11 w-full rounded-[3px] border border-[#CCD8CB] bg-white px-3 font-serif text-[13px] text-[#1E2520] outline-none focus:border-[#3F5B4B]"
/>
{timePreview && (
<div className="space-y-2 rounded-[3px] border border-[#CCD8CB] bg-[#FAFBF9] p-3 font-serif text-[11.5px]">
<div className="flex flex-wrap items-center justify-between gap-1 border-b border-[#E8EFE4] pb-1.5">
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[#7A8A78]">
公历:<span className="font-sans font-medium text-[#1E2520]">{timePreview.solarDateStr}</span>
</span>
<span className="hidden text-[#CCD8CB] sm:inline">|</span>
<span className="font-bold text-[#1E2520]">干支:{timePreview.ganzhiStr}</span>
</div>
<span className="text-[10.5px] text-[#6B7B69]">{timePreview.lunarStr}</span>
</div>
<div className="grid grid-cols-3 gap-2 pt-0.5 text-center">
<div className="rounded border border-[#E8EFE4] bg-white p-1.5">
<span className="block text-[10px] text-[#7A8A78]">上卦(年+月+日)</span>
<span className="mt-0.5 block text-[13px] font-bold text-[#3F5B4B]">
余 {timePreview.upperRem} · {XIAN_TIAN_NUMBER[timePreview.upperRem]}卦
</span>
</div>
<div className="rounded border border-[#E8EFE4] bg-white p-1.5">
<span className="block text-[10px] text-[#7A8A78]">下卦(加时辰支)</span>
<span className="mt-0.5 block text-[13px] font-bold text-[#3F5B4B]">
余 {timePreview.lowerRem} · {XIAN_TIAN_NUMBER[timePreview.lowerRem]}卦
</span>
</div>
<div className="rounded border border-[#E8EFE4] bg-white p-1.5">
<span className="block text-[10px] text-[#7A8A78]">动爻(总和÷6)</span>
<span className="mt-0.5 block text-[13px] font-bold text-[#9c7a3c]">
第 {timePreview.movingYao} 爻变
</span>
</div>
</div>
</div>
)}
</div>
)}
{/* 自定选卦 */}
{method === 'self' && (
<div className="space-y-2 border-t border-[#EDF2EB] pt-3">
<span className="block font-serif text-[11px] text-[#7A8A78]">直选本卦之卦上下卦:</span>
<div className="grid grid-cols-2 gap-1.5 font-serif text-[11px] sm:grid-cols-4">
{(
[
['本卦上卦', manualBenUpper, setManualBenUpper, 'ben-upper'],
['本卦下卦', manualBenLower, setManualBenLower, 'ben-lower'],
['之卦上卦', manualZhiUpper, setManualZhiUpper, 'zhi-upper'],
['之卦下卦', manualZhiLower, setManualZhiLower, 'zhi-lower'],
] as const
).map(([label, value, setter, id]) => (
<div key={id}>
<label htmlFor={id} className="mb-0.5 block text-[#7A8A78]">
{label}
</label>
<select
id={id}
value={value}
onChange={(e) => (setter as (t: Trigram) => void)(e.target.value as Trigram)}
className="w-full rounded border border-[#CCD8CB] bg-white p-1.5 text-[12px]"
>
{ALL_TRIGRAMS.map((g) => (
<option key={g} value={g}>
{g}
</option>
))}
</select>
</div>
))}
</div>
</div>
)}
<div className="flex justify-center border-t border-[#EDF2EB] pt-3">
<button
type="button"
disabled={isRolling}
onClick={() => runCast()}
className="flex h-11 w-full max-w-[220px] select-none cursor-pointer items-center justify-center bg-[#334a5d] px-6 font-serif text-[14px] tracking-[0.2em] text-[#fbf7ec] shadow-sm transition-all hover:bg-[#283a49] active:scale-[0.99] disabled:cursor-not-allowed disabled:bg-stone-300 disabled:text-stone-500"
>
{isRolling ? '数字翻滚中…' : '排 盘 →'}
</button>
</div>
</div>
</div>
);
}
-94
View File
@@ -1,94 +0,0 @@
'use client';
import React from 'react';
import { ZhengTuiChain, BoardState, PalaceNumber } from '@/lib/xct/types';
interface ZhengTuiPathViewProps {
chain: ZhengTuiChain;
board?: BoardState;
activePalace: PalaceNumber;
onSelectPalace: (p: PalaceNumber) => void;
}
/**
* 正推气路(数往者顺)。
*
* 早先每一站是一个填色胶囊:用神站琥珀、闭环站紫、归位站青绿,选中站墨底,
* 而判语又写死了深褐 `text-[#5A5346]` 不跟随底色——选中时对比度只剩 1.3:1,
* 等于把「吉」字抹掉了。现在站号改圆圈(中性形制),判语继承文字色,
* 用「用 / 闭 / 归」三个字区分首末站,不再用色块。
*/
export default function ZhengTuiPathView({
chain,
activePalace,
onSelectPalace,
}: ZhengTuiPathViewProps) {
if (!chain || !chain.nodes || chain.nodes.length === 0) {
return null;
}
const endText =
chain.endReason === 'guiwei'
? '归位 · 气止得位'
: chain.hasCycle
? '气路闭环循环'
: chain.endReason === 'center'
? '气机归藏入中'
: '链止于末站';
return (
<div className="space-y-3">
<div className="flex flex-wrap items-center gap-x-2 gap-y-3">
{chain.nodes.map((node, index) => {
const isSelected = activePalace === node.palace;
const isFirst = index === 0;
const isLast = index === chain.nodes.length - 1;
const badge = isFirst
? '用'
: isLast && chain.endReason === 'guiwei'
? '归'
: isLast && chain.hasCycle
? '闭'
: String(index + 1);
return (
<React.Fragment key={`${node.palace}-${index}`}>
<button
type="button"
onClick={() => onSelectPalace(node.palace)}
aria-pressed={isSelected}
className="flex cursor-pointer items-center gap-2 text-left"
>
<span
className={`flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full border font-serif text-[11px] transition-colors ${
isSelected
? 'border-[#22201B] bg-[#22201B] text-[#FAF7F0]'
: 'border-[#CBBFA8] text-[#5E5A50]'
}`}
>
{badge}
</span>
<span className="flex flex-col leading-tight">
<span className="font-serif text-[12px] text-[#22201B]">{node.palaceName.slice(0, 2)}</span>
<span className="font-serif text-[11px] text-[#5E5A50]">
{node.judgment.hexName || node.heaven} · {node.judgment.verdict}
</span>
</span>
</button>
{index < chain.nodes.length - 1 && (
<span className="text-[11px] text-[#CBBFA8]">→</span>
)}
</React.Fragment>
);
})}
</div>
<p className="text-[11px] leading-relaxed text-[#5E5A50]">
{endText}
{chain.summary ? ` ${chain.summary}` : ''}
</p>
</div>
);
}
+63 -76
View File
@@ -1,92 +1,79 @@
# Cloudflare 目标与约束(暂不部署)
# Cloudflare 部署备忘
当前阶段:**先把产品做对,不部署**。但所有新代码都按 Cloudflare Workers 的能力写,
避免上线前才发现「这段在 Workers 上跑不了」。
目标:Cloudflare Workers(vinext / workerd)。**部署步骤见根目录 `README.md`**;本文只记取舍与约束。
验证命令:
## 运行形态
```bash
npm run check:portability # 运行时代码是否有 fs/node 内置、next/image、next/font、锁死静态导出
| 部分 | 位置 | 说明 |
| --- | --- | --- |
| `/`、`/liuyao`、`/cases`、`/classics` | 静态预渲染 | 排盘引擎全在客户端,纯函数 |
| `/api/read` | Worker | 解卦 SSE 代理(prompt 服务端拼装) |
| `/api/llm-test` | Worker | 大模型连通性测试(一次性转发) |
| `/api/cases` | Worker | 卦例读写(D1,按匿名设备 Cookie 隔离) |
## 状态
- **D1**:只有 `cases` 一张表(`migrations/0001_init.sql`)。
`npm run gen:schema` 生成运行时建表常量,`npm run check:schema` 校验一致性。
- **后台已下线**:没有 `/admin`、没有 `settings` / `llm_profiles` / `admin_audit`。
大模型配置改由用户自带,只存在用户浏览器的 `localStorage['liuyao.llm.v1']`,
每次解卦随请求体发到 `/api/read`,服务端只做一次转发,不落库、不写日志。
- 旧库如果还留着那三张表,不影响运行(代码不再读写);想清干净可在 D1 控制台 DROP。
## 大模型链路
```
浏览器(localStorage 里的 baseUrl/model/key)
└─ POST /api/read { facts, llm } ← 服务端校验:协议、模型名、拦内网地址
└─ POST {baseUrl}/chat/completions ← 原样转发,key 只在内存里活一次
└─ SSE 回传 → 四段正文
```
## 一、现在的形态
- 任何「OpenAI 兼容」供应商都能用(DeepSeek / OpenAI / Moonshot / 智谱 / 通义 /
OpenRouter / SiliconFlow / Ollama / 自建网关)。
- 自建部署可用服务端 env 兜底:`LLM_API_KEY`(可选 `LLM_BASE_URL`、`LLM_MODEL`、
`LLM_THINKING`、`LLM_REASONING_EFFORT`);请求体里带了 `llm` 就以请求体为准。
- 限流是模块级内存表,只在单实例内生效;真要上线建议换 Cloudflare Rate Limiting 或 D1 计数。
| 路由 | 形态 | 说明 |
|---|---|---|
| `/`、`/liuyao`、`/xct`、`/cases` | 静态预渲染 | 引擎全在客户端,纯函数 |
| `/api/read` | 动态(服务端) | 解卦流式代理;只收盘面事实,key 只在服务端 |
## 可移植性红线
- 运行时没有 `fs` / `node:*`;唯一例外 `lib/dev/dev-origins.ts` 只被 `next.config.ts`(构建期)引用。
- 字体是本地 CSS,没有 `next/font`;图片是普通 `<img>`,没有 `next/image`。
- 不把 `next.config.ts` 设成 `output: 'export'`:那会把 route handler 的门焊死。
`npm run check:portability` 会扫运行时代码,禁止:
## 二、已定的产品方向(2026-11)
- `node:*` / `fs` / `path` 等 Node 内置模块(Worker 里没有);
- `next/image`、`next/font`、`output: 'export'`;
- 任何在起卦路径上用 `Math.random` 的地方(见 `tests/random.test.ts`)。
1. **A**:排盘/盘面持续优化,纯前端。
2. **B**:存卦例/历史/收藏。存储通过 `lib/store` 的异步接口访问,本地实现是 localStorage,
将来换 D1 只改实现。记录只存「起卦输入」,盘面由引擎重算。
3. **C**:解卦。客户端只发 `lib/readings/types.ts` 里的事实对象;prompt 在服务端
(`app/api/read/prompt.ts`)拼;key 只在服务端环境变量/secret。
4. **后台**:公告、LLM 切换、流量统计配置(进行中,见下)。
## 命令
## 三、后台(规划中)的 Cloudflare 形态
```bash
npm run check # schema + portability + 测试
npm run dev:vinext # workerd + 本地 D1(http://localhost:3001)
npm run build && npm run build:vinext
```
- **存储**:D1(`admin_settings` / `llm_profiles` / `admin_audit`)。
- 公告 = 一行 JSON;LLM = profile 行(`base_url` / `model` / **`key_env`**,密钥本身永远不进库)。
- 本地开发先走文件/内存实现(`AdminStore` 接口),D1 适配器在 vinext/wrangler 本地环境跑通后接入。
- **鉴权**:先单管理员口令(HttpOnly + HMAC 签名 Cookie,WebCrypto 实现,Workers 可用);
绑定自有域名后切 Cloudflare Access(Zero Trust),把 `/admin*` 与 `/api/admin/*` 交给边缘保护。
- **公告下发**:`GET /api/announcement`(D1 读 + 短缓存),布局里客户端组件渲染;
接口不可用时静默不显示,不影响排盘。
- **统计**:优先「结构化配置」而不是任意 JS —— Cloudflare Web Analytics token / 第三方 siteId;
若要支持自定义 snippet,必须单独开关并标注 XSS 风险。
- **密钥**:`wrangler secret put LLM_API_KEY`(或 `DEEPSEEK_API_KEY` 等)。
后台只切 profile,不显示、不落库密钥。
## 部署(自有域名,不上架应用商店)
## 四、部署触发条件(满足任意一条再动)
```bash
npx cf auth login # 设备码授权
cf d1 create --name liuyao-db # 可选,deploy 也会自动 provision
WORKER_DOMAIN=liuyao.example.com WORKER_ZONE=example.com npx cf deploy
```
1. 需要跨设备/多人看到同一份公告、同一套 LLM 配置;
2. 卦例要跨设备同步(D1);
3. 要给内测用户一个公网地址。
- `WORKER_DOMAIN` / `WORKER_ZONE` 写在 `cloudflare.config.ts` 的 `triggers.fetch` 里;
不设就只挂 `*.workers.dev`。域名必须已在同一个 Cloudflare 账号下托管(DNS 在 CF)。
- 部署产物:60 个静态资源 + Worker,**1.5MB / gzip 486KB**;绑定只有 `DB`(D1) 与 `ASSETS`,
不需要任何 secret(大模型 key 在用户浏览器里)。
- D1 表结构在首次请求时惰性建(`ensureD1Schema`),无需手工跑迁移。
- 上线后建议:给 `/api/read` 加 Cloudflare Rate Limiting 规则(内存限流只在单实例生效);
若担心被当免费代理,可把上游限制在供应商白名单。
## 五、真要部署时的时间账(已实测)
## 移动端
- 纯静态上线:约 1 小时(`output: 'export'` + Workers 静态资源 + 域名)。
- 带服务端:`vinext check` 对当前代码 94% 兼容、0 issue;
`vinext init --platform=cloudflare` 为非破坏性改造,`next dev` 可继续作为主开发流。
OpenNext 目前要求 `next >=15.5.29 <16 || >=16.4.5`,我们用 16.3.0,若走 OpenNext 需先升 Next。
- Cloudflare 官方已把新项目的 Next 方案改为 **vinext**(OpenNext 降为存量维护);
vinext 自身仍标注 "under active development",所以只在要加服务端能力时才引入,并做 `--preview` 验证。
不上架商店,走 **PWA**:
## 六、国内可达性
`*.workers.dev` 在国内常被阻断或很慢。真正上线应绑定自有域名(Cloudflare 代理),
并用手机流量实测;文档里「国内访问也很流畅」的说法不可作为依据。
## 七、M0 框架验证结果(2026-11-05,分支 `spike/vinext`)
环境:Windows 11 · Node v26.4.0 · npm 11.17 · Next 16.3.0 · React 19.3.1 · vite 8.3.0 · vinext 1.4.3
已验证:
| 项目 | 结果 |
|---|---|
| `vinext init --platform=cloudflare --cdn-cache=none --data-cache=none --image-optimization=none` | 生成 `vite.config.ts` + `cloudflare.config.ts`,React 升 19.3.1 |
| `vite dev`(workerd) | `/` `/liuyao` `/xct` `/cases` 全 200;六爻起卦→排盘→保存→打开、小成图起盘→点宫全部正常,0 console error |
| 本地 D1 | `bindings.d1({name})` + `cloudflare:workers` 的 `env.DB` 可建表/写入/查询,跨请求持久(`.cloudflare/state/v3/d1/*.sqlite`) |
| WebCrypto | HMAC-SHA256 签名/验签、`crypto.randomUUID` 可用 |
| `/api/read` | 指向本地 mock 上游时 SSE 逐字下发 + done 事件正常(workerd 内 fetch 流式 OK) |
| `vite build` / `vite preview` | 构建 3.5s;生产包页面 200、客户端 hydration 正常、D1 与 SSE 均正常 |
| 产物体积 | `.cloudflare/output` 8.2 MB(worker bundle ≈300 KB + assets),远低于 Workers 限制 |
| 既有回路回归 | `next dev` / `next build` 在 `type: module` + React 19.3.1 下仍正常;`tsc --noEmit` 通过;22 项测试通过;`check:portability` 通过 |
需要注意(M1 前要解决/确认):
1. **`.dev.vars` 没有映射进 workerd 的 `process.env`**;反而是 `bindings.text()` 文本绑定会被 nodejs_compat 映射到 `process.env`。
真实 secret(`cf` 的 secret)注入后 `process.env` 是否可见,需要在拿到账号后实测,再定 `getSecret()` 的写法(必要时改成 `cloudflare:workers` 的 `env`)。
2. `vinext dev` 会打印 `eval() is not supported... React dev mode`——React 开发期警告,生产无影响。
3. `vinext:optimize-imports` 对 `lucide-react` 部分图标跳过 barrel 优化(非报错)。
4. 某依赖声明 Node `^26.12.0`(当前 26.4.0 可用但不在声明区间);建议升 Node 26.12+ 或 24.x LTS。
5. `vinext init` 在 npm 11 + 用户级 `allow-scripts=workerd` 下会报 `EALLOWSCRIPTS`;本次用 `--userconfig` 绕过。
正式接入时把 `allowScripts` 收进项目配置,别依赖本机 npmrc。
6. **未做**:`vinext-cloudflare deploy`(wrangler/cf 未登录)、Cloudflare Access、真实 secret 注入。
- `app/manifest.ts` → `/manifest.webmanifest`(standalone、暖纸主题色、案例/历史排盘快捷方式)
- 图标:`public/icons/{icon-192,icon-512,icon-maskable-512,apple-touch-icon}.png`(由 `app/icon.svg` 渲染)
- `public/sw.js`:导航 network-first 回落离线壳;`/_next/static`、`/icons`、`/images`、`/fonts`、`/data`
cache-first + 后台更新;`/api/*` 一律直连不缓存
- `components/site/ServiceWorkerRegister.tsx`:只在**非本机域名**注册(localhost / *.local 自动注销)
- 效果:加到主屏后全屏无地址栏,**起卦与排盘离线可用**;解卦与历史同步需要联网。
File diff suppressed because it is too large Load Diff
+1 -36
View File
@@ -3,12 +3,11 @@
*
* 记录里不存盘面(盘面由引擎重算),只存能复现这一卦的最小事实:
* 六爻 → 时间 + 投掷 + 方法 + 问句 + 性别
* 小成图 → 时间 + 起卦法 + 四数 / 自定八卦
*/
import type { LiuyaoChart } from '@/lib/liuyao/najia';
import type { CastTimeInfo } from '@/lib/liuyao/ganzhi';
import type { CaseRecord, LiuyaoMethod, XctMethod } from '@/lib/store/types';
import type { CaseRecord, LiuyaoMethod } from '@/lib/store/types';
export function newCaseId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
@@ -45,40 +44,6 @@ export function buildLiuyaoRecord(args: {
};
}
export function buildXctRecord(args: {
benName: string;
zhiName: string;
center: string;
timeInput: string;
method: XctMethod;
tianDiNums?: [string, string, string, string];
timeDate?: string;
manual?: { benUpper: string; benLower: string; zhiUpper: string; zhiLower: string };
question?: string;
}): CaseRecord {
const { benName, zhiName, center, timeInput, method, tianDiNums, timeDate, manual, question = '' } = args;
return {
id: newCaseId(),
schema: 1,
kind: 'xct',
createdAt: new Date().toISOString(),
timeInput,
question,
input: {
kind: 'xct',
method,
...(tianDiNums ? { tianDiNums } : {}),
...(timeDate ? { timeDate } : {}),
...(manual ? { manual } : {}),
},
summary: {
primary: benName,
changed: zhiName,
tags: center ? [`中宫${center}`] : [],
},
};
}
/** 列表里的时间显示:优先显示起卦时间,退回收起时刻 */
export function caseTimeLabel(record: CaseRecord): string {
const raw = record.timeInput || record.createdAt;
+110
View File
@@ -0,0 +1,110 @@
/**
* 卦例写入校验(服务端 fail-closed)。
*
* 客户端可以伪造任何 JSON;这里只接受「能由引擎复现的最小事实」,
* 并对长度/枚举做硬约束,避免把无关大字段塞进 D1。
*/
import type { CaseInput, CaseRecord, CaseSummary } from '@/lib/store/types';
export class CaseValidationError extends Error {}
const ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
const TIME_RE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2})?/;
const ISO_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
function obj(v: unknown, field: string): Record<string, unknown> {
if (!v || typeof v !== 'object' || Array.isArray(v)) throw new CaseValidationError(`${field} 必须是对象`);
return v as Record<string, unknown>;
}
function str(v: unknown, max: number, field: string, allowEmpty = true): string {
if (typeof v !== 'string') throw new CaseValidationError(`${field} 必须是字符串`);
const s = v.trim();
if (!allowEmpty && !s) throw new CaseValidationError(`${field} 不能为空`);
if (s.length > max) throw new CaseValidationError(`${field} 超过 ${max} 字`);
return s;
}
export function parseCaseRecord(value: unknown): CaseRecord {
const o = obj(value, 'record');
const id = str(o.id, 64, 'id', false);
if (!ID_RE.test(id)) throw new CaseValidationError('id 格式不合法');
if (o.schema !== 1) throw new CaseValidationError('schema 必须为 1');
const kind = o.kind;
if (kind !== 'liuyao') throw new CaseValidationError('kind 不合法');
const createdAt = str(o.createdAt, 40, 'createdAt', false);
if (!ISO_RE.test(createdAt) || !Number.isFinite(new Date(createdAt).getTime())) {
throw new CaseValidationError('createdAt 必须是 ISO 时间');
}
const timeInput = str(o.timeInput, 40, 'timeInput', false);
if (!TIME_RE.test(timeInput)) throw new CaseValidationError('timeInput 格式应为 YYYY-MM-DDTHH:mm');
const question = str(o.question ?? '', 2000, 'question');
const genderRaw = o.gender;
if (genderRaw !== undefined && genderRaw !== null && genderRaw !== '男' && genderRaw !== '女') {
throw new CaseValidationError('gender 只能是 男/女');
}
const gender = genderRaw === '男' || genderRaw === '女' ? genderRaw : undefined;
const summary = parseSummary(o.summary);
const input = parseInput(o.input, kind);
const favorite = o.favorite === true;
return {
id,
schema: 1,
kind,
createdAt,
timeInput,
question,
...(gender ? { gender } : {}),
input,
summary,
...(favorite ? { favorite } : {}),
};
}
function parseSummary(value: unknown): CaseSummary {
const s = obj(value, 'summary');
const primary = str(s.primary, 100, 'summary.primary', false);
const changedRaw = s.changed;
const changed = changedRaw === undefined || changedRaw === null ? null : str(changedRaw, 100, 'summary.changed');
const tagsRaw = s.tags;
let tags: string[] | undefined;
if (tagsRaw !== undefined) {
if (!Array.isArray(tagsRaw)) throw new CaseValidationError('summary.tags 必须是数组');
if (tagsRaw.length > 8) throw new CaseValidationError('summary.tags 最多 8 个');
tags = tagsRaw.map((t, i) => str(t, 20, `summary.tags[${i}]`));
}
return { primary, changed, ...(tags ? { tags } : {}) };
}
function parseInput(value: unknown, kind: 'liuyao'): CaseInput {
const i = obj(value, 'input');
if (i.kind !== kind) throw new CaseValidationError('input.kind 与 record.kind 不一致');
const method = i.method;
if (method !== 'coin' && method !== 'yarrow' && method !== 'manual') {
throw new CaseValidationError('input.method 不合法');
}
if (!Array.isArray(i.coins) || i.coins.length !== 6) {
throw new CaseValidationError('input.coins 必须是 6 个投掷值');
}
const coins = i.coins.map((c, idx) => {
if (c !== 6 && c !== 7 && c !== 8 && c !== 9) {
throw new CaseValidationError(`input.coins[${idx}] 必须是 6/7/8/9`);
}
return c as 6 | 7 | 8 | 9;
});
const q = str(i.question ?? '', 2000, 'input.question');
const g = i.gender === '女' ? '女' : '男';
return { kind, method, coins, question: q, gender: g };
}
+23
View File
@@ -0,0 +1,23 @@
/**
* 最小 D1 接口(结构化类型)。
*
* 不依赖 `@cloudflare/workers-types` / `.cloudflare/types` 这些生成物:
* 生成的类型文件是 gitignore 的,fresh clone 上 tsc 不该因为缺它而失败。
*/
export interface D1Result<T = Record<string, unknown>> {
results?: T[];
success?: boolean;
}
export interface D1PreparedStatement {
bind(...values: unknown[]): D1PreparedStatement;
run(): Promise<unknown>;
all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
first<T = unknown>(): Promise<T | null>;
}
export interface D1Like {
prepare(sql: string): D1PreparedStatement;
batch?(statements: D1PreparedStatement[]): Promise<unknown>;
}
+26
View File
@@ -0,0 +1,26 @@
import { SCHEMA_STATEMENTS } from './schema.generated';
import type { D1Like } from '@/lib/db/d1-types';
const ensured = new WeakSet<object>();
/**
* D1 惰性建表(幂等)。
*
* 本地 miniflare 与首次部署都免手工迁移;schema 变更仍以 migrations/*.sql 为准,
* 这里只负责「表不存在就建」。
*/
export async function ensureD1Schema(db: D1Like): Promise<void> {
if (ensured.has(db as unknown as object)) return;
for (const statement of SCHEMA_STATEMENTS) {
try {
await db.prepare(statement).run();
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
// SQLite 没有 ADD COLUMN IF NOT EXISTS:迁移里的 ALTER 在已有库上会报重复列,
// 这属于「已经加过了」,跳过即可。
if (/duplicate column name/i.test(message)) continue;
throw e;
}
}
ensured.add(db as unknown as object);
}
+23
View File
@@ -0,0 +1,23 @@
/**
* 运行时绑定访问(仅服务端)—— D1 / KV 等 Workers 绑定入口。
*
* Next(dev/Node) 里没有 Workers 绑定;vinext/workerd 里通过 `cloudflare:workers` 取。
* 这里用**变量说明符**做动态 import:打包器不会静态解析,Node 下抛错被吞掉,
* Workers 下正常返回 env。这样同一份代码在两个运行时都不炸。
*/
export interface RuntimeEnv {
DB?: unknown;
[key: string]: unknown;
}
export async function getRuntimeEnv(): Promise<RuntimeEnv | null> {
try {
const specifier = 'cloudflare:workers';
const mod = (await import(/* webpackIgnore: true */ /* @vite-ignore */ specifier)) as {
env?: RuntimeEnv;
};
return mod?.env ?? null;
} catch {
return null;
}
}
+10
View File
@@ -0,0 +1,10 @@
/* 由 scripts/gen-db-schema.mjs 生成,请勿手改。
* 事实源:migrations/*.sql
*/
export const SCHEMA_SQL = "-- >>> 0001_init.sql\n-- 0001_init.sql\n-- 卦例表(Cloudflare D1 / SQLite)\n-- 约定:所有时间用 ISO-8601 字符串;JSON 以 TEXT 存储。\n-- 说明:后台(settings / llm_profiles / admin_audit)已下线,\n-- 大模型配置改由用户自带、只存在本机浏览器,服务端不落库。\n\nCREATE TABLE IF NOT EXISTS cases (\n id TEXT PRIMARY KEY,\n owner_id TEXT NOT NULL DEFAULT 'local',\n kind TEXT NOT NULL,\n created_at TEXT NOT NULL,\n time_input TEXT NOT NULL,\n question TEXT NOT NULL DEFAULT '',\n gender TEXT,\n input_json TEXT NOT NULL,\n summary_json TEXT NOT NULL,\n favorite INTEGER NOT NULL DEFAULT 0\n);\n\nCREATE INDEX IF NOT EXISTS idx_cases_owner_created ON cases (owner_id, created_at DESC);";
export const SCHEMA_STATEMENTS: readonly string[] = [
"CREATE TABLE IF NOT EXISTS cases (\n id TEXT PRIMARY KEY,\n owner_id TEXT NOT NULL DEFAULT 'local',\n kind TEXT NOT NULL,\n created_at TEXT NOT NULL,\n time_input TEXT NOT NULL,\n question TEXT NOT NULL DEFAULT '',\n gender TEXT,\n input_json TEXT NOT NULL,\n summary_json TEXT NOT NULL,\n favorite INTEGER NOT NULL DEFAULT 0\n)",
"CREATE INDEX IF NOT EXISTS idx_cases_owner_created ON cases (owner_id, created_at DESC)"
];
+9
View File
@@ -62,6 +62,15 @@ export function masksOf(values: number[]): { primary: number; moving: number; re
export const movingPositions = (values: number[]): number[] =>
values.flatMap((v, i) => (LINE_VALUES[v]?.moving ? [i] : []));
/**
* 动爻爻位 (1-based,自下而上):界面文案一律用这个。
*
* 踩过的坑:`movingPositions` 是 0-based 投掷序,直接拿去查「初/二/三…」
* 会整体错一位(初爻动查不到,二爻动显示成初爻)。
*/
export const movingLineNumbers = (values: number[]): number[] =>
movingPositions(values).map((i) => i + 1);
/**
* 拆解掩码各位为爻序与阴阳对象
*/
+807
View File
@@ -0,0 +1,807 @@
/**
* 64 卦经文(仅卦辞 + 爻辞,剥掉原版附带的「翻译 / 象征」注文)
*
* 事实源:bazi-web lib/hexagram/oracle.ts 的 ORACLE(源自大衍筮法 gua_db)。
* key = 六爻掩码(bit0 = 初爻,1 为阳),与 lib/hexagram/hex-math.ts 的 masksOf() 一致。
*
* 为什么只留经文:解卦 prompt 允许「辞象合参」,但模型不应看到现代翻译与注家发挥,
* 也不该由它补写原文。要引就引这两层原始文字。
*/
export interface OracleText {
/** 卦名全称 */
n: string;
/** 卦辞(仅第一段经文) */
g: string;
/** 爻辞:1..6 为初爻至上爻,yong 为用九/用六 */
y: Record<string, string>;
}
export const ORACLE_TEXT: Record<number, OracleText> = {
"0": {
"n": "坤为地",
"g": "元亨,利牝马之贞。君子有攸往,先迷后得主,利西南得朋,东北丧朋。安贞吉。",
"y": {
"1": "初六:履霜,坚冰至。",
"2": "六二:直,方,大,不习无不利。",
"3": "六三:含章可贞。或从王事,无成有终。",
"4": "六四:括囊;无咎,无誉。",
"5": "六五:黄裳,元吉。",
"6": "上六:龙战于野,其血玄黄。",
"yong": "用六:利永贞。"
}
},
"1": {
"n": "地雷复",
"g": "亨。出入无疾,朋来无咎。反复其道,七日来复,利有攸往。",
"y": {
"1": "初九:不远复,无祗悔,元吉。",
"2": "六二:休复,吉。",
"3": "六三:频复,厉无咎。",
"4": "六四:中行独复。",
"5": "六五:敦复,无悔。",
"6": "上六:迷复,凶,有灾眚。用行师,终有大败;以其国,君凶,至于十年不克征。"
}
},
"2": {
"n": "地水师",
"g": "师,贞,丈人吉,无咎。",
"y": {
"1": "初六:师出以律,否臧凶。",
"2": "九二:在师中,吉,无咎,王三锡命。",
"3": "六三:师或舆尸,凶。",
"4": "六四:师左次,无咎。",
"5": "六五:田有禽,利执言,无咎。长子帅师,弟子舆尸,贞凶。",
"6": "上六:大君有命,开国承家,小人勿用。"
}
},
"3": {
"n": "地泽临",
"g": "元亨,利贞。至于八月有凶。",
"y": {
"1": "初九:咸临,贞吉。",
"2": "九二:咸临,吉无不利。",
"3": "六三:甘临,无攸利。既忧之,无咎。",
"4": "六四:至临,无咎。",
"5": "六五:知临,大君之宜,吉。",
"6": "上六:敦临,吉,无咎。"
}
},
"4": {
"n": "地山谦",
"g": "亨,君子有终。",
"y": {
"1": "初六:谦谦君子,用涉大川,吉。",
"2": "六二:鸣谦,贞吉。",
"3": "九三:劳谦君子,有终,吉。",
"4": "六四:无不利,撝谦。",
"5": "六五:不富以其邻,利用侵伐,无不利。",
"6": "上六:鸣谦,利用行师,征邑国。"
}
},
"5": {
"n": "地火明夷",
"g": "明夷,利艰贞。",
"y": {
"1": "初九:明夷于飞,垂其翼。君子于行,三日不食。有攸往,主人忌。",
"2": "六二:明夷,夷于左股,用拯马壮,吉。",
"3": "九三:明夷于南狩,得其大首,不可疾贞。",
"4": "六四:入于左腹,获明夷之心,于出门庭。",
"5": "六五:箕子之明夷,利贞。",
"6": "上六:不明晦,初登于天,后入于地。"
}
},
"6": {
"n": "地风升",
"g": "元亨,用见大人,勿恤,南征吉。",
"y": {
"1": "初六:允升,大吉。",
"2": "九二:孚乃利用禴,无咎。",
"3": "九三:升虚邑。",
"4": "六四:王用亨于岐山,吉无咎。",
"5": "六五:贞吉,升阶。",
"6": "上六:冥升,利于不息之贞"
}
},
"7": {
"n": "地天泰",
"g": "小往大来,吉,亨。",
"y": {
"1": "初九:拔茅茹,以其汇,征吉。",
"2": "九二:包荒,用冯河,不遐遗,朋亡,得尚于中行。",
"3": "九三:无平不陂,无往不复,艰贞无咎。勿恤其孚,于食有福。",
"4": "六四:翩翩,不富以其邻,不戒以孚。",
"5": "六五:帝乙归妹,以祉元吉。",
"6": "上六:城复于隍,勿用师。自邑告命,贞吝。"
}
},
"8": {
"n": "雷地豫",
"g": "利建侯行师。",
"y": {
"1": "初六:鸣豫,凶。",
"2": "六二:介于石,不终日,贞吉。",
"3": "六三:盱豫,悔。迟有悔。",
"4": "九四:由豫,大有得。勿疑。朋盍簪。",
"5": "六五:贞疾,恒不死。",
"6": "上六:冥豫,成有渝,无咎。"
}
},
"9": {
"n": "震为雷",
"g": "亨。震来虩虩,笑言哑哑。震惊百里,不丧匕鬯。",
"y": {
"1": "初九:震来虩虩,后笑言哑哑,吉。",
"2": "六二:震来厉,亿丧贝,跻于九陵,勿逐,七日得。",
"3": "六三:震苏苏,震行无眚",
"4": "九四:震遂泥。",
"5": "六五:震往来厉,亿无丧,有事。",
"6": "上六:震索索,视矍矍,征凶。震不于其躬,于其邻,无咎。婚媾有言。"
}
},
"10": {
"n": "雷水解",
"g": "利西南,无所往,其来复吉。有攸往,夙吉。",
"y": {
"1": "初六:无咎。",
"2": "九二:田获三狐,得黄矢,贞吉。",
"3": "六三:负且乘,致寇至,贞吝。",
"4": "九四:解而拇,朋至斯孚。",
"5": "六五:君子维有解,吉;有孚于小人。",
"6": "上六:公用射隼于高墉之上,获之,无不利。"
}
},
"11": {
"n": "雷泽归妹",
"g": "征凶,无攸利。",
"y": {
"1": "初九:归妹以娣,跛能履,征吉。",
"2": "九二:眇能视,利幽人之贞。",
"3": "六三:归妹以须,反归以娣。",
"4": "九四:归妹愆期,迟归有时。",
"5": "六五:帝乙归妹,其君之袂,不如其娣之袂良。月几望,吉。",
"6": "上六:女承筐无实,士刲羊无血,无攸利。"
}
},
"12": {
"n": "雷山小过",
"g": "亨,利贞。可小事,不可大事。飞鸟遗之音,不宜上,宜下,大吉。",
"y": {
"1": "初六:飞鸟以凶。",
"2": "六二:过其祖,遇其妣;不及其君,遇其臣,无咎。",
"3": "九三:弗过防之,从或戕之,凶。",
"4": "九四:无咎,弗过遇之。往厉必戒,勿用永贞。",
"5": "六五:密云不雨,自我西郊,公弋取彼在穴。",
"6": "上六:弗遇过之,飞鸟离之,凶,是谓灾眚。"
}
},
"13": {
"n": "雷火丰",
"g": "丰,亨,王假之,勿忧,宜日中。",
"y": {
"1": "初九:遇其配主,虽旬无咎,往有尚。",
"2": "六二:丰其蔀,日中见斗,往得疑疾。有孚发若,吉。",
"3": "九三:丰其沛,日中见沬,折其右肱,无咎。",
"4": "九四:丰其蔀,日中见斗,遇其夷主,吉。",
"5": "六五:来章,有庆誉,吉。",
"6": "上六:丰其屋,蔀其家,窥其户,阒其无人,三岁不觌,凶。"
}
},
"14": {
"n": "雷风恒",
"g": "亨,无咎,利贞,利有攸往。",
"y": {
"1": "初六:浚恒,贞凶,无攸利。",
"2": "九二:悔亡。",
"3": "九三:不恒其德,或承之羞,贞吝。",
"4": "九四:田无禽。",
"5": "六五:恒其德,贞,妇人吉,夫子凶。",
"6": "上六:振恒,凶。"
}
},
"15": {
"n": "雷天大壮",
"g": "利贞。",
"y": {
"1": "初九:壮于趾,征凶,有孚。",
"2": "九二:贞吉。",
"3": "九三:小人用壮,君子用罔,贞厉。羝羊触藩,羸其角。",
"4": "九四:贞吉,悔亡。藩决不羸,壮于大舆之輹。",
"5": "六五:丧羊于易,无悔。",
"6": "上六:羝羊触藩,不能退,不能遂,无攸利,艰则吉。"
}
},
"16": {
"n": "水地比",
"g": "吉。原筮,元永贞,无咎。不宁方来,后夫凶。",
"y": {
"1": "初六:有孚比之,无咎。有孚盈缶,终来有它,吉。",
"2": "六二:比之自内,贞吉。",
"3": "六三:比之匪人。",
"4": "六四:外比之,贞吉。",
"5": "九五:显比,王用三驱,失前禽。邑人不诫,吉。",
"6": "上六:比之无首,凶。"
}
},
"17": {
"n": "水雷屯",
"g": "屯,元亨利贞。勿用有攸往,利建侯。",
"y": {
"1": "初九:磐桓,利居贞,利建侯。",
"2": "六二:屯如邅如,乘马班如。匪寇婚媾,女子贞不字,十年乃字。",
"3": "六三:即鹿无虞,惟入于林中,君子几不如舍,往吝。",
"4": "六四:乘马班如,求婚媾,往吉,无不利。",
"5": "九五:屯其膏,小贞吉,大贞凶。",
"6": "上六:乘马班如,泣血涟如。"
}
},
"18": {
"n": "坎为水",
"g": "习坎,有孚,维心亨,行有尚。",
"y": {
"1": "初六:习坎,入于坎窞,凶。",
"2": "九二:坎有险,求小得。",
"3": "六三:来之坎坎,险且枕,入于坎窞,勿用。",
"4": "六四:樽酒簋贰,用缶,纳约自牖,终无咎。",
"5": "九五:坎不盈,祇既平,无咎。",
"6": "上六:系用徽纆,置于丛棘,三岁不得,凶。"
}
},
"19": {
"n": "水泽节",
"g": "节,亨。苦节不可贞。",
"y": {
"1": "初九:不出户庭,无咎。",
"2": "九二:不出门庭,凶。",
"3": "六三:不节若,则嗟若,无咎。",
"4": "六四:安节,亨。",
"5": "九五:甘节,吉;往有尚。",
"6": "上六:苦节,贞凶,悔亡。"
}
},
"20": {
"n": "水山蹇",
"g": "利西南,不利东北。利见大人,贞吉。",
"y": {
"1": "初六:往蹇,来誉。",
"2": "六二:王臣蹇蹇,匪躬之故。",
"3": "九三:往蹇,来反。",
"4": "六四:往蹇,来连。",
"5": "九五:大蹇,朋来。",
"6": "上六:往蹇,来硕,吉,利见大人。"
}
},
"21": {
"n": "水火既济",
"g": "既济,亨小,利贞。初吉终乱。",
"y": {
"1": "初九:曳其轮,濡其尾,无咎。",
"2": "六二:妇丧其茀,勿逐,七日得。",
"3": "九三:高宗伐鬼方,三年克之,小人勿用。",
"4": "六四:繻有衣袽,终日戒。",
"5": "九五:东邻杀牛,不如西邻之禴祭,实受其福。",
"6": "上六:濡其首,厉。"
}
},
"22": {
"n": "水风井",
"g": "改邑不改井,无丧无得,往来井井。汔至,亦未繘井,羸其瓶,凶。",
"y": {
"1": "初六:井泥不食,旧井无禽。",
"2": "九二:井谷射鲋,瓮敝漏。",
"3": "九三:井渫不食,为我心恻,可用汲,王明,并受其福。",
"4": "六四:井甃,无咎。",
"5": "九五:井冽,寒泉食。",
"6": "上六:井收勿幕,有孚元吉。"
}
},
"23": {
"n": "水天需",
"g": "有孚,光亨,贞吉。利涉大川。",
"y": {
"1": "初九:需于郊,利用恒,无咎。",
"2": "九二:需于沙,小有言,终吉。",
"3": "九三:需于泥,致寇至。",
"4": "六四:需于血,出自穴。",
"5": "九五:需于酒食,贞吉。",
"6": "上六:入于穴,有不速之客三人来,敬之终吉。"
}
},
"24": {
"n": "泽地萃",
"g": "亨,王假有庙。利见大人,亨,利贞。用大牲吉,利有攸往。",
"y": {
"1": "初六:有孚不终,乃乱乃萃,若号,一握为笑,勿恤,往无咎。",
"2": "六二:引吉,无咎,孚乃利用禴。",
"3": "六三:萃如嗟如,无攸利,往无咎,小吝。",
"4": "九四:大吉,无咎。",
"5": "九五:萃有位,无咎,匪孚,元永贞,悔亡。",
"6": "上六:赍咨涕洟,无咎。"
}
},
"25": {
"n": "泽雷随",
"g": "元亨利贞,无咎。",
"y": {
"1": "初九:官有渝,贞吉。出门交有功。",
"2": "六二:系小子,失丈夫。",
"3": "六三:系丈夫,失小子。随有求得,利居贞。",
"4": "九四:随有获,贞凶。有孚在道,以明,何咎。",
"5": "九五:孚于嘉,吉。",
"6": "上六:拘系之,乃从维之。王用亨于西山。"
}
},
"26": {
"n": "泽水困",
"g": "亨,贞,大人吉,无咎。有言不信。",
"y": {
"1": "初六:臀困于株木,入于幽谷,三岁不觌。",
"2": "九二:困于酒食,朱绂方来,利用享祀。征凶,无咎。",
"3": "六三:困于石,据于蒺藜,入于其宫,不见其妻,凶。",
"4": "九四:来徐徐,困于金车,吝,有终。",
"5": "九五:劓刖,困于赤绂,乃徐有说,利用祭祀。",
"6": "上六:困于葛藟,于臲卼,曰动悔有悔,征吉。"
}
},
"27": {
"n": "兑为泽",
"g": "亨,利贞。",
"y": {
"1": "初九:和兑,吉。",
"2": "九二:孚兑,吉,悔亡。",
"3": "六三:来兑,凶。",
"4": "九四:商兑,未宁,介疾有喜。",
"5": "九五:孚于剥,有厉。",
"6": "上六:引兑。"
}
},
"28": {
"n": "泽山咸",
"g": "亨,利贞,取女吉。",
"y": {
"1": "初六:咸其拇。",
"2": "六二:咸其腓,凶,居吉。",
"3": "九三:咸其股,执其随,往吝。",
"4": "九四:贞吉,悔亡,憧憧往来,朋从尔思。",
"5": "九五:咸其脢,无悔。",
"6": "上六:咸其辅颊舌。"
}
},
"29": {
"n": "泽火革",
"g": "革,己日乃孚,元亨,利贞,悔亡。",
"y": {
"1": "初九:巩用黄牛之革。",
"2": "六二:己日乃革之,征吉,无咎。",
"3": "九三:征凶,贞厉。革言三就,有孚。",
"4": "九四:悔亡,有孚改命,吉。",
"5": "九五:大人虎变,未占有孚。",
"6": "上六:君子豹变,小人革面。征凶,居贞吉。"
}
},
"30": {
"n": "泽风大过",
"g": "栋桡,利有攸往,亨。",
"y": {
"1": "初六:藉用白茅,无咎。",
"2": "九二:枯杨生稊,老夫得其女妻,无不利。",
"3": "九三:栋桡,凶。",
"4": "九四:栋隆,吉;有它吝。",
"5": "九五:枯杨生华,老妇得其士夫,无咎无誉。",
"6": "上六:过涉灭顶,凶,无咎。"
}
},
"31": {
"n": "泽天夬",
"g": "扬于王庭,孚号有厉,告自邑,不利即戎,利有攸往。",
"y": {
"1": "初九:壮于前趾,往不胜为咎。",
"2": "九二:惕号,莫夜有戎,勿恤。",
"3": "九三:壮于頄,有凶。君子夬夬,独行遇雨,若濡有愠,无咎。",
"4": "九四:臀无肤,其行次且。牵羊悔亡,闻言不信。",
"5": "九五:苋陆夬夬,中行无咎。",
"6": "上六:无号,终有凶。"
}
},
"32": {
"n": "山地剥",
"g": "不利有攸往。",
"y": {
"1": "初六:剥床以足,蔑贞凶。",
"2": "六二:剥床以辨,蔑贞凶。",
"3": "六三:剥之,无咎。",
"4": "六四:剥床以肤,凶。",
"5": "六五:贯鱼,以宫人宠,无不利。",
"6": "上九:硕果不食,君子得舆,小人剥庐。"
}
},
"33": {
"n": "山雷颐",
"g": "贞吉。观颐,自求口实。",
"y": {
"1": "初九:舍尔灵龟,观我朵颐,凶。",
"2": "六二:颠颐,拂经,于丘颐,征凶。",
"3": "六三:拂颐,贞凶,十年勿用,无攸利。",
"4": "六四:颠颐,吉。虎视眈眈,其欲逐逐,无咎。",
"5": "六五:拂经,居贞吉,不可涉大川。",
"6": "上九:由颐,厉吉,利涉大川。"
}
},
"34": {
"n": "山水蒙",
"g": "亨。匪我求童蒙,童蒙求我。初筮告,再三渎,渎则不告。利贞。",
"y": {
"1": "初六:发蒙,利用刑人,用说桎梏,以往吝。",
"2": "九二:包蒙,吉。纳妇吉,子克家。",
"3": "六三:勿用取女,见金夫,不有躬,无攸利。",
"4": "六四:困蒙,吝。",
"5": "六五:童蒙,吉。",
"6": "上九:击蒙,不利为寇,利御寇。"
}
},
"35": {
"n": "山泽损",
"g": "有孚,元吉,无咎,可贞,利有攸往。曷之用?二簋可用享。",
"y": {
"1": "初九:已事遄往,无咎,酌损之。",
"2": "九二:利贞,征凶,弗损益之。",
"3": "六三:三人行,则损一人;一人行,则得其友。",
"4": "六四:损其疾,使遄有喜,无咎。",
"5": "六五:或益之十朋之龟,弗克违,元吉。",
"6": "上九:弗损益之,无咎,贞吉,利有攸往,得臣无家。"
}
},
"36": {
"n": "艮为山",
"g": "艮其背,不获其身;行其庭,不见其人,无咎。",
"y": {
"1": "初六:艮其趾,无咎,利永贞。",
"2": "六二:艮其腓,不拯其随,其心不快。",
"3": "九三:艮其限,列其夤,厉薰心。",
"4": "六四:艮其身,无咎。",
"5": "六五:艮其辅,言有序,悔亡。",
"6": "上九:敦艮,吉。"
}
},
"37": {
"n": "山火贲",
"g": "亨。小利有攸往。",
"y": {
"1": "初九:贲其趾,舍车而徒。",
"2": "六二:贲其须。",
"3": "九三:贲如濡如,永贞吉。",
"4": "六四:贲如皤如,白马翰如,匪寇婚媾。",
"5": "六五:贲于丘园,束帛戋戋,吝,终吉。",
"6": "上九:白贲,无咎。"
}
},
"38": {
"n": "山风蛊",
"g": "元亨,利涉大川。先甲三日,后甲三日。",
"y": {
"1": "初六:干父之蛊,有子,考无咎,厉终吉。",
"2": "九二:干母之蛊,不可贞。",
"3": "九三:干父之蛊,小有悔,无大咎。",
"4": "六四:裕父之蛊,往见吝。",
"5": "六五:干父之蛊,用誉。",
"6": "上九:不事王侯,高尚其事。"
}
},
"39": {
"n": "山天大畜",
"g": "利贞,不家食吉,利涉大川。",
"y": {
"1": "初九:有厉,利已。",
"2": "九二:舆说輹。",
"3": "九三:良马逐,利艰贞。曰闲舆卫,利有攸往。",
"4": "六四:童牛之牿,元吉。",
"5": "六五:豮豕之牙,吉。",
"6": "上九:何天之衢,亨。"
}
},
"40": {
"n": "火地晋",
"g": "康侯用锡马蕃庶,昼日三接。",
"y": {
"1": "初六:晋如摧如,贞吉,罔孚裕无咎。",
"2": "六二:晋如愁如,贞吉,受兹介福于其王母。",
"3": "六三:众允,悔亡。",
"4": "九四:晋如硕鼠,贞厉。",
"5": "六五:悔亡,失得勿恤,往吉无不利。",
"6": "上九:晋其角,维用伐邑,厉吉无咎,贞吝。"
}
},
"41": {
"n": "火雷噬嗑",
"g": "亨。利用狱。",
"y": {
"1": "初九:屦校灭趾,无咎。",
"2": "六二:噬肤灭鼻,无咎。",
"3": "六三:噬腊肉,遇毒;小吝,无咎。",
"4": "九四:噬乾胏,得金矢,利艰贞,吉。",
"5": "六五:噬乾肉,得黄金,贞厉,无咎。",
"6": "上九:何校灭耳,凶。"
}
},
"42": {
"n": "火水未济",
"g": "亨。小狐汔济,濡其尾,无攸利。",
"y": {
"1": "初六:濡其尾,吝。",
"2": "九二:曳其轮,贞吉。",
"3": "六三:未济,征凶,利涉大川。",
"4": "九四:贞吉,悔亡,震用伐鬼方,三年有赏于大国。",
"5": "六五:贞吉,无悔。君子之光,有孚,吉。",
"6": "上九:有孚于饮酒,无咎。濡其首,有孚失是。"
}
},
"43": {
"n": "火泽睽",
"g": "小事吉。",
"y": {
"1": "初九:悔亡,丧马勿逐,自复。见恶人,无咎。",
"2": "九二:遇主于巷,无咎。",
"3": "六三:见舆曳,其牛掣,其人天且劓,无初有终。",
"4": "九四:睽孤,遇元夫,交孚,厉无咎。",
"5": "六五:悔亡,厥宗噬肤,往何咎。",
"6": "上九:睽孤,见豕负涂,载鬼一车,先张之弧,后说之弧,匪寇婚媾,往遇雨则吉。"
}
},
"44": {
"n": "火山旅",
"g": "小亨。旅贞吉。",
"y": {
"1": "初六:旅琐琐,斯其所取灾。",
"2": "六二:旅即次,怀其资,得童仆,贞。",
"3": "九三:旅焚其次,丧其童仆,贞厉。",
"4": "九四:旅于处,得其资斧,我心不快。",
"5": "六五:射雉,一矢亡,终以誉命。",
"6": "上九:鸟焚其巢,旅人先笑后号咷。丧牛于易,凶。"
}
},
"45": {
"n": "离为火",
"g": "利贞,亨。畜牝牛,吉。",
"y": {
"1": "初九:履错然,敬之,无咎。",
"2": "六二:黄离,元吉。",
"3": "九三:日昃之离,不鼓缶而歌,则大耋之嗟,凶。",
"4": "九四:突如其来如,焚如,死如,弃如。",
"5": "六五:出涕沱若,戚嗟若,吉。",
"6": "上九:王用出征,有嘉折首,获匪其丑,无咎。"
}
},
"46": {
"n": "火风鼎",
"g": "元吉,亨。",
"y": {
"1": "初六:鼎颠趾,利出否。得妾以其子,无咎。",
"2": "九二:鼎有实,我仇有疾,不我能即,吉。",
"3": "九三:鼎耳革,其行塞,雉膏不食。方雨亏悔,终吉。",
"4": "九四:鼎折足,覆公餗,其形渥,凶。",
"5": "六五:鼎黄耳金铉,利贞。",
"6": "上九:鼎玉铉,大吉,无不利。"
}
},
"47": {
"n": "火天大有",
"g": "元亨。",
"y": {
"1": "初九:无交害,匪咎,艰则无咎。",
"2": "九二:大车以载,有攸往,无咎。",
"3": "九三:公用亨于天子,小人弗克。",
"4": "九四:匪其彭,无咎。",
"5": "六五:厥孚交如,威如,吉。",
"6": "上九:自天佑之,吉无不利。"
}
},
"48": {
"n": "风地观",
"g": "盥而不荐,有孚颙若。",
"y": {
"1": "初六:童观,小人无咎,君子吝。",
"2": "六二:窥观,利女贞。",
"3": "六三:观我生,进退。",
"4": "六四:观国之光,利用宾于王。",
"5": "九五:观我生,君子无咎。",
"6": "上九:观其生,君子无咎。"
}
},
"49": {
"n": "风雷益",
"g": "利有攸往,利涉大川。",
"y": {
"1": "初九:利用为大作,元吉,无咎。",
"2": "六二:或益之十朋之龟,弗克违,永贞吉。王用享于帝,吉。",
"3": "六三:益之用凶事,无咎。有孚中行,告公用圭。",
"4": "六四:中行,告公从。利用为依迁国。",
"5": "九五:有孚惠心,勿问元吉。有孚惠我德。",
"6": "上九:莫益之,或击之,立心勿恒,凶。"
}
},
"50": {
"n": "风水涣",
"g": "亨。王假有庙,利涉大川,利贞。",
"y": {
"1": "初六:用拯马壮,吉。",
"2": "九二:涣奔其机,悔亡。",
"3": "六三:涣其躬,无悔。",
"4": "六四:涣其群,元吉。涣有丘,匪夷所思。",
"5": "九五:涣汗其大号,涣王居,无咎。",
"6": "上九:涣其血去逖出,无咎。"
}
},
"51": {
"n": "风泽中孚",
"g": "豚鱼吉,利涉大川,利贞。",
"y": {
"1": "初九:虞吉,有它不燕",
"2": "九二:鸣鹤在阴,其子和之。我有好爵,吾与尔靡之。",
"3": "六三:得敌,或鼓或罢,或泣或歌。",
"4": "六四:月几望,马匹亡,无咎。",
"5": "九五:有孚挛如,无咎。",
"6": "上九:翰音登于天,贞凶。"
}
},
"52": {
"n": "风山渐",
"g": "女归吉,利贞。",
"y": {
"1": "初六:鸿渐于干,小子厉,有言,无咎。",
"2": "六二:鸿渐于磐,饮食衎衎,吉。",
"3": "九三:鸿渐于陆,夫征不复,妇孕不育,凶;利御寇。",
"4": "六四:鸿渐于木,或得其桷,无咎。",
"5": "九五:鸿渐于陵,妇三岁不孕,终莫之胜,吉。",
"6": "上九:鸿渐于陆,其羽可用为仪,吉。"
}
},
"53": {
"n": "风火家人",
"g": "利女贞。",
"y": {
"1": "初九:闲有家,悔亡。",
"2": "六二:无攸遂,在中馈,贞吉。",
"3": "九三:家人嗃嗃,悔厉吉。妇子嘻嘻,终吝。",
"4": "六四:富家,大吉。",
"5": "九五:王假有家,勿恤,吉。",
"6": "上九:有孚威如,终吉。"
}
},
"54": {
"n": "巽为风",
"g": "小亨,利攸往,利见大人。",
"y": {
"1": "初六:进退,利武人之贞。",
"2": "九二:巽在床下,用史巫纷若,吉,无咎。",
"3": "九三:频巽,吝。",
"4": "六四:悔亡,田获三品。",
"5": "九五:贞吉,悔亡,无不利。无初有终。先庚三日,后庚三日,吉。",
"6": "上九:巽在床下,丧其资斧,贞凶。"
}
},
"55": {
"n": "风天小畜",
"g": "亨。密云不雨,自我西郊。",
"y": {
"1": "初九:复自道,何其咎?吉。",
"2": "九二:牵复,吉。",
"3": "九三:舆说辐,夫妻反目。",
"4": "六四:有孚,血去惕出,无咎。",
"5": "九五:有孚挛如,富以其邻。",
"6": "上九:既雨既处,尚德载。妇贞厉。月几望,君子征凶。"
}
},
"56": {
"n": "天地否",
"g": "否之匪人,不利君子贞,大往小来。",
"y": {
"1": "初六:拔茅茹,以其汇,贞吉亨。",
"2": "六二:包承,小人吉,大人否亨。",
"3": "六三:包羞。",
"4": "九四:有命无咎,畴离祉。",
"5": "九五:休否,大人吉。",
"6": "上九:倾否,先否后喜。"
}
},
"57": {
"n": "天雷无妄",
"g": "元亨,利贞。其匪正有眚,不利有攸往。",
"y": {
"1": "初九:无妄,往吉。",
"2": "六二:不耕获,不菑畲,则利有攸往。",
"3": "六三:无妄之灾,或系之牛,行人之得,邑人之灾。",
"4": "九四:可贞,无咎。",
"5": "九五:无妄之疾,勿药有喜。",
"6": "上九:无妄,行有眚,无攸利。"
}
},
"58": {
"n": "天水讼",
"g": "有孚,窒惕,中吉,终凶。利见大人,不利涉大川。",
"y": {
"1": "初六:不永所事,小有言,终吉。",
"2": "九二:不克讼,归而逋,其邑人三百户,无眚。",
"3": "六三:食旧德,贞厉,终吉。或从王事,无成。",
"4": "九四:不克讼,复即命,渝,安贞吉。",
"5": "九五:讼,元吉。",
"6": "上九:或锡之鞶带,终朝三褫之。"
}
},
"59": {
"n": "天泽履",
"g": "履虎尾,不咥人,亨。",
"y": {
"1": "初九:素履,往无咎。",
"2": "九二:履道坦坦,幽人贞吉。",
"3": "六三:眇能视,跛能履,履虎尾,咥人,凶。武人为于大君。",
"4": "九四:履虎尾,愬愬,终吉。",
"5": "九五:夬履,贞厉。",
"6": "上九:视履考祥,其旋元吉。"
}
},
"60": {
"n": "天山遁",
"g": "亨,小利贞。",
"y": {
"1": "初六:遁尾,厉,勿用有攸往。",
"2": "六二:执之用黄牛之革,莫之胜说。",
"3": "九三:系遁,有疾厉,畜臣妾吉。",
"4": "九四:好遁,君子吉,小人否。",
"5": "九五:嘉遁,贞吉。",
"6": "上九:肥遁,无不利。"
}
},
"61": {
"n": "天火同人",
"g": "同人于野,亨。利涉大川,利君子贞。",
"y": {
"1": "初九:同人于门,无咎。",
"2": "六二:同人于宗,吝。",
"3": "九三:伏戎于莽,升其高陵,三岁不兴。",
"4": "九四:乘其墉,弗克攻,吉。",
"5": "九五:同人,先号啕而后笑,大师克相遇。",
"6": "上九:同人于郊,无悔。"
}
},
"62": {
"n": "天风姤",
"g": "女壮,勿用取女。",
"y": {
"1": "初六:系于金柅,贞吉。有攸往,见凶。羸豕孚蹢躅。",
"2": "九二:包有鱼,无咎,不利宾。",
"3": "九三:臀无肤,其行次且,厉,无大咎。",
"4": "九四:包无鱼,起凶。",
"5": "九五:以杞包瓜,含章,有陨自天。",
"6": "上九:姤其角,吝,无咎。"
}
},
"63": {
"n": "乾为天",
"g": "元亨利贞。",
"y": {
"1": "初九:潜龙勿用。",
"2": "九二:见龙在田,利见大人。",
"3": "九三:君子终日乾乾,夕惕若,厉无咎。",
"4": "九四:或跃在渊,无咎。",
"5": "九五:飞龙在天,利见大人。",
"6": "上九:亢龙有悔。",
"yong": "用九:见群龙无首,吉。"
}
}
};
/** 卦辞;缺卦返回 null(不编造) */
export function guaCi(mask: number): string | null {
return ORACLE_TEXT[mask]?.g ?? null;
}
/** 某爻爻辞;pos 1..6 或 'yong';缺辞返回 null */
export function yaoCi(mask: number, pos: number | 'yong'): string | null {
return ORACLE_TEXT[mask]?.y[String(pos)] ?? null;
}
export function hexMaskFromBinary(binary: string): number {
let mask = 0;
for (let i = 0; i < 6; i += 1) if (binary[i] === '1') mask |= 1 << i;
return mask;
}
+66
View File
@@ -0,0 +1,66 @@
/**
* 起卦参数在 URL 里的编解码。
*
* 为什么放 URL:卦是"一次投掷的时点产物",刷新、收藏、分享都该复原同一卦,
* 而页面本身仍是静态的(不在服务端存任何会话状态)。
*
* 参数刻意短:coins 用 0/1/2/3 表示 6/7/8/9(一位就能表达一爻),
* 性别用 g=男/女,婚否用 m=0/1。
*/
import type { CoinResult } from '@/components/liuyao/types';
export interface CastState {
coins: CoinResult[];
/** datetime-local:YYYY-MM-DDTHH:mm */
timeInput: string;
gender: '男' | '女';
marital: 'unmarried' | 'married';
question: string;
}
const TO_DIGIT: Record<number, string> = { 6: '0', 7: '1', 8: '2', 9: '3' };
const FROM_DIGIT: Record<string, CoinResult> = { 0: 6, 1: 7, 2: 8, 3: 9 };
export function encodeCastState(state: CastState): string {
const p = new URLSearchParams();
p.set('c', state.coins.map((v) => TO_DIGIT[v]).join(''));
p.set('t', state.timeInput);
p.set('g', state.gender);
p.set('m', state.marital === 'married' ? '1' : '0');
if (state.question.trim()) p.set('q', state.question.trim().slice(0, 200));
return p.toString();
}
export function decodeCastState(params: URLSearchParams): CastState | null {
const c = params.get('c');
const t = params.get('t');
if (!c || !t) return null;
if (!/^[0-3]{6}$/.test(c)) return null;
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(t)) return null;
const coins = c.split('').map((d) => FROM_DIGIT[d]) as CoinResult[];
const g = params.get('g') === '女' ? '女' : '男';
const marital = params.get('m') === '1' ? 'married' : 'unmarried';
return { coins, timeInput: t, gender: g, marital, question: params.get('q') ?? '' };
}
/**
* 爻值 → 三枚币面(仅用于展示)。
* 字 = 2、背 = 3:6 三字 · 7 一背 · 8 两背 · 9 三背。
*/
export function coinSidesOf(value: number): ('字' | '背')[] {
switch (value) {
case 6:
return ['字', '字', '字'];
case 7:
return ['背', '字', '字'];
case 8:
return ['背', '背', '字'];
case 9:
return ['背', '背', '背'];
default:
return ['字', '字', '字'];
}
}
+84
View File
@@ -0,0 +1,84 @@
/**
* 六十四卦索引与检索(手动指定用)
* ================================
* 手动指定的交互改成「可输入的下拉」:直接打字过滤,或用方向键在列表里挑。
* 这里只提供纯数据与纯函数,UI 在 components/cast/GuaCombobox.tsx。
*/
import { SIXTY_FOUR_HEXAGRAMS, type TrigramName } from '@/lib/liuyao/najia';
export interface GuaEntry {
binary: string;
/** 全名,如「天风姤」 */
name: string;
/** 简称,如「姤」 */
short: string;
palace: TrigramName;
rank: number;
upper: string;
lower: string;
}
const TRIGRAM_NAME: Record<string, string> = {
'111': '乾',
'110': '兑',
'101': '离',
'100': '震',
'011': '巽',
'010': '坎',
'001': '艮',
'000': '坤',
};
export const ALL_GUA: GuaEntry[] = Object.entries(SIXTY_FOUR_HEXAGRAMS).map(([binary, info]) => ({
binary,
name: info.name,
// 「乾为天」→「乾」;「天风姤」→「姤」
short: info.name.length >= 3 ? info.name.slice(2) : info.name,
palace: info.palace,
rank: info.rank,
upper: TRIGRAM_NAME[binary.slice(3, 6)] ?? '',
lower: TRIGRAM_NAME[binary.slice(0, 3)] ?? '',
}));
/** 八宫顺序(乾坎艮震巽离坤兑),用于列表排序 */
const PALACE_ORDER: TrigramName[] = ['乾', '坎', '艮', '震', '巽', '离', '坤', '兑'];
export const ALL_GUA_SORTED: GuaEntry[] = [...ALL_GUA].sort(
(a, b) => PALACE_ORDER.indexOf(a.palace) - PALACE_ORDER.indexOf(b.palace) || a.rank - b.rank,
);
export function guaByBinary(binary: string): GuaEntry | undefined {
return ALL_GUA.find((g) => g.binary === binary);
}
/** 两卦逐爻比对 → 动爻位(1..6,自初爻起) */
export function movingBetween(benBinary: string, zhiBinary: string): number[] {
const out: number[] = [];
for (let i = 0; i < 6; i += 1) if (benBinary[i] !== zhiBinary[i]) out.push(i + 1);
return out;
}
/** 由上下卦(三爻二进制串)拼 6 位二进制:初爻在下 */
export function binaryOf(upper: string, lower: string): string {
return `${lower}${upper}`;
}
/**
* 检索:全名、简称、宫名、上下卦组合(如「乾上兑下」)都能命中。
* 空串返回全部(按八宫序)。
*/
export function searchGua(query: string): GuaEntry[] {
const q = query.trim();
if (!q) return ALL_GUA_SORTED;
const lower = q.toLowerCase();
return ALL_GUA_SORTED.filter((g) => {
if (g.name.includes(q)) return true;
if (g.short === q || g.short.includes(q)) return true;
if (`${g.palace}宫`.includes(q)) return true;
if (`${g.upper}上${g.lower}下`.includes(q)) return true;
if (g.binary.includes(q.replace(/[^01]/g, '')) && /^[01]+$/.test(q)) return true;
if (g.name.toLowerCase().includes(lower)) return true;
return false;
});
}
+150
View File
@@ -0,0 +1,150 @@
/**
* 起卦随机源(密码学级)
* =======================
* 铁律:起卦的每一次投掷都必须来自 Web Crypto(`crypto.getRandomValues`),
* 不得使用 `Math.random()` —— 后者是 PRNG,可被预测、可复现,断卦结果就失去意义。
*
* 均匀性:币面只有「字 / 背」两态。这里不用 `x % 2`(会引入模偏差),
* 而是**逐位取用 Uint32 的最低有效位**(2^32 可整除 2,天然无偏),
* 每次调用取 32 枚币面,用完再取,避免频繁系统调用。
*
* 可核查:`tossStats()` 会统计字/背与 6/7/8/9 的分布,界面可展示实测频率,
* 让"是不是真随机"可被用户自己验证,而不是靠信任。
*/
export type CoinFace = 2 | 3; // 2 = 字(阴), 3 = 背(阳)
export type TossValue = 6 | 7 | 8 | 9;
const hasCrypto = () =>
typeof globalThis.crypto !== 'undefined' && typeof globalThis.crypto.getRandomValues === 'function';
let bitBuffer: number[] = [];
function nextBits(count: number): number[] {
if (!hasCrypto()) {
// 环境不支持 Web Crypto(极旧浏览器 / 非安全上下文)时**必须失败**,
// 绝不静默回落到 Math.random —— 那会让"随机"变成一句空话。
throw new Error(
'当前环境不支持 Web Crypto(crypto.getRandomValues)。起卦需要加密级随机数,请用 https 或更新的浏览器打开。',
);
}
const out: number[] = [];
while (out.length < count) {
if (bitBuffer.length === 0) {
const buf = new Uint32Array(16); // 一次取 16×32 = 512 位
crypto.getRandomValues(buf);
for (const word of buf) {
for (let i = 0; i < 32; i += 1) bitBuffer.push((word >>> i) & 1);
}
}
out.push(bitBuffer.pop() as number);
}
return out;
}
/** 单枚铜钱:字(2) / 背(3),各 50%,无模偏差 */
export function tossCoin(): CoinFace {
return nextBits(1)[0] === 1 ? 3 : 2;
}
/** 三钱一掷 */
export function tossThree(): [CoinFace, CoinFace, CoinFace] {
return [tossCoin(), tossCoin(), tossCoin()];
}
/** 三钱一掷 → 爻值(6 老阴 / 7 少阳 / 8 少阴 / 9 老阳) */
export function tossLine(): TossValue {
const [a, b, c] = tossThree();
return (a + b + c) as TossValue;
}
/** 连续 n 掷(用于「一键起卦」),一次取足随机位 */
export function tossLines(n: number): TossValue[] {
if (n <= 0) return [];
const bits = nextBits(n * 3);
const out: TossValue[] = [];
for (let i = 0; i < n; i += 1) {
let sum = 0;
for (let k = 0; k < 3; k += 1) sum += bits[i * 3 + k] === 1 ? 3 : 2;
out.push(sum as TossValue);
}
return out;
}
/**
* 0–9 的 n 个数字(用于需要随机数字的起卦输入)。
* 采用拒绝采样:Uint32 不能整除 10,直接取模会有偏差;
* 这里只接受 < 4294967290(= 2^32 − 6,10 的整数倍)的采样值,其余重采。
*/
export function secureDigits(n: number): string[] {
if (!hasCrypto()) throw new Error('当前环境不支持 Web Crypto,无法生成加密级随机数。');
const out: string[] = [];
const LIMIT = 4294967290; // 10 的倍数,且小于 2^32
while (out.length < n) {
const buf = new Uint32Array(Math.max(8, n - out.length));
crypto.getRandomValues(buf);
for (const v of buf) {
if (v >= LIMIT) continue; // 拒绝采样,保证均匀
out.push(String(v % 10));
if (out.length === n) break;
}
}
return out;
}
export interface TossStats {
total: number;
/** 字面(2)出现次数 */
faceCounts: Record<2 | 3, number>;
/** 爻值分布 */
valueCounts: Record<TossValue, number>;
/** 字面占比(理想 0.5),用于展示"是否均匀" */
faceRatio: number;
/** 与理论值的最大偏差(百分点) */
maxDeviation: number;
/** 理论分布(6/7/8/9) */
ideal: Record<TossValue, number>;
}
/**
* 三钱法的理论分布(用于自证与测试):
* 6 老阴(三字)= 1/8 · 7 少阳(一背两字)= 3/8
* 8 少阴(两背一字)= 3/8 · 9 老阳(三背)= 1/8
* 每枚铜钱字/背各 1/2,三枚独立 → 组合数 2³ = 8,故为以上比例。
*/
const IDEAL: Record<TossValue, number> = {
6: 1 / 8,
7: 3 / 8,
8: 3 / 8,
9: 1 / 8,
};
/** 供测试与界面展示:返回理论分布 */
export function __idealDistribution(): Record<TossValue, number> {
return { ...IDEAL };
}
/** 自证随机性:真跑 n 次,给出实测分布与偏差 */
export function tossStats(rounds = 3000): TossStats {
const faceCounts: Record<2 | 3, number> = { 2: 0, 3: 0 };
const valueCounts: Record<TossValue, number> = { 6: 0, 7: 0, 8: 0, 9: 0 };
for (let i = 0; i < rounds; i += 1) {
const bits = nextBits(3);
let sum = 0;
for (const b of bits) {
const face: 2 | 3 = b === 1 ? 3 : 2;
faceCounts[face] += 1;
sum += face;
}
valueCounts[sum as TossValue] += 1;
}
const totalFaces = rounds * 3;
const faceRatio = faceCounts[2] / totalFaces;
const maxDeviation = Math.max(
...([6, 7, 8, 9] as TossValue[]).map((v) => Math.abs(valueCounts[v] / rounds - IDEAL[v]) * 100),
);
return { total: rounds, faceCounts, valueCounts, faceRatio, maxDeviation, ideal: { ...IDEAL } };
}
+145
View File
@@ -0,0 +1,145 @@
/**
* 从解卦正文里解析「用神」,用于在盘面上高亮那一爻。
*
* 为什么用解析而不是让模型额外输出结构:模型已经按要求在第一段明写取用,
* 多加一个字段反而容易出现"字段与正文不一致"。这里只做保守提取:
* 1. 先在「取用 / 一、」段落里找形如「父母辛丑土」「妻财未土」「官鬼亥水」的片段;
* 2. 找不到干支时,认「以财爻为用」「取官鬼为用」这类取用句(含单字简称);
* 3. 再退「某某持世」「取世爻」这类说法;
* 4. 都没有就返回 null —— 宁可不标,也不标错。
*
* 地支只在**全文里该六亲只出现一个地支**时才补上(六亲多现则不猜)。
*/
export interface UseGodHint {
/** 六亲:父母/兄弟/子孙/妻财/官鬼 */
relation: '父母' | '兄弟' | '子孙' | '妻财' | '官鬼' | null;
/** 地支(子丑寅…),可能为空 */
branch: string | null;
/** 取自「世爻 / 应爻」时给出 */
role: '世' | '应' | null;
/** 命中的原文片段,便于在 UI 上回显核对 */
excerpt: string;
}
const RELATIONS = ['父母', '兄弟', '子孙', '妻财', '官鬼'] as const;
const BRANCHES = '子丑寅卯辰巳午未申酉戌亥';
const STEMS = '甲乙丙丁戊己庚辛壬癸';
type Relation = NonNullable<UseGodHint['relation']>;
/** 取用句里的六亲简称(「以财爻为用」→ 妻财) */
const RELATION_ALIAS: Record<string, Relation> = {
父母: '父母', 父: '父母',
兄弟: '兄弟', 兄: '兄弟',
子孙: '子孙', 孙: '子孙', 子: '子孙',
妻财: '妻财', 妻: '妻财', 财: '妻财',
官鬼: '官鬼', 官: '官鬼', 鬼: '官鬼',
};
/** 「以妻财为用」「财爻为用神」「取官鬼为用」 */
const USE_PHRASE =
/[以取]?\s*(父母|兄弟|子孙|妻财|父|兄|孙|子|妻|财|官|鬼)\s*(?:爻)?\s*(?:为用|作用)/;
/** 只看正文开头的取用段,避免后文"兼看"把结果带偏 */
function headOf(text: string, max = 320): string {
const clean = text.replace(/\*\*/g, '').replace(/\r/g, '');
const cut = clean.search(/二、|【二】/);
return cut > 0 ? clean.slice(0, cut) : clean.slice(0, max);
}
/** 全文里该六亲只对应唯一地支时才返回,六亲多现则返回 null */
function uniqueBranchOf(text: string, relation: string): { branch: string; excerpt: string } | null {
const re = new RegExp(`${relation}[\\s]?([${STEMS}])?([${BRANCHES}])[金木水火土]?`, 'g');
const seen = new Map<string, string>();
for (let m = re.exec(text); m; m = re.exec(text)) seen.set(m[2], m[0]);
if (seen.size !== 1) return null;
const [branch, excerpt] = [...seen.entries()][0];
return { branch, excerpt };
}
export function parseUseGod(text: string): UseGodHint | null {
if (!text || !text.trim()) return null;
const head = headOf(text);
const full = text.replace(/\*\*/g, '').replace(/\r/g, '');
// 1) 六亲 + 可选天干 + 地支(+ 五行)——最精确
for (const rel of RELATIONS) {
const re = new RegExp(`${rel}[\\s]?([${STEMS}])?([${BRANCHES}])`, 'g');
const m = re.exec(head);
if (m) {
return {
relation: rel,
branch: m[2],
role: null,
excerpt: m[0],
};
}
}
// 2) 取用句:「以财爻为用神」——只取六亲,地支回全文补(唯一才补)
const use = head.match(USE_PHRASE);
const relation = use ? RELATION_ALIAS[use[1]] : null;
if (relation) {
const hit = uniqueBranchOf(full, relation);
return {
relation,
branch: hit?.branch ?? null,
role: null,
excerpt: hit?.excerpt ?? relation,
};
}
// 3) 「某某持世」「取世爻」优先于纯六亲兜底
const world = head.match(/([父母兄弟子孙妻财官鬼])(?:爻)?持世|取?世爻/);
if (world) {
return {
relation: (world[1] as UseGodHint['relation']) ?? null,
branch: null,
role: '世',
excerpt: world[0],
};
}
// 4) 只写了六亲(正文没给地支):取最早出现的那个
let earliest: { rel: (typeof RELATIONS)[number]; at: number } | null = null;
for (const rel of RELATIONS) {
const at = head.indexOf(rel);
if (at >= 0 && (!earliest || at < earliest.at)) earliest = { rel, at };
}
if (earliest) {
return { relation: earliest.rel, branch: null, role: null, excerpt: earliest.rel };
}
// 5) 应爻为用
if (/取?应爻/.test(head)) {
return { relation: null, branch: null, role: '应', excerpt: '应爻' };
}
return null;
}
/** 用神提示 → 盘面第几爻(1..6);无法唯一确定时返回 null */
export function resolveUseGodLine(
hint: UseGodHint | null,
lines: { position: number; relation: string; branch: string; isWorld: boolean; isResponse: boolean }[],
): number | null {
if (!hint) return null;
if (hint.role === '世') {
return lines.find((l) => l.isWorld)?.position ?? null;
}
if (hint.role === '应') {
return lines.find((l) => l.isResponse)?.position ?? null;
}
if (hint.relation && hint.branch) {
// 给了地支就只认精确匹配:对不上宁可不标,也不退回到「六亲唯一」去猜
return lines.find((l) => l.relation === hint.relation && l.branch === hint.branch)?.position ?? null;
}
if (hint.relation) {
const same = lines.filter((l) => l.relation === hint.relation);
// 六亲多现时不猜:只有唯一一爻才高亮
if (same.length === 1) return same[0].position;
}
return null;
}
+151
View File
@@ -0,0 +1,151 @@
/**
* 大模型请求配置(服务端)
* =========================
* 用户的大模型设置只存在他自己浏览器里,随请求体一起到达;这里只做三件事:
* 1. 校验(地址/模型/key 的形态,非法直接 400,不去打上游);
* 2. 拦明显的内网地址(防 SSRF),本机 Ollama 放行;
* 3. 客户端没配置时,退回服务端环境变量(私人部署兜底)。
*
* 铁律:key 只在内存里活一次,不落库、不写日志、不回显给客户端。
*/
import { normalizeBaseUrl } from '@/lib/llm/settings';
export interface LlmRequestConfig {
baseUrl: string;
model: string;
key: string;
thinking?: 'enabled' | 'disabled';
reasoningEffort?: 'low' | 'high' | 'max';
}
export type LlmNormalizeResult = { ok: true; config: LlmRequestConfig | null } | { ok: false; error: string };
const MODEL_RE = /^[\w.:/@-]{1,80}$/;
/** 明显指向内网的地址(本机回环放行,供 Ollama 使用) */
function isPrivateHost(hostname: string): boolean {
const h = hostname.toLowerCase();
if (h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]') return false;
if (h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal')) return true;
const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if (!m) return false;
const [a, b] = [Number(m[1]), Number(m[2])];
if (a === 10) return true;
if (a === 127) return true;
if (a === 0) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 168) return true;
if (a === 100 && b >= 64 && b <= 127) return true;
return false;
}
export function normalizeLlmRequest(input: unknown): LlmNormalizeResult {
if (input === undefined || input === null) return { ok: true, config: envFallback() };
if (typeof input !== 'object') return { ok: false, error: 'llm 必须是对象' };
const o = input as Record<string, unknown>;
const baseUrl = typeof o.baseUrl === 'string' ? normalizeBaseUrl(o.baseUrl) : '';
const model = typeof o.model === 'string' ? o.model.trim() : '';
const apiKey = typeof o.apiKey === 'string' ? o.apiKey.trim() : '';
if (!baseUrl) return { ok: false, error: '接口地址为空' };
let url: URL;
try {
url = new URL(baseUrl);
} catch {
return { ok: false, error: '接口地址不是合法 URL' };
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
return { ok: false, error: '接口地址必须是 http(s)' };
}
if (url.username || url.password) return { ok: false, error: '接口地址不能内嵌账号密码' };
if (isPrivateHost(url.hostname)) return { ok: false, error: '接口地址不能指向内网' };
if (baseUrl.length > 300) return { ok: false, error: '接口地址过长' };
if (!model) return { ok: false, error: '模型名为空' };
if (!MODEL_RE.test(model)) return { ok: false, error: '模型名含非法字符' };
const isLocal = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]';
if (!apiKey && !isLocal) return { ok: false, error: '缺少 API Key' };
if (apiKey.length > 400) return { ok: false, error: 'API Key 过长' };
const thinking = o.thinking === 'enabled' || o.thinking === 'disabled' ? o.thinking : undefined;
const reasoningEffort =
o.reasoningEffort === 'low' || o.reasoningEffort === 'high' || o.reasoningEffort === 'max'
? o.reasoningEffort
: undefined;
return { ok: true, config: { baseUrl, model, key: apiKey, thinking, reasoningEffort } };
}
/**
* 可选的上游域名白名单(逗号分隔的域名后缀,如 `deepseek.com,openai.com,opencode.ai`)。
* 设了 `LLM_ALLOWED_HOSTS` 就只放行列表内的上游,防止本站被当成任意转发代理;
* 不设则放行任意 https 上游(保持「通用供应商」)。
*/
export function upstreamHostAllowed(baseUrl: string): { ok: true } | { ok: false; error: string } {
const raw = (typeof process !== 'undefined' ? process.env.LLM_ALLOWED_HOSTS : '') || '';
const list = raw
.split(',')
.map((x) => x.trim().toLowerCase())
.filter(Boolean);
if (!list.length) return { ok: true };
let host = '';
try {
host = new URL(baseUrl).hostname.toLowerCase();
} catch {
return { ok: false, error: '接口地址不合法' };
}
const hit = list.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));
return hit ? { ok: true } : { ok: false, error: `上游域名不在允许列表内:${host}` };
}
/**
* 上游是否值得重试(纯函数,便于测试)。
*
* 整份规范约 36k token 的前缀在网关满载时会被拒(429 / prefill_cap_refused / overloaded),
* 这类错误是瞬时的:同一请求隔几秒再来往往就成功,所以在服务端重试一次比让用户重点便宜。
*/
export function shouldRetryUpstream(status: number, bodyText: string): boolean {
if (status === 429 || status === 502 || status === 503 || status === 504) return true;
return /overloaded|prefill_cap_refused|at capacity|rate.?limit|too many requests|retry shortly/i.test(bodyText);
}
/** 把上游错误翻译成一句人话(前端不再显示原始 JSON) */
export function friendlyUpstreamError(status: number, bodyText: string): string {
if (status === 429 || /overloaded|at capacity|prefill_cap_refused/i.test(bodyText)) {
return '上游模型当前繁忙(429),稍等几秒再点「重试」即可;本次请求没有产生费用。';
}
if (status === 401 || status === 403) {
return '上游拒绝了这个 key(401/403):请到「设置」里核对 API Key 是否有权限。';
}
if (status === 404) {
return '上游 404:接口地址或模型名不对,请检查「设置」里的 Base URL 与模型名。';
}
const brief = bodyText.replace(/\s+/g, ' ').slice(0, 160);
return `上游返回 ${status}:${brief}`;
}
/** 私人部署兜底:服务端环境变量(客户端没配时才会用到) */
function envFallback(): LlmRequestConfig | null {
if (typeof process === 'undefined') return null;
const key = process.env.LLM_API_KEY || process.env.DEEPSEEK_API_KEY || process.env.OPENAI_API_KEY || '';
if (!key) return null;
return {
baseUrl: normalizeBaseUrl(process.env.LLM_BASE_URL || 'https://api.deepseek.com/v1'),
model: process.env.LLM_MODEL || 'deepseek-chat',
key,
thinking:
process.env.LLM_THINKING === 'enabled' || process.env.LLM_THINKING === 'disabled'
? process.env.LLM_THINKING
: undefined,
reasoningEffort:
process.env.LLM_REASONING_EFFORT === 'low' ||
process.env.LLM_REASONING_EFFORT === 'high' ||
process.env.LLM_REASONING_EFFORT === 'max'
? process.env.LLM_REASONING_EFFORT
: undefined,
};
}
+216
View File
@@ -0,0 +1,216 @@
/**
* 大模型设置(客户端)
* ====================
* 用户自带 key:只存浏览器 localStorage,解卦时随请求发给本站 `/api/read`,
* 由服务端原样转发到「OpenAI 兼容」的 `/chat/completions`。服务端不落库、不写日志。
*
* 为什么按「OpenAI 兼容」做通用层:国内外主流(OpenAI / DeepSeek / Moonshot /
* 智谱 / 通义 / OpenRouter / SiliconFlow / Ollama / 各类网关)都提供这个协议,
* 只要填 baseUrl + model + key 就能用,不必为每家写适配。
*/
export const LLM_SETTINGS_KEY = 'liuyao.llm.v1';
export interface LlmSettings {
/** 预设 id(custom 表示自己填) */
provider: string;
/** 不含 /chat/completions 的根地址,如 https://api.deepseek.com/v1 */
baseUrl: string;
model: string;
apiKey: string;
/** 思考模式:default 不显式传;enabled/disabled 显式开关(DeepSeek 等) */
thinking?: 'default' | 'enabled' | 'disabled';
/** 思考强度(部分供应商支持) */
reasoningEffort?: 'low' | 'high' | 'max';
}
export interface LlmProviderPreset {
id: string;
label: string;
baseUrl: string;
/** 建议模型(第一个作为默认) */
models: string[];
/** 是否需要 key(本地 Ollama 不需要) */
needsKey: boolean;
hint?: string;
}
export const LLM_PROVIDERS: LlmProviderPreset[] = [
{
id: 'deepseek',
label: 'DeepSeek 官方(支持上下文缓存)',
baseUrl: 'https://api.deepseek.com/v1',
models: ['deepseek-chat', 'deepseek-reasoner'],
needsKey: true,
hint: '官方 API 会自动缓存重复前缀:本站提示词约 4 万 token,第二次起命中缓存后输入按缓存价计(约为原价 1/10),预填充也更快,长前缀不易被限流。',
},
{
id: 'opencode-go',
label: 'OpenCode Zen / Go',
baseUrl: 'https://opencode.ai/zen/go/v1',
models: ['deepseek-v4.1-flash', 'deepseek-v4-pro', 'kimi-k3', 'glm-5.3', 'qwen3.8-max', 'claude-haiku-5-5'],
needsKey: true,
hint: '网关要求 x-opencode-session 路由头(本站在转发时自动补);key 形如 oc_sk_…',
},
{
id: 'openai',
label: 'OpenAI',
baseUrl: 'https://api.openai.com/v1',
models: ['gpt-4.1-mini', 'gpt-4o-mini', 'gpt-4.1'],
needsKey: true,
},
{
id: 'moonshot',
label: 'Moonshot / Kimi',
baseUrl: 'https://api.moonshot.cn/v1',
models: ['kimi-k2-0905-preview', 'moonshot-v1-32k', 'moonshot-v1-8k'],
needsKey: true,
},
{
id: 'zhipu',
label: '智谱 GLM',
baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
models: ['glm-4.6', 'glm-4-plus', 'glm-4-flash'],
needsKey: true,
},
{
id: 'dashscope',
label: '通义千问(DashScope)',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
models: ['qwen-plus', 'qwen-max', 'qwen-turbo'],
needsKey: true,
},
{
id: 'openrouter',
label: 'OpenRouter',
baseUrl: 'https://openrouter.ai/api/v1',
models: ['deepseek/deepseek-chat', 'anthropic/claude-3.7-sonnet', 'google/gemini-2.5-pro'],
needsKey: true,
},
{
id: 'siliconflow',
label: 'SiliconFlow 硅基流动',
baseUrl: 'https://api.siliconflow.cn/v1',
models: ['deepseek-ai/DeepSeek-V3', 'Qwen/Qwen2.5-72B-Instruct'],
needsKey: true,
},
{
id: 'ollama',
label: 'Ollama(本机)',
baseUrl: 'http://localhost:11434/v1',
models: ['qwen2.5', 'llama3.1'],
needsKey: false,
hint: '本机运行 Ollama 时可用,不需要 key;服务端与 Ollama 需在同一台机器。',
},
{
id: 'custom',
label: '自定义(任意 OpenAI 兼容接口)',
baseUrl: '',
models: [],
needsKey: true,
hint: '填到 /v1 为止,例如 https://your-gateway.com/v1。注意:服务端只放行白名单内的上游域名,自建网关需要先加入 LLM_ALLOWED_HOSTS。',
},
];
export function findProvider(id: string): LlmProviderPreset | null {
return LLM_PROVIDERS.find((p) => p.id === id) ?? null;
}
/** 地址归一:去尾斜杠;缺 /v1 的常见网关不自动补,交给用户看清楚 */
export function normalizeBaseUrl(input: string): string {
return input.trim().replace(/\/+$/, '');
}
export function isLlmConfigured(s: LlmSettings | null): boolean {
if (!s) return false;
if (!normalizeBaseUrl(s.baseUrl) || !s.model.trim()) return false;
const preset = findProvider(s.provider);
if (preset && !preset.needsKey) return true;
return Boolean(s.apiKey.trim());
}
/** 宽松校验:给 UI 提示用;真正的 SSRF 拦截在服务端 */
export function validateLlmSettings(s: LlmSettings): string | null {
const base = normalizeBaseUrl(s.baseUrl);
if (!base) return '请填写接口地址(Base URL)';
let url: URL;
try {
url = new URL(base);
} catch {
return '接口地址不是合法 URL';
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') return '接口地址必须是 http(s)';
if (!s.model.trim()) return '请填写模型名';
if (!/^[\w.:/@-]{1,80}$/.test(s.model.trim())) return '模型名含非法字符';
const preset = findProvider(s.provider);
if ((!preset || preset.needsKey) && !s.apiKey.trim()) return '请填写 API Key';
return null;
}
function safeParse(raw: string | null): LlmSettings | null {
if (!raw) return null;
try {
const o = JSON.parse(raw) as Partial<LlmSettings>;
if (!o || typeof o !== 'object') return null;
const provider = typeof o.provider === 'string' ? o.provider : 'custom';
const baseUrl = typeof o.baseUrl === 'string' ? o.baseUrl : '';
const model = typeof o.model === 'string' ? o.model : '';
const apiKey = typeof o.apiKey === 'string' ? o.apiKey : '';
const thinking =
o.thinking === 'enabled' || o.thinking === 'disabled' || o.thinking === 'default' ? o.thinking : undefined;
const reasoningEffort =
o.reasoningEffort === 'low' || o.reasoningEffort === 'high' || o.reasoningEffort === 'max'
? o.reasoningEffort
: undefined;
return { provider, baseUrl, model, apiKey, ...(thinking ? { thinking } : {}), ...(reasoningEffort ? { reasoningEffort } : {}) };
} catch {
return null;
}
}
export function loadLlmSettings(): LlmSettings | null {
if (typeof window === 'undefined') return null;
try {
return safeParse(window.localStorage.getItem(LLM_SETTINGS_KEY));
} catch {
return null;
}
}
export function saveLlmSettings(s: LlmSettings): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(
LLM_SETTINGS_KEY,
JSON.stringify({ ...s, baseUrl: normalizeBaseUrl(s.baseUrl), model: s.model.trim(), apiKey: s.apiKey.trim() }),
);
} catch {
/* 隐私模式:忽略 */
}
}
export function clearLlmSettings(): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.removeItem(LLM_SETTINGS_KEY);
} catch {
/* 忽略 */
}
}
/** 发给服务端的最小载荷(不含 provider 等 UI 字段) */
export function llmRequestPayload(s: LlmSettings): {
baseUrl: string;
model: string;
apiKey: string;
thinking?: 'enabled' | 'disabled';
reasoningEffort?: 'low' | 'high' | 'max';
} {
return {
baseUrl: normalizeBaseUrl(s.baseUrl),
model: s.model.trim(),
apiKey: s.apiKey.trim(),
...(s.thinking === 'enabled' || s.thinking === 'disabled' ? { thinking: s.thinking } : {}),
...(s.reasoningEffort ? { reasoningEffort: s.reasoningEffort } : {}),
};
}
+29 -51
View File
@@ -2,20 +2,18 @@
* 盘面事实打包(客户端安全,纯函数)。
*
* 这些函数产出的对象就是「允许离开浏览器」的全部内容:
* 卦名、纳甲、六亲、世应、动变、伏神、旬空、神煞、九宫断语、正推链。
* 卦名、纳甲、六亲、世应、动变、伏神、旬空、神煞、经文。
* 不含用神推断、不含 prompt、不含任何环境变量。
*/
import type { LiuyaoChart } from '@/lib/liuyao/najia';
import type { CastTimeInfo } from '@/lib/liuyao/ganzhi';
import type { BoardState, PalaceJudgment, PalaceNumber, ZhengTuiChain } from '@/lib/xct/types';
import { PALACE_NAMES, SIXTY_FOUR_HEXAGRAMS } from '@/lib/xct/constants';
import { calcGuShiShenSha } from '@/lib/zhanbu/shensha';
import { guaCi, hexMaskFromBinary, yaoCi } from '@/lib/hexagram/oracle-text';
import type {
LiuyaoLineFacts,
LiuyaoReadingFacts,
ReadingTimeFacts,
XctPalaceFacts,
XctReadingFacts,
} from './types';
export function timeFacts(time: CastTimeInfo): ReadingTimeFacts {
@@ -57,6 +55,12 @@ export function buildLiuyaoReadingFacts(
: {}),
}));
const mask = hexMaskFromBinary(chart.base.binary);
const changedMask = chart.changed ? hexMaskFromBinary(chart.changed.binary) : null;
const allMoving = chart.movingLines.length === 6;
const yongText = allMoving ? yaoCi(mask, 'yong') : null;
const ss = calcGuShiShenSha(chart.input.dayGz, chart.input.monthBranch);
return {
kind: 'liuyao',
question: question.trim().slice(0, 500),
@@ -79,54 +83,28 @@ export function buildLiuyaoReadingFacts(
voidBranches: chart.voidBranches as string[],
monthBody: { branch: chart.monthBody.branch, position: chart.monthBody.position },
shensha: {
yima: chart.shensha.yima,
taohua: chart.shensha.taohua,
lushen: chart.shensha.lushen,
guiren: chart.shensha.guiren,
tianyi: chart.shensha.tianyi,
wenchang: chart.shensha.wenchang,
guiren: ss.guiren,
lushen: ss.lushen,
yangren: ss.yangren,
wenchang: ss.wenchang,
yima: ss.yima,
taohua: ss.taohua,
jiangxing: ss.jiangxing,
huagai: ss.huagai,
mouxing: ss.mouxing,
jiesha: ss.jiesha,
zaisha: ss.zaisha,
tianyi: ss.tianyi,
tianxi: ss.tianxi,
},
lines,
};
}
export function buildXctReadingFacts(
board: BoardState,
judgments: Record<PalaceNumber, PalaceJudgment>,
chain: ZhengTuiChain,
time: CastTimeInfo,
question = '',
): XctReadingFacts {
const palaces: XctPalaceFacts[] = [];
for (let p = 1; p <= 9; p += 1) {
const j = judgments[p as PalaceNumber];
palaces.push({
palace: p,
palaceName: j.palaceName,
heaven: j.heaven,
earth: j.earth,
hexName: j.hexName,
mode: j.mode,
matched: j.matched,
verdict: j.verdict,
});
}
const name = (pair: { upper: string; lower: string }) =>
SIXTY_FOUR_HEXAGRAMS[pair.upper as never]?.[pair.lower as never] ?? `${pair.upper}${pair.lower}`;
return {
kind: 'xct',
question: question.trim().slice(0, 500),
time: timeFacts(time),
ben: { upper: board.ben.upper, lower: board.ben.lower, name: name(board.ben) },
zhi: { upper: board.zhi.upper, lower: board.zhi.lower, name: name(board.zhi) },
center: board.center,
palaces,
chain: {
path: chain.path.map((p) => PALACE_NAMES[p]),
summary: chain.summary,
endReason: chain.endReason ?? 'open',
hasCycle: chain.hasCycle,
oracle: {
baseGuaCi: guaCi(mask),
changedGuaCi: changedMask !== null ? guaCi(changedMask) : null,
movingLines: chart.movingLines
.map((pos) => ({ position: pos, text: yaoCi(mask, pos) }))
.filter((x): x is { position: number; text: string } => Boolean(x.text)),
yong: yongText ? { title: chart.base.name.startsWith('乾') ? '用九' : '用六', text: yongText } : null,
},
};
}
+41
View File
@@ -0,0 +1,41 @@
import type { LlmSettings } from '@/lib/llm/settings';
type ThinkingMode = NonNullable<LlmSettings['thinking']>;
type ReasoningEffort = NonNullable<LlmSettings['reasoningEffort']>;
/**
* 组装 chat/completions 请求体(纯函数,便于测试)。
*
* 思考模式(DeepSeek):
* - `thinking: {type: "enabled"|"disabled"}`;不传则由模型默认(deepseek-flash 默认开)
* - `reasoning_effort: "low"|"high"|"max"`
* - 思考模式下 temperature 会被忽略;这里仍保留低温度,供非思考模型使用
*/
export interface ChatBodyConfig {
model: string;
messages: { role: 'system' | 'user' | 'assistant'; content: string }[];
thinking?: ThinkingMode;
reasoningEffort?: ReasoningEffort;
stream?: boolean;
maxTokens?: number;
temperature?: number;
}
export function buildChatRequestBody(cfg: ChatBodyConfig): Record<string, unknown> {
const body: Record<string, unknown> = {
model: cfg.model,
stream: cfg.stream !== false,
temperature: cfg.temperature ?? 0.3,
max_tokens: cfg.maxTokens ?? 4096,
messages: cfg.messages,
};
if (cfg.thinking === 'enabled' || cfg.thinking === 'disabled') {
body.thinking = { type: cfg.thinking };
}
if (cfg.reasoningEffort) {
body.reasoning_effort = cfg.reasoningEffort;
}
return body;
}
File diff suppressed because one or more lines are too long
+42
View File
@@ -0,0 +1,42 @@
/**
* 上游请求头(纯函数)。
*
* 有些网关要求额外的路由头:opencode 的 zen/go 网关在**流式**请求上强制要求
* `x-opencode-session`,缺失直接 400 MissingSessionID。
* 这里按 baseUrl 主机名判断,只对需要的网关附加,不影响官方 API。
*/
const SESSION_HEADER = 'x-opencode-session';
/** 进程内稳定的会话标识(同一 Worker 实例复用,便于网关侧路由) */
let stableSession: string | null = null;
export function opencodeSessionId(): string {
if (stableSession) return stableSession;
const fromEnv = typeof process !== 'undefined' ? process.env.OPENCODE_SESSION : undefined;
stableSession =
fromEnv ||
`liuyao-${typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2)}`;
return stableSession;
}
export function needsOpencodeSession(baseUrl: string): boolean {
try {
return new URL(baseUrl).hostname.endsWith('opencode.ai');
} catch {
return false;
}
}
export function buildProviderHeaders(
baseUrl: string,
apiKey: string,
sessionId: string = opencodeSessionId(),
): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
};
if (needsOpencodeSession(baseUrl)) headers[SESSION_HEADER] = sessionId;
return headers;
}
+22 -28
View File
@@ -6,8 +6,8 @@
* 2. prompt 由服务端拼装(app/api/read/prompt.ts),不随客户端 bundle 下发;
* 3. 事实层只描述排盘结果,不含用神取舍与吉凶结论——那属于解读层。
*
* 现在只落地契约与 /api/read 通道,暂时没有前端入口:
* 断卦口径(宗法用神、吉凶表达、应期)是产品决策,定了再接 UI。
* 目前只有六爻一条链路:事实层由 lib/readings/facts.ts 打包,
* prompt 在 app/api/read/prompt.ts 服务端拼装。
*/
export interface ReadingTimeFacts {
@@ -45,40 +45,34 @@ export interface LiuyaoReadingFacts {
movingLines: number[];
voidBranches: string[];
monthBody: { branch: string; position: number };
/** 十三实用星煞(与盘面同一套算法) */
shensha: {
guiren: string;
lushen: string;
yangren: string;
wenchang: string;
yima: string;
taohua: string;
lushen: string;
guiren: string[];
jiangxing: string;
huagai: string;
mouxing: string;
jiesha: string;
zaisha: string;
tianyi: string;
wenchang: string;
tianxi: string;
};
lines: LiuyaoLineFacts[];
/** 经文层:只给卦辞与动爻爻辞(不含翻译/注家) */
oracle: {
baseGuaCi: string | null;
changedGuaCi: string | null;
movingLines: { position: number; text: string }[];
/** 六爻全动且为乾/坤时的用九/用六 */
yong: { title: string; text: string } | null;
};
}
export interface XctPalaceFacts {
palace: number;
palaceName: string;
heaven: string;
earth: string;
hexName: string;
mode: string | null;
matched: boolean | null;
verdict: string;
}
export interface XctReadingFacts {
kind: 'xct';
question: string;
time: ReadingTimeFacts;
ben: { upper: string; lower: string; name: string };
zhi: { upper: string; lower: string; name: string };
center: string;
palaces: XctPalaceFacts[];
chain: { path: string[]; summary: string; endReason: string; hasCycle: boolean };
}
export type ReadingFacts = LiuyaoReadingFacts | XctReadingFacts;
export type ReadingFacts = LiuyaoReadingFacts;
export interface ReadingRequestBody {
facts: ReadingFacts;
+43
View File
@@ -0,0 +1,43 @@
/**
* 匿名设备标识(卦例归属)。
*
* 不引入登录:首次访问卦例接口时下发一个 HttpOnly UUID Cookie,
* 服务端用它做 `owner_id` 隔离。以后接账号体系时,只换 ownerId 的来源,
* CaseStore 接口与前端都不用改。
*
* 边界(务必如实告知用户):同一浏览器/同一 Cookie 才能看到同一批卦例;
* 换设备、换浏览器或清除 Cookie 都会得到一个新的卦例夹。
*/
export const DEVICE_COOKIE = 'ly_device';
const ONE_YEAR = 365 * 24 * 3600;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function readCookie(req: Request, name: string): string | null {
const header = req.headers.get('cookie');
if (!header) return null;
for (const part of header.split(';')) {
const idx = part.indexOf('=');
if (idx < 0) continue;
if (part.slice(0, idx).trim() === name) return decodeURIComponent(part.slice(idx + 1).trim());
}
return null;
}
export interface DeviceIdentity {
ownerId: string;
/** 只在新建/替换时返回,调用方负责加到响应头 */
setCookie?: string;
}
export function getOrCreateDeviceId(req: Request): DeviceIdentity {
const existing = readCookie(req, DEVICE_COOKIE);
if (existing && UUID_RE.test(existing)) return { ownerId: existing };
const ownerId = crypto.randomUUID();
const secure = new URL(req.url).protocol === 'https:' ? '; Secure' : '';
return {
ownerId,
setCookie: `${DEVICE_COOKIE}=${ownerId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ONE_YEAR}${secure}`,
};
}
+36
View File
@@ -0,0 +1,36 @@
/** 请求侧小工具(服务端):客户端 IP、同源判断。 */
export function clientIp(req: Request): string {
const h = req.headers;
return (
h.get('cf-connecting-ip') ||
h.get('x-real-ip') ||
(h.get('x-forwarded-for') || '').split(',')[0].trim() ||
'unknown'
);
}
/** 写操作 CSRF 兜底:带 Origin 时必须与 Host 同源(curl/服务端调用没有 Origin,放行) */
export function sameOrigin(req: Request): boolean {
const origin = req.headers.get('origin');
if (!origin) return true;
try {
return new URL(origin).host === req.headers.get('host');
} catch {
return false;
}
}
/** 极简进程内限流(单 isolate 有效);上线后换 Cloudflare Rate Limiting */
const buckets = new Map<string, { count: number; resetAt: number }>();
export function rateLimit(key: string, max: number, windowMs: number): boolean {
const now = Date.now();
const cur = buckets.get(key);
if (!cur || cur.resetAt < now) {
buckets.set(key, { count: 1, resetAt: now + windowMs });
return false;
}
cur.count += 1;
return cur.count > max;
}
+130
View File
@@ -0,0 +1,130 @@
import { ensureD1Schema } from '@/lib/db/ensure-schema';
import type { D1Like } from '@/lib/db/d1-types';
import type { CaseRecord, CaseStore } from './types';
interface CaseRow {
id: string;
kind: string;
created_at: string;
time_input: string;
question: string;
gender: string | null;
input_json: string;
summary_json: string;
favorite: number;
}
const MAX_PER_OWNER = 200;
/**
* D1 版卦例存储(按 owner 隔离)。
*
* owner 来自匿名设备 Cookie,只在服务端感知;记录本身不带 owner 字段,
* 避免客户端伪造「写到别人名下」。
*/
export class D1CaseStore implements CaseStore {
readonly mode = 'remote' as const;
constructor(
private readonly db: D1Like,
private readonly ownerId: string,
) {}
private async ready(): Promise<void> {
await ensureD1Schema(this.db);
}
async list(): Promise<CaseRecord[]> {
await this.ready();
const res = await this.db
.prepare(
'SELECT id, kind, created_at, time_input, question, gender, input_json, summary_json, favorite FROM cases WHERE owner_id = ? AND kind = ? ORDER BY created_at DESC LIMIT ?',
)
.bind(this.ownerId, 'liuyao', MAX_PER_OWNER)
.all<CaseRow>();
return (res.results ?? []).map(rowToRecord).filter((r): r is CaseRecord => r !== null);
}
async get(id: string): Promise<CaseRecord | null> {
await this.ready();
const row = await this.db
.prepare(
'SELECT id, kind, created_at, time_input, question, gender, input_json, summary_json, favorite FROM cases WHERE owner_id = ? AND id = ? AND kind = ?',
)
.bind(this.ownerId, id, 'liuyao')
.first<CaseRow>();
return row ? rowToRecord(row) : null;
}
async save(record: CaseRecord): Promise<void> {
await this.ready();
await this.db
.prepare(
`INSERT INTO cases (id, owner_id, kind, created_at, time_input, question, gender, input_json, summary_json, favorite)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
kind = excluded.kind, created_at = excluded.created_at, time_input = excluded.time_input,
question = excluded.question, gender = excluded.gender, input_json = excluded.input_json,
summary_json = excluded.summary_json, favorite = excluded.favorite
WHERE cases.owner_id = excluded.owner_id`,
)
.bind(
record.id,
this.ownerId,
record.kind,
record.createdAt,
record.timeInput,
record.question,
record.gender ?? null,
JSON.stringify(record.input),
JSON.stringify(record.summary),
record.favorite ? 1 : 0,
)
.run();
// 每个 owner 只保留最近 200 条
await this.db
.prepare(
`DELETE FROM cases WHERE owner_id = ? AND id NOT IN (
SELECT id FROM cases WHERE owner_id = ? ORDER BY created_at DESC LIMIT ?
)`,
)
.bind(this.ownerId, this.ownerId, MAX_PER_OWNER)
.run();
}
async remove(id: string): Promise<void> {
await this.ready();
await this.db.prepare('DELETE FROM cases WHERE owner_id = ? AND id = ?').bind(this.ownerId, id).run();
}
async setFavorite(id: string, favorite: boolean): Promise<void> {
await this.ready();
await this.db
.prepare('UPDATE cases SET favorite = ? WHERE owner_id = ? AND id = ?')
.bind(favorite ? 1 : 0, this.ownerId, id)
.run();
}
}
function rowToRecord(row: CaseRow): CaseRecord | null {
try {
const input = JSON.parse(row.input_json);
const summary = JSON.parse(row.summary_json);
if (!input || typeof input !== 'object' || !summary || typeof summary !== 'object') return null;
return {
id: row.id,
schema: 1,
kind: 'liuyao',
createdAt: row.created_at,
timeInput: row.time_input,
question: row.question,
...(row.gender === '男' || row.gender === '女' ? { gender: row.gender } : {}),
input,
summary,
...(row.favorite ? { favorite: true } : {}),
} as CaseRecord;
} catch {
return null;
}
}
+58 -17
View File
@@ -1,38 +1,79 @@
import { LocalCaseStore, MemoryCaseStore } from './local-store';
import { RemoteCaseStore } from './remote';
import type { CaseStore } from './types';
let singleton: CaseStore | null = null;
const MIGRATED_KEY = 'liuyao.cases.migrated.v1';
let pending: Promise<CaseStore> | null = null;
/**
* 取卦例存储。
* 取卦例存储(异步)。
*
* 浏览器里是 localStorage;SSR / 测试环境退回内存实现(不落盘、不抛错),
* 保证组件在服务端渲染时调用也不会炸。
*
* 将来接 D1:`getCaseStore()` 按 `NEXT_PUBLIC_CASE_STORE` / 登录态返回 RemoteCaseStore 即可,
* 调用方(CasesView、保存按钮)不用改。
* 1. 先问服务端 `/api/cases?probe=1`:
* - mode=d1 → 用远端存储(匿名设备 Cookie 归属,持久化)
* - mode=memory(next dev 无绑定)→ 用本地 localStorage,避免"重启就丢"的错觉
* 2. 接口不可用(离线/未部署)→ 本地 localStorage
* 3. 切到远端时,把 localStorage 里的旧卦例一次性导入(按 id 幂等),避免历史丢失
*/
export function getCaseStore(): CaseStore {
if (singleton) return singleton;
export function getCaseStore(): Promise<CaseStore> {
if (!pending) pending = resolveCaseStore();
return pending;
}
async function resolveCaseStore(): Promise<CaseStore> {
if (typeof window === 'undefined') return new MemoryCaseStore();
try {
const res = await fetch('/api/cases?probe=1', { cache: 'no-store' });
if (res.ok) {
const { mode } = (await res.json()) as { mode?: string };
if (mode === 'd1') {
const remote = new RemoteCaseStore();
await migrateLocalCases(remote);
return remote;
}
}
} catch {
/* 接口不可用:退回本地 */
}
return localCaseStore();
}
function localCaseStore(): CaseStore {
if (typeof window !== 'undefined' && window.localStorage) {
try {
const probe = '__liuyao_probe__';
const probe = '__liuyao_cases_probe__';
window.localStorage.setItem(probe, '1');
window.localStorage.removeItem(probe);
singleton = new LocalCaseStore(window.localStorage);
return singleton;
return new LocalCaseStore(window.localStorage);
} catch {
// 隐私模式 / 配额禁用:退回内存,本次会话仍可用
/* 隐私模式 / 配额禁用 */
}
}
singleton = new MemoryCaseStore();
return singleton;
return new MemoryCaseStore();
}
async function migrateLocalCases(remote: RemoteCaseStore): Promise<void> {
if (typeof window === 'undefined' || !window.localStorage) return;
try {
if (window.localStorage.getItem(MIGRATED_KEY)) return;
} catch {
return;
}
try {
const records = await new LocalCaseStore(window.localStorage).list();
await remote.importAll(records);
window.localStorage.setItem(MIGRATED_KEY, '1');
} catch {
/* 网络失败就下次再试;不阻塞本次使用 */
}
}
/** 测试用:重置单例 */
export function __resetCaseStoreForTests(store?: CaseStore) {
singleton = store ?? null;
pending = store ? Promise.resolve(store) : null;
}
export { LocalCaseStore, MemoryCaseStore };
export { LocalCaseStore, MemoryCaseStore, RemoteCaseStore };
export * from './types';
+4 -1
View File
@@ -26,7 +26,7 @@ function isRecord(x: unknown): x is CaseRecord {
const r = x as Partial<CaseRecord>;
return (
typeof r.id === 'string' &&
(r.kind === 'liuyao' || r.kind === 'xct') &&
r.kind === 'liuyao' &&
typeof r.createdAt === 'string' &&
typeof r.timeInput === 'string' &&
typeof r.question === 'string' &&
@@ -50,6 +50,8 @@ function migrate(raw: unknown): CaseRecord[] {
}
export class LocalCaseStore implements CaseStore {
readonly mode = 'local' as const;
constructor(private readonly storage: StorageLike) {}
private read(): CaseRecord[] {
@@ -98,6 +100,7 @@ export class LocalCaseStore implements CaseStore {
/** 测试 / SSR 用的内存实现 */
export class MemoryCaseStore implements CaseStore {
readonly mode = 'local' as const;
private items: CaseRecord[] = [];
async list() {
return [...this.items].sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
+50
View File
@@ -0,0 +1,50 @@
import type { CaseRecord, CaseStore } from './types';
async function request<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, {
...init,
cache: 'no-store',
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
});
const json = (await res.json().catch(() => ({}))) as T & { error?: string };
if (!res.ok) throw new Error(json?.error || `请求失败(${res.status})`);
return json;
}
/**
* 远端卦例存储(D1)。归属由服务端的匿名设备 Cookie 决定,客户端不传 owner。
*/
export class RemoteCaseStore implements CaseStore {
readonly mode = 'remote' as const;
async list(): Promise<CaseRecord[]> {
const { cases } = await request<{ cases: CaseRecord[] }>('/api/cases');
return cases;
}
async get(id: string): Promise<CaseRecord | null> {
const res = await fetch(`/api/cases?id=${encodeURIComponent(id)}`, { cache: 'no-store' });
if (res.status === 404) return null;
if (!res.ok) throw new Error(`读取卦例失败(${res.status})`);
const json = (await res.json()) as { case?: CaseRecord | null };
return json.case ?? null;
}
async save(record: CaseRecord): Promise<void> {
await request('/api/cases', { method: 'POST', body: JSON.stringify({ record }) });
}
async remove(id: string): Promise<void> {
await request(`/api/cases?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
}
async setFavorite(id: string, favorite: boolean): Promise<void> {
await request('/api/cases', { method: 'PATCH', body: JSON.stringify({ id, favorite }) });
}
/** 一次性导入(本地 → 远端迁移用) */
async importAll(records: CaseRecord[]): Promise<void> {
if (!records.length) return;
await request('/api/cases', { method: 'POST', body: JSON.stringify({ cases: records }) });
}
}
+26
View File
@@ -0,0 +1,26 @@
import type { D1Like } from '@/lib/db/d1-types';
import { getRuntimeEnv } from '@/lib/db/runtime';
import { D1CaseStore } from './d1-case-store';
import { MemoryCaseStore } from './local-store';
import type { CaseStore } from './types';
const memoryByOwner = new Map<string, MemoryCaseStore>();
/**
* 服务端卦例存储(按匿名 owner 隔离)。
*
* - Workers/线上(有 DB 绑定):D1
* - next dev(无绑定):进程内存(客户端会看到 mode=memory,改走 localStorage,避免"重启就丢"的错觉)
*/
export async function getServerCaseStore(ownerId: string): Promise<{ store: CaseStore; mode: 'd1' | 'memory' }> {
const env = await getRuntimeEnv();
const db = env?.DB as D1Like | undefined;
if (db) return { store: new D1CaseStore(db, ownerId), mode: 'd1' };
let store = memoryByOwner.get(ownerId);
if (!store) {
store = new MemoryCaseStore();
memoryByOwner.set(ownerId, store);
}
return { store, mode: 'memory' };
}
+5 -19
View File
@@ -10,10 +10,9 @@
* 3. 记录带 schema 版本,读取时逐版迁移,绝不因字段变化丢历史。
*/
export type CaseKind = 'liuyao' | 'xct';
export type CaseKind = 'liuyao';
export type LiuyaoMethod = 'coin' | 'yarrow' | 'manual';
export type XctMethod = 'four' | 'time' | 'self';
export interface LiuyaoCaseInput {
kind: 'liuyao';
@@ -24,28 +23,13 @@ export interface LiuyaoCaseInput {
gender: '男' | '女';
}
export interface XctManual {
benUpper: string;
benLower: string;
zhiUpper: string;
zhiLower: string;
}
export interface XctCaseInput {
kind: 'xct';
method: XctMethod;
tianDiNums?: [string, string, string, string];
timeDate?: string;
manual?: XctManual;
}
export type CaseInput = LiuyaoCaseInput | XctCaseInput;
export type CaseInput = LiuyaoCaseInput;
/** 列表展示用快照(不作为事实来源) */
export interface CaseSummary {
/** 本卦 / 本图 */
primary: string;
/** 变卦(六爻)或 中宫归藏(小成图) */
/** 变卦(静卦为空) */
changed?: string | null;
/** 结构标签:六冲/归魂/… */
tags?: string[];
@@ -67,6 +51,8 @@ export interface CaseRecord {
}
export interface CaseStore {
/** local = 仅本机浏览器;remote = 服务端(D1,按匿名设备隔离) */
readonly mode?: 'local' | 'remote';
list(): Promise<CaseRecord[]>;
get(id: string): Promise<CaseRecord | null>;
save(record: CaseRecord): Promise<void>;
-238
View File
@@ -1,238 +0,0 @@
import { Trigram, HexagramPair, BoardState, PalaceNumber } from './types';
import { XIAN_TIAN_NUMBER, TRIGRAM_BITS, TIAN_DI_NUMBER_TO_GUA } from './constants';
import { calculateHuGua, guizang, bitsToTrigram } from './guizang';
import { Lunar } from 'lunar-javascript';
/**
* 依据本卦与之卦(变卦)构建小成图天地盘与中宫立极
*/
export function buildBoard(ben: HexagramPair, zhi: HexagramPair): BoardState {
// 1. 计算本互与之互
const benHu = calculateHuGua(ben);
const zhiHu = calculateHuGua(zhi);
// 2. 排布八宫天盘
// 离9: 本上;坎1: 本下;震3: 之上;兑7: 之下;
// 巽4: 本互上;坤2: 本互下;艮8: 之互上;乾6: 之互下
const heaven: Record<PalaceNumber, Trigram> = {
9: ben.upper,
1: ben.lower,
3: zhi.upper,
7: zhi.lower,
4: benHu.upper,
2: benHu.lower,
8: zhiHu.upper,
6: zhiHu.lower,
5: '乾', // 先占位,稍后立极填入
};
// 3. 中宫立极:四象统摄,大归藏入中
// 第一步:本之卦连环归藏 mid1 = (本上 ^ 本下) ^ (之上 ^ 之下)
const gBen = guizang(ben.upper, ben.lower);
const gZhi = guizang(zhi.upper, zhi.lower);
const mid1 = guizang(gBen, gZhi);
// 第二步:本互与之互连环归藏 mid2 = (本互上 ^ 本互下) ^ (之互上 ^ 之互下)
const gBenHu = guizang(benHu.upper, benHu.lower);
const gZhiHu = guizang(zhiHu.upper, zhiHu.lower);
const mid2 = guizang(gBenHu, gZhiHu);
// 第三步:两枢归藏入中宫 center = mid1 ^ mid2
const center = guizang(mid1, mid2);
heaven[5] = center;
return {
ben,
zhi,
benHu,
zhiHu,
heaven,
center,
centerSteps: {
a: ben.upper,
b: ben.lower,
mid1,
mid2,
},
};
}
/**
* 辅助函数:将六爻数字反求上下两经卦
*/
export function sixLinesToHexagram(lines: [number, number, number, number, number, number]): HexagramPair {
const lowerBits: [number, number, number] = [lines[0], lines[1], lines[2]];
const upperBits: [number, number, number] = [lines[3], lines[4], lines[5]];
return {
lower: bitsToTrigram(lowerBits),
upper: bitsToTrigram(upperBits),
};
}
/**
* 解析用户输入时间(支持 Date 对象或 'YYYY-MM-DDTHH:mm' / 'YYYY-MM-DD HH:mm' 字符串)
* 确保在本地时区下精确还原年月日时分,避免由于时区转换导致的偏差
*/
export function parseToLocalDate(input: Date | string = new Date()): Date {
if (input instanceof Date) {
return isNaN(input.getTime()) ? new Date() : input;
}
if (typeof input === 'string') {
const match = input.match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[T\s](\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?/);
if (match) {
const y = parseInt(match[1], 10);
const m = parseInt(match[2], 10) - 1;
const d = parseInt(match[3], 10);
const h = match[4] ? parseInt(match[4], 10) : 0;
const mi = match[5] ? parseInt(match[5], 10) : 0;
const s = match[6] ? parseInt(match[6], 10) : 0;
return new Date(y, m, d, h, mi, s);
}
const parsed = new Date(input);
return isNaN(parsed.getTime()) ? new Date() : parsed;
}
return new Date();
}
/**
* 提取起卦时刻详情(公历、农历与四柱干支存证)
*/
export function getDivinationTimeInfo(dateInput: Date | string = new Date()): {
solarDateStr: string;
lunarDateStr: string;
ganzhiStr: string;
iso: string;
} {
const date = parseToLocalDate(dateInput);
const lunar = Lunar.fromDate(date) as any;
const solarDateStr = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
const lunarDateStr = `${lunar.getYearInChinese()}年 农历${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}`;
const ganzhiStr = `${lunar.getYearInGanZhiExact()}年 ${lunar.getMonthInGanZhiExact()}月 ${lunar.getDayInGanZhiExact()}日 ${lunar.getTimeInGanZhi()}时`;
return {
solarDateStr,
lunarDateStr,
ganzhiStr,
iso: date.toISOString(),
};
}
/**
* 经典梅花易数时间起卦法:
* 1. 年支数 (子1..亥12) + 农历月 (1..12) + 农历日 (1..30) 除以 8 取余数(余0作8)为上卦(先天八卦数)。
* 2. 年支数 + 农历月 + 农历日 + 时支数 (子1..亥12) 除以 8 取余数(余0作8)为下卦(先天八卦数)。
* 3. 年月日时总和除以 6 取余数(余0作6)为动爻 (1..6)。
* 4. 动爻发动翻转阴阳生成变卦(之卦)。
* 5. 依据本卦与变卦构建小成图天地盘与大归藏中宫立极。
*/
export function buildBoardFromMeihuaTime(dateInput: Date | string = new Date()): {
board: BoardState;
movingYao: number;
timeInfo: {
solarDateStr: string;
lunarDateStr: string;
ganzhiStr: string;
yearZhi: string;
yearZhiNum: number;
lunarMonth: number;
lunarDay: number;
hourZhi: string;
hourZhiNum: number;
upperSum: number;
lowerSum: number;
upperRem: number;
lowerRem: number;
movingYao: number;
};
} {
const date = parseToLocalDate(dateInput);
const lunar = Lunar.fromDate(date) as any;
const DIZHI_LIST = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
const yearZhi = lunar.getYearZhiExact();
const yearZhiNum = DIZHI_LIST.indexOf(yearZhi) + 1;
const lunarMonth = Math.abs(lunar.getMonth());
const lunarDay = lunar.getDay();
const hourZhi = lunar.getTimeZhi();
const hourZhiNum = DIZHI_LIST.indexOf(hourZhi) + 1;
// 上卦:(年支 + 农历月 + 农历日) % 8
const upperSum = yearZhiNum + lunarMonth + lunarDay;
const upperRem = upperSum % 8 === 0 ? 8 : upperSum % 8;
const benUpper = XIAN_TIAN_NUMBER[upperRem];
// 下卦:(年支 + 农历月 + 农历日 + 时支) % 8
const lowerSum = upperSum + hourZhiNum;
const lowerRem = lowerSum % 8 === 0 ? 8 : lowerSum % 8;
const benLower = XIAN_TIAN_NUMBER[lowerRem];
const ben: HexagramPair = { upper: benUpper, lower: benLower };
// 动爻:(年支 + 农历月 + 农历日 + 时支) % 6
const movingYao = lowerSum % 6 === 0 ? 6 : lowerSum % 6;
// 动爻翻转生成变卦
const lowerBits = TRIGRAM_BITS[benLower];
const upperBits = TRIGRAM_BITS[benUpper];
const sixLines = [...lowerBits, ...upperBits] as [number, number, number, number, number, number];
const changedIdx = movingYao - 1;
sixLines[changedIdx] = sixLines[changedIdx] === 1 ? 0 : 1;
const zhi = sixLinesToHexagram(sixLines);
const board = buildBoard(ben, zhi);
const solarDateStr = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
const lunarDateStr = `${lunar.getYearInChinese()}年 ${lunar.getMonthInChinese()}月${lunar.getDayInChinese()}`;
const ganzhiStr = `${lunar.getYearInGanZhiExact()}年 ${lunar.getMonthInGanZhiExact()}月 ${lunar.getDayInGanZhiExact()}日 ${lunar.getTimeInGanZhi()}时`;
return {
board,
movingYao,
timeInfo: {
solarDateStr,
lunarDateStr,
ganzhiStr,
yearZhi,
yearZhiNum,
lunarMonth,
lunarDay,
hourZhi,
hourZhiNum,
upperSum,
lowerSum,
upperRem,
lowerRem,
movingYao,
},
};
}
/**
* 天地数起卦(四数):原 App 'four' 模式(小成图独门起卦法,小事首选)
* 随口报 4 数(各取 0 至 9)。
* 前两数相重为本卦(上、下),后两数相重为之卦(上、下)。
* 直接成卦,不需动爻。
*/
export function buildBoardFromTianDiNumbers(
nums: [number, number, number, number]
): BoardState {
const mapped = nums.map((n) => {
const val = ((n % 10) + 10) % 10;
return TIAN_DI_NUMBER_TO_GUA[val] || '坤';
});
const ben: HexagramPair = { upper: mapped[0], lower: mapped[1] };
const zhi: HexagramPair = { upper: mapped[2], lower: mapped[3] };
return buildBoard(ben, zhi);
}
/**
* 自定选卦(点选八卦):原 App 'self' 模式
*/
export function buildBoardFromManualTrigrams(
benUpper: Trigram,
benLower: Trigram,
zhiUpper: Trigram,
zhiLower: Trigram
): BoardState {
return buildBoard({ upper: benUpper, lower: benLower }, { upper: zhiUpper, lower: zhiLower });
}
-332
View File
@@ -1,332 +0,0 @@
import { Trigram, PalaceNumber, FourImagesMode, EightVerdicts } from './types';
/** 八卦三爻二进制定义 [初爻, 二爻, 三爻] (1为阳爻,0为阴爻) */
export const TRIGRAM_BITS: Record<Trigram, [number, number, number]> = {
乾: [1, 1, 1],
兑: [1, 1, 0],
离: [1, 0, 1],
震: [1, 0, 0],
巽: [0, 1, 1],
坎: [0, 1, 0],
艮: [0, 0, 1],
坤: [0, 0, 0],
};
/** 八卦卦名列表 */
export const ALL_TRIGRAMS: Trigram[] = ['乾', '兑', '离', '震', '巽', '坎', '艮', '坤'];
/** 后天八卦九宫地盘映射 */
export const PALACE_TO_GUA: Record<PalaceNumber, string> = {
1: '坎',
2: '坤',
3: '震',
4: '巽',
5: '中',
6: '乾',
7: '兑',
8: '艮',
9: '离',
};
/** 后天八卦各卦对应的地盘本宫号 */
export const GUA_TO_PALACE: Record<Trigram, PalaceNumber> = {
坎: 1,
坤: 2,
震: 3,
巽: 4,
乾: 6,
兑: 7,
艮: 8,
离: 9,
};
/** 九宫中文名 */
export const PALACE_NAMES: Record<PalaceNumber, string> = {
1: '坎一宫',
2: '坤二宫',
3: '震三宫',
4: '巽四宫',
5: '中五宫',
6: '乾六宫',
7: '兑七宫',
8: '艮八宫',
9: '离九宫',
};
/** 宫位五行属性 */
export const PALACE_WUXING: Record<PalaceNumber, string> = {
1: '水',
2: '土',
3: '木',
4: '木',
5: '土',
6: '金',
7: '金',
8: '土',
9: '火',
};
/** 八卦阴阳:阳卦(乾震坎艮)为true,阴卦(坤巽离兑)为false */
export const TRIGRAM_YANG: Record<Trigram, boolean> = {
乾: true,
震: true,
坎: true,
艮: true,
坤: false,
巽: false,
离: false,
兑: false,
};
/**
* 八卦升降律(霍斐然小成图公理):
* 乾震艮升,坤巽兑降;
* 水火互根,离火独升,坎水独降。
* 升为 true,降为 false。
*/
export const TRIGRAM_RISING: Record<Trigram, boolean> = {
乾: true,
震: true,
艮: true,
离: true, // 离虽阴卦,其性炎上,独升
坤: false,
巽: false,
兑: false,
坎: false, // 坎虽阳卦,其性润下,独降
};
/** 先天八卦数起卦映射 */
export const XIAN_TIAN_NUMBER: Record<number, Trigram> = {
1: '乾',
2: '兑',
3: '离',
4: '震',
5: '巽',
6: '坎',
7: '艮',
8: '坤',
};
/** 天地数配卦映射(小成图独门配卦:天一乾、地二坤、天三艮、地四兑、天五坎、地六离、天七震、地八巽、天九乾、地十坤) */
export const TIAN_DI_NUMBER_TO_GUA: Record<number, Trigram> = {
1: '乾',
2: '坤',
3: '艮',
4: '兑',
5: '坎',
6: '离',
7: '震',
8: '巽',
9: '乾',
10: '坤',
0: '坤',
};
/** 高亨宜变法往复循环路径 (初至上、上至初折返往复) */
export const GAO_HENG_PATH = [1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1];
/** 地支列表 */
export const DI_ZHI = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
/** 64 卦重卦名称速查矩阵 [上卦][下卦] */
export const SIXTY_FOUR_HEXAGRAMS: Record<Trigram, Record<Trigram, string>> = {
乾: {
乾: '乾为天',
兑: '天泽履',
离: '天火同人',
震: '天雷无妄',
巽: '天风姤',
坎: '天水讼',
艮: '天山遁',
坤: '天地否',
},
兑: {
乾: '泽天夬',
兑: '兑为泽',
离: '泽火革',
震: '泽雷随',
巽: '泽风大过',
坎: '泽水困',
艮: '泽山咸',
坤: '泽地萃',
},
离: {
乾: '火天大有',
兑: '火泽睽',
离: '离为火',
震: '火雷噬嗑',
巽: '火风鼎',
坎: '火水未济',
艮: '火山旅',
坤: '火地晋',
},
震: {
乾: '雷天大壮',
兑: '雷泽归妹',
离: '雷火丰',
震: '震为雷',
巽: '雷风恒',
坎: '雷水解',
艮: '雷山小过',
坤: '雷地豫',
},
巽: {
乾: '风天小畜',
兑: '风泽中孚',
离: '风火家人',
震: '风雷益',
巽: '巽为风',
坎: '风水涣',
艮: '风山渐',
坤: '风地观',
},
坎: {
乾: '水天需',
兑: '水泽节',
离: '水火既济',
震: '水雷屯',
巽: '水风井',
坎: '坎为水',
艮: '水山蹇',
坤: '水地比',
},
艮: {
乾: '山天大畜',
兑: '山泽损',
离: '山火贲',
震: '山雷颐',
巽: '山风蛊',
坎: '山水蒙',
艮: '艮为山',
坤: '山地剥',
},
坤: {
乾: '地天泰',
兑: '地泽临',
离: '地火明夷',
震: '地雷复',
巽: '地风升',
坎: '地水师',
艮: '地山谦',
坤: '坤为地',
},
};
/** 四象与八断决断字典 */
export const FOUR_IMAGES_VERDICTS: Record<
FourImagesMode,
{ matched: EightVerdicts; unmatched: EightVerdicts; note: string }
> = {
阖: {
matched: '吉',
unmatched: '凶',
note: '向心,天地交合收敛(如地天泰,天地交而万物通)',
},
辟: {
matched: '害',
unmatched: '利',
note: '离心,天地背离散开(如天地否,天地不交而万物不通)',
},
往: {
matched: '亨',
unmatched: '悔',
note: '上升外引,向外发展推进;悔为吉之渐,历经波折转为吉',
},
来: {
matched: '贞',
unmatched: '吝',
note: '下降内引,向内收聚回归;贞为正固守常,吝为阻滞不足',
},
};
/** 天盘寻卦标准巡查顺序 (原著宗法) */
export const SEEK_ORDER: PalaceNumber[] = [9, 1, 3, 7, 4, 2, 8, 6];
/** 八卦对待相错映射 (旁推法:天地定位、山泽通气、雷风相薄、水火不相射) */
export const OPPOSITE_TRIGRAM: Record<Trigram, Trigram> = {
乾: '坤',
坤: '乾',
艮: '兑',
兑: '艮',
震: '巽',
巽: '震',
坎: '离',
离: '坎',
};
/** 后天八卦数映射(坎1、坤2、震3、巽4、乾6、兑7、艮8、离9) */
export const HOU_TIAN_NUMBER: Record<number, Trigram> = {
1: '坎',
2: '坤',
3: '震',
4: '巽',
6: '乾',
7: '兑',
8: '艮',
9: '离',
};
/** 卦名转后天数 */
export const GUA_TO_HOU_TIAN_NUMBER: Record<Trigram, number> = {
坎: 1,
坤: 2,
震: 3,
巽: 4,
乾: 6,
兑: 7,
艮: 8,
离: 9,
};
/** 卦名转先天数 */
export const GUA_TO_XIAN_TIAN_NUMBER: Record<Trigram, number> = {
乾: 1,
兑: 2,
离: 3,
震: 4,
巽: 5,
坎: 6,
艮: 7,
坤: 8,
};
/**
* 后天八卦九宫所配地支映射:
* 坎一宫:子
* 艮八宫:丑、寅
* 震三宫:卯
* 巽四宫:辰、巳
* 离九宫:午
* 坤二宫:未、申
* 兑七宫:酉
* 乾六宫:戌、亥
* 中五宫:寄旺于四季辰戌丑未
*/
export const PALACE_TO_BRANCHES: Record<PalaceNumber, string[]> = {
1: ['子'],
2: ['未', '申'],
3: ['卯'],
4: ['辰', '巳'],
5: ['辰', '戌', '丑', '未'],
6: ['戌', '亥'],
7: ['酉'],
8: ['丑', '寅'],
9: ['午'],
};
/** 地支所属后天八宫映射 */
export const BRANCH_TO_PALACE: Record<string, PalaceNumber> = {
'子': 1,
'丑': 8,
'寅': 8,
'卯': 3,
'辰': 4,
'巳': 4,
'午': 9,
'未': 2,
'申': 2,
'酉': 7,
'戌': 6,
'亥': 6,
};
-103
View File
@@ -1,103 +0,0 @@
import { BoardState, PalaceNumber, ZhengTuiChain, ZhengTuiNode } from './types';
import { GUA_TO_PALACE, PALACE_NAMES } from './constants';
import { judgePalace } from './judgeEngine';
/**
* 追踪小成图正推因果链(气路链 DAG)
* 原理:从用神宫出发,看天盘何卦;该天盘卦归其地盘本宫,再看该宫天盘何卦;
* 如此层层正推因果,直至闭环(成环)或归中宫止。
*/
export function traceZhengTuiChain(board: BoardState, startPalace: PalaceNumber): ZhengTuiChain {
const path: PalaceNumber[] = [startPalace];
const visited = new Set<PalaceNumber>([startPalace]);
let curr = startPalace;
let hasCycle = false;
let endReason: 'guiwei' | 'cycle' | 'center' | 'open' = 'open';
for (let step = 0; step < 8; step++) {
const heavenGua = board.heaven[curr];
// 中宫不落八方
if (curr === 5 || !heavenGua) {
endReason = curr === 5 ? 'center' : 'open';
break;
}
const nextPalace = GUA_TO_PALACE[heavenGua];
if (!nextPalace) break;
// 归位:天盘卦即本宫地盘卦 —— 气止得位,是终局,不是闭环。
// 旧实现把两者都算作 hasCycle,会把「事已归元」误报成「矛盾自缠」。
if (nextPalace === curr) {
endReason = 'guiwei';
break;
}
if (visited.has(nextPalace)) {
path.push(nextPalace);
hasCycle = true;
endReason = 'cycle';
break;
}
path.push(nextPalace);
visited.add(nextPalace);
curr = nextPalace;
if (curr === 5) {
endReason = 'center';
break;
}
}
// 构造沿途节点判语
const nodes: ZhengTuiNode[] = path.map((palace, idx) => {
const judgment = judgePalace(board, palace);
const isLoopOrEnd =
idx === path.length - 1 && (hasCycle || palace === 5 || endReason === 'guiwei');
return {
palace,
palaceName: PALACE_NAMES[palace],
heaven: board.heaven[palace],
judgment,
isLoopOrEnd,
};
});
// 构造摘要
const stepTexts = nodes.map((n, i) => {
// 起手即止(归位 / 中宫 / 天盘缺卦):只有一站,不能说成「起因」就完事
if (i === 0 && nodes.length === 1) {
if (endReason === 'guiwei') {
return `【起手归位·气止】${n.palaceName}天盘即本宫地盘,卦归本位,气机无待演化`;
}
if (n.palace === 5) {
return `【用神在中宫】${n.palaceName}立极归藏·${n.heaven}`;
}
return `【起因/用神】${n.palaceName}(${n.judgment.hexName || n.heaven})·${n.judgment.verdict}(气路未成链)`;
}
if (i === 0) {
return `【起因/用神】${n.palaceName}(${n.judgment.hexName || n.heaven})·${n.judgment.verdict}`;
}
if (i === nodes.length - 1 && endReason === 'guiwei') {
return `【归位·气止】${n.palaceName}天盘即本宫地盘,卦归本位,气机释放完毕`;
}
if (i === nodes.length - 1 && hasCycle) {
return `【闭环成因】归至${n.palaceName}形成气路因果循环`;
}
if (i === nodes.length - 1 && n.palace === 5) {
return `【最终归宿】气归中五宫(立极归藏)·${n.heaven}`;
}
return `【演化第${i}阶段】转入${n.palaceName}(${n.judgment.hexName})·${n.judgment.verdict}`;
});
const summary = stepTexts.join(' ➔ ');
return {
startPalace,
nodes,
path,
hasCycle,
endReason,
summary,
};
}
-60
View File
@@ -1,60 +0,0 @@
import { Trigram, HexagramPair } from './types';
import { TRIGRAM_BITS } from './constants';
/**
* 将 3 个布尔/数字爻位转换为卦名
* [初爻, 二爻, 三爻] (1为阳,0为阴)
*/
export function bitsToTrigram(bits: [number, number, number]): Trigram {
for (const [trigram, b] of Object.entries(TRIGRAM_BITS)) {
if (b[0] === bits[0] && b[1] === bits[1] && b[2] === bits[2]) {
return trigram as Trigram;
}
}
return '乾';
}
/**
* 归藏法:两卦逐爻异或(同性为阴0,异性为阳1)
* 归藏易核心算子:3-bit XOR
*/
export function guizang(t1: Trigram, t2: Trigram): Trigram {
const b1 = TRIGRAM_BITS[t1];
const b2 = TRIGRAM_BITS[t2];
const res: [number, number, number] = [
b1[0] === b2[0] ? 0 : 1,
b1[1] === b2[1] ? 0 : 1,
b1[2] === b2[2] ? 0 : 1,
];
return bitsToTrigram(res);
}
/**
* 四卦连环归藏:(t1 ^ t2) ^ (t3 ^ t4)
*/
export function guizangFour(t1: Trigram, t2: Trigram, t3: Trigram, t4: Trigram): Trigram {
const g12 = guizang(t1, t2);
const g34 = guizang(t3, t4);
return guizang(g12, g34);
}
/**
* 求重卦的互卦
* 下互:二、三、四爻;上互:三、四、五爻
*/
export function calculateHuGua(hex: HexagramPair): HexagramPair {
const lowerBits = TRIGRAM_BITS[hex.lower];
const upperBits = TRIGRAM_BITS[hex.upper];
// 6 爻自下而上排列 [1, 2, 3, 4, 5, 6] 对应索引 [0, 1, 2, 3, 4, 5]
const sixLines = [...lowerBits, ...upperBits];
// 下互取 2, 3, 4 爻(索引 1, 2, 3)
const lowerHuBits: [number, number, number] = [sixLines[1], sixLines[2], sixLines[3]];
// 上互取 3, 4, 5 爻(索引 2, 3, 4)
const upperHuBits: [number, number, number] = [sixLines[2], sixLines[3], sixLines[4]];
return {
lower: bitsToTrigram(lowerHuBits),
upper: bitsToTrigram(upperHuBits),
};
}
-108
View File
@@ -1,108 +0,0 @@
import { BoardState, PalaceNumber, PalaceJudgment, FourImagesMode, Trigram } from './types';
import {
PALACE_TO_GUA,
PALACE_NAMES,
TRIGRAM_RISING,
TRIGRAM_YANG,
FOUR_IMAGES_VERDICTS,
SIXTY_FOUR_HEXAGRAMS,
} from './constants';
/**
* 判定单宫吉凶得失(小成图四象八断核心逻辑)
*/
export function judgePalace(board: BoardState, palace: PalaceNumber): PalaceJudgment {
const heaven = board.heaven[palace];
const earth = PALACE_TO_GUA[palace];
const palaceName = PALACE_NAMES[palace];
// 1. 中宫特殊处理:归藏之枢,中立立极
if (palace === 5 || earth === '中') {
return {
palace,
palaceName,
heaven,
earth,
mode: null,
matched: null,
verdict: '归藏之枢',
hexName: '',
meaning: `中宫归藏得「${heaven}」,为全盘八方气数之总归藏,体现事态整体本质与核心枢纽。`,
};
}
// 2. 归位:天盘卦与本宫地盘卦相同
// 气归本位、因果气机释放完毕,此处即正推终局,不判吉凶。
// 若不特判,同卦阴阳必同 → matched 恒为 false,会被硬扣上「悔 / 吝」。
const earthTrigram = earth as Trigram;
if (heaven === earthTrigram) {
return {
palace,
palaceName,
heaven,
earth,
mode: null,
matched: null,
verdict: '归位',
hexName: SIXTY_FOUR_HEXAGRAMS[heaven][earthTrigram],
meaning: `天盘${heaven}临本宫地盘${earth},卦归本位,为「归位」——事已归元、气机释放完毕,此处即终局,不作吉凶断。`,
};
}
// 3. 地盘八宫正常研判
const r = TRIGRAM_RISING[heaven];
const s = TRIGRAM_RISING[earthTrigram];
// 升降定四象:天降地升为阖,天升地降为辟,天地皆升为往,天地皆降为来
let mode: FourImagesMode;
if (!r && s) {
mode = '阖';
} else if (r && !s) {
mode = '辟';
} else if (r && s) {
mode = '往';
} else {
mode = '来';
}
// 阴阳定得配:异性为得配,同性为失配
const matched = TRIGRAM_YANG[heaven] !== TRIGRAM_YANG[earthTrigram];
// 四象得配失配断八字(吉、凶、害、利、吝、悔、贞、亨)
const info = FOUR_IMAGES_VERDICTS[mode];
const verdict = matched ? info.matched : info.unmatched;
// 上天下地合成重卦名
const hexName = SIXTY_FOUR_HEXAGRAMS[heaven][earthTrigram];
const heavenYangStr = TRIGRAM_YANG[heaven] ? '阳' : '阴';
const heavenRiseStr = r ? '升' : '降';
const earthYangStr = TRIGRAM_YANG[earthTrigram] ? '阳' : '阴';
const earthRiseStr = s ? '升' : '降';
const matchStr = matched ? '得配' : '失配';
const meaning = `天盘${heaven}(${heavenYangStr}${heavenRiseStr})临地盘${earth}(${earthYangStr}${earthRiseStr}),合成【${hexName}】,成「${mode}」式,阴阳${matchStr},决断为「${verdict}」。${info.note}。`;
return {
palace,
palaceName,
heaven,
earth,
mode,
matched,
verdict,
hexName,
meaning,
};
}
/**
* 全盘九宫一次性判定
*/
export function judgeFullBoard(board: BoardState): Record<PalaceNumber, PalaceJudgment> {
const result = {} as Record<PalaceNumber, PalaceJudgment>;
for (let p = 1; p <= 9; p++) {
result[p as PalaceNumber] = judgePalace(board, p as PalaceNumber);
}
return result;
}
-69
View File
@@ -1,69 +0,0 @@
export type Trigram = '乾' | '兑' | '离' | '震' | '巽' | '坎' | '艮' | '坤';
export type PalaceNumber = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
export type FourImagesMode = '阖' | '辟' | '往' | '来';
export type EightVerdicts = '吉' | '凶' | '害' | '利' | '吝' | '悔' | '贞' | '亨' | '归藏之枢' | '归位';
export interface HexagramPair {
upper: Trigram;
lower: Trigram;
}
export interface BoardState {
ben: HexagramPair;
zhi: HexagramPair;
benHu: HexagramPair;
zhiHu: HexagramPair;
heaven: Record<PalaceNumber, Trigram>;
center: Trigram;
centerSteps: {
a: Trigram;
b: Trigram;
mid1: Trigram;
mid2: Trigram;
};
}
export interface PalaceJudgment {
palace: PalaceNumber;
palaceName: string;
heaven: Trigram;
earth: string;
mode: FourImagesMode | null;
matched: boolean | null;
verdict: EightVerdicts;
hexName: string;
meaning: string;
}
export interface ZhengTuiNode {
palace: PalaceNumber;
palaceName: string;
heaven: Trigram;
judgment: PalaceJudgment;
isLoopOrEnd: boolean;
}
export interface ZhengTuiChain {
startPalace: PalaceNumber;
nodes: ZhengTuiNode[];
path: PalaceNumber[];
hasCycle: boolean;
/** 收敛方式:归位(气止得位)/ 闭环(互飞成环)/ 入中宫(气归本质)/ 未收敛 */
endReason?: 'guiwei' | 'cycle' | 'center' | 'open';
summary: string;
}
export interface DivinationRequest {
question: string;
method: 'four' | 'time' | 'manual';
tianDiNums?: [number, number, number, number];
solarDate?: string;
manualBenUpper?: Trigram;
manualBenLower?: Trigram;
manualZhiUpper?: Trigram;
manualZhiLower?: Trigram;
movingYao?: number;
}
+20
View File
@@ -0,0 +1,20 @@
-- 0001_init.sql
-- 卦例表(Cloudflare D1 / SQLite)
-- 约定:所有时间用 ISO-8601 字符串;JSON 以 TEXT 存储。
-- 说明:后台(settings / llm_profiles / admin_audit)已下线,
-- 大模型配置改由用户自带、只存在本机浏览器,服务端不落库。
CREATE TABLE IF NOT EXISTS cases (
id TEXT PRIMARY KEY,
owner_id TEXT NOT NULL DEFAULT 'local',
kind TEXT NOT NULL,
created_at TEXT NOT NULL,
time_input TEXT NOT NULL,
question TEXT NOT NULL DEFAULT '',
gender TEXT,
input_json TEXT NOT NULL,
summary_json TEXT NOT NULL,
favorite INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_cases_owner_created ON cases (owner_id, created_at DESC);
+7
View File
@@ -9,6 +9,7 @@
"version": "0.1.0",
"dependencies": {
"@vinext/cloudflare": "^1.3.3",
"html-to-image": "^1.11.13",
"lucide-react": "^1.40.0",
"lunar-javascript": "^1.7.7",
"next": "16.3.0",
@@ -2993,6 +2994,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/html-to-image": {
"version": "1.11.13",
"resolved": "https://registry.npmjs.org/html-to-image/-/html-to-image-1.11.13.tgz",
"integrity": "sha512-cuOPoI7WApyhBElTTb9oqsawRvZ0rHhaHwghRLlTuffoD1B2aDemlCruLeZrUIIdvG7gs9xeELEPm6PhuASqrg==",
"license": "MIT"
},
"node_modules/ipaddr.js": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz",
+10 -4
View File
@@ -10,13 +10,19 @@
"test": "vitest run",
"dev:bg": "node scripts/dev-bg.mjs",
"check:portability": "node scripts/check-portability.mjs",
"dev:vinext": "vite dev --port 3001",
"build:vinext": "vite build",
"start:vinext": "vite preview",
"deploy:vinext": "vinext-cloudflare deploy"
"dev:vinext": "node scripts/vinext.mjs dev --port 3001 --strictPort",
"build:vinext": "node scripts/vinext.mjs build",
"start:vinext": "node scripts/vinext.mjs preview",
"deploy:vinext": "vinext-cloudflare deploy",
"gen:schema": "node scripts/gen-db-schema.mjs",
"check:schema": "node scripts/gen-db-schema.mjs --check",
"check": "npm run check:schema && npm run check:prompt && npm run check:portability && npm test",
"gen:prompt": "node scripts/build-prompt-spec.mjs",
"check:prompt": "node scripts/build-prompt-spec.mjs --check"
},
"dependencies": {
"@vinext/cloudflare": "^1.3.3",
"html-to-image": "^1.11.13",
"lucide-react": "^1.40.0",
"lunar-javascript": "^1.7.7",
"next": "16.3.0",
File diff suppressed because it is too large Load Diff
+93
View File
@@ -0,0 +1,93 @@
Copyright 2018 The Ma Shan Zheng Project Authors (https://github.com/googlefonts/mashanzheng)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

+118
View File
@@ -0,0 +1,118 @@
/* 野鹤六爻 · Service Worker
* ==========================
* 目标只有一个:装到主屏后,起卦与排盘能离线跑(这两步全是本地计算)。
*
* 策略:
* - 导航请求:network-first,断网回落缓存里的 `/`(离线壳)
* - 静态资源(/_next/static、/icons、/images、/fonts、/data):cache-first + 后台更新
* - /api/*:一律直连,不缓存(解卦是流式、历史排盘要实时)
* - 其它同源 GET:network-first,失败回落缓存
*
* 版本号改动即触发更新;旧缓存在 activate 时清掉。
*/
const VERSION = 'yehe-v1';
const SHELL = [
'/',
'/examples',
'/cases',
'/manifest.webmanifest',
'/icons/icon-192.png',
'/icons/icon-512.png',
'/icons/apple-touch-icon.png',
];
self.addEventListener('install', (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(VERSION);
// 单个失败不影响整体安装(例如某页临时 500)
await Promise.allSettled(SHELL.map((url) => cache.add(new Request(url, { cache: 'reload' }))));
await self.skipWaiting();
})(),
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
(async () => {
const keys = await caches.keys();
await Promise.all(keys.filter((k) => k !== VERSION).map((k) => caches.delete(k)));
await self.clients.claim();
})(),
);
});
const STATIC_PREFIX = ['/_next/static/', '/icons/', '/images/', '/fonts/', '/data/'];
function isStatic(url) {
return STATIC_PREFIX.some((p) => url.pathname.startsWith(p));
}
self.addEventListener('fetch', (event) => {
const req = event.request;
if (req.method !== 'GET') return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith('/api/')) return; // 接口直连
if (url.pathname === '/sw.js') return;
// 页面导航:先网后缓存
if (req.mode === 'navigate') {
event.respondWith(
(async () => {
try {
const fresh = await fetch(req);
const cache = await caches.open(VERSION);
cache.put(req, fresh.clone()).catch(() => {});
return fresh;
} catch {
const cache = await caches.open(VERSION);
const hit = (await cache.match(req)) || (await cache.match('/'));
return hit || new Response('离线中,且没有可用的缓存页面。', { status: 503, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
}
})(),
);
return;
}
// 静态资源:缓存优先,后台补新
if (isStatic(url)) {
event.respondWith(
(async () => {
const cache = await caches.open(VERSION);
const hit = await cache.match(req);
if (hit) {
fetch(req)
.then((fresh) => {
if (fresh.ok) cache.put(req, fresh.clone()).catch(() => {});
})
.catch(() => {});
return hit;
}
try {
const fresh = await fetch(req);
if (fresh.ok) cache.put(req, fresh.clone()).catch(() => {});
return fresh;
} catch {
return new Response('', { status: 504 });
}
})(),
);
return;
}
// 其它:先网后缓存
event.respondWith(
(async () => {
try {
return await fetch(req);
} catch {
const cache = await caches.open(VERSION);
const hit = await cache.match(req);
return hit || new Response('', { status: 504 });
}
})(),
);
});
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env node
/**
* 把完整断卦规范(docs/prompt-liuyao.md)内联成 TS 模块。
*
* node scripts/build-prompt-spec.mjs # 生成
* node scripts/build-prompt-spec.mjs --check # 只校验是否最新(CI 用)
*
* 为什么内联:Workers 没有 fs,读不到仓库里的 md。
* 为什么拆章:整份 5.4 万字(≈36k token)每次全发,网关满载时容易被拒(429/prefill_cap_refused),
* 且首字要 9–10 秒。拆成"章 + 输出清单"后可按问句只发「核心章 + 命中的专项章」,
* **内容一字不改**(整章原样搬运),只是发送策略变化。
*/
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const src = path.join(root, 'docs', 'prompt-liuyao.md');
const out = path.join(root, 'lib', 'readings', 'prompt-spec.generated.ts');
const text = fs.readFileSync(src, 'utf8').replace(/\r\n/g, '\n');
// ---- 按 `# 零、…` 这种一级标题切章 ----
const heads = [...text.matchAll(/^# ([零一二三四五六七八九十]+)、(.+)$/gm)];
const chapters = {};
for (let i = 0; i < heads.length; i += 1) {
const start = heads[i].index;
const end = i + 1 < heads.length ? heads[i + 1].index : text.length;
chapters[heads[i][1]] = text.slice(start, end).trimEnd();
}
const preface = text.slice(0, heads[0]?.index ?? 0).trimEnd();
// ---- 把「输出格式」章再拆成 头部 + A~J(章号随文档顺延,动态识别) ----
const outputChapterId = Object.entries(chapters).find(([, v]) => v.includes('## A. 通用人事占'))?.[0] ?? '';
const ch17 = chapters[outputChapterId] ?? '';
const fmtHeads = [...ch17.matchAll(/^## ([A-J])\. (.+)$/gm)];
const outputHead = fmtHeads.length ? ch17.slice(0, fmtHeads[0].index).trimEnd() : ch17;
const formats = {};
for (let i = 0; i < fmtHeads.length; i += 1) {
const start = fmtHeads[i].index;
const end = i + 1 < fmtHeads.length ? fmtHeads[i + 1].index : ch17.length;
formats[fmtHeads[i][1]] = ch17.slice(start, end).trimEnd();
}
const q = (s) => JSON.stringify(s);
const body = `/* 由 scripts/build-prompt-spec.mjs 生成,请勿手改。
* 事实源:docs/prompt-liuyao.md(整章原样搬运,未做任何改写)
*/
/** 完整规范(原版全文,${text.length} 字):给"详版/外部 Agent"投放用 */
export const PROMPT_SPEC = ${q(text)};
/** 前言(版本与投放说明,运行时不发) */
export const SPEC_PREFACE = ${q(preface)};
/** 按章切开(零 / 一 / … / 二十二),内容与原文逐字一致 */
export const SPEC_CHAPTERS: Record<string, string> = {
${Object.entries(chapters).map(([k, v]) => ` ${q(k)}: ${q(v)},`).join('\n')}
};
/** §十七 的头部(四层输出 + 四段模板与字数预算) */
export const OUTPUT_HEAD = ${q(outputHead)};
/** §十七 里的 A~I 输出清单(按专项取用) */
export const OUTPUT_FORMATS: Record<string, string> = {
${Object.entries(formats).map(([k, v]) => ` ${q(k)}: ${q(v)},`).join('\n')}
};
/** 「输出格式」所在章号(运行时用它的头部 + 选中清单替换整章) */
export const OUTPUT_CHAPTER_ID = ${q(Object.entries(chapters).find(([, v]) => v.includes('## A. 通用人事占'))?.[0] ?? '')};
/** 核心章列表(仅文档完整性校验用;运行时发全量) */
export const CORE_CHAPTER_IDS = ${q(['零', '一', '二', '三', '四', '五', '六', '十六', '十七', '十八', '十九', '二十', '二十一'])};
/** 专项 → 输出清单的对应表(文档完整性校验用;运行时已改为全量发送,不再选章) */
export const CHAPTER_FORMAT_MAP: Record<string, string> = ${q({ 七: 'B', 八: 'C', 九: 'D', 十: 'E', 十一: 'F', 十二: 'G', 十三: 'H', 十四: 'I', 十五: 'J' })};
`;
if (process.argv.includes('--check')) {
const cur = fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : '';
if (cur !== body) {
console.error('[check:prompt] lib/readings/prompt-spec.generated.ts 与 docs/prompt-liuyao.md 不一致,请运行 npm run gen:prompt');
process.exit(1);
}
console.log(`[check:prompt] OK(${text.length} 字 / ${Object.keys(chapters).length} 章 / ${Object.keys(formats).length} 个输出清单,与规范一致)`);
} else {
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, body, 'utf8');
console.log(
`[gen:prompt] 写入 ${path.relative(root, out)}:${text.length} 字 / ${Object.keys(chapters).length} 章 / ${Object.keys(formats).length} 个输出清单`,
);
}
+17
View File
@@ -76,6 +76,23 @@ if (fs.existsSync(configPath)) {
}
}
// public/ 里的文件名不要带 @:Workers Assets 会把 @2x 重写成 %402x 再 307 回 @2x,
// 线上变成无限重定向(本地 dev 正常,手机 DPR 3 直接裂图)。用 -2x / -3x。
const publicDir = path.join(root, 'public');
const walkAll = (dir) => {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const full = path.join(dir, e.name);
return e.isDirectory() ? walkAll(full) : [full];
});
};
for (const file of walkAll(publicDir)) {
const rel = path.relative(root, file).split(path.sep).join('/');
if (rel.includes('@')) {
issues.push(`${rel} 文件名含 @ —— Workers Assets 会 307 重写成 %40 并循环;改用 -2x / -3x`);
}
}
if (issues.length) {
console.error(`\n[check:portability] 发现 ${issues.length} 处可能阻断 Cloudflare 部署的写法:\n`);
for (const line of issues) console.error(' ✗ ' + line);
+2
View File
@@ -8,6 +8,7 @@
* 日志写 logs/dev.out.log,最后等端口就绪。前台 `npm run dev` 仍然可用。
*/
import { execSync, spawn } from 'node:child_process';
import { loadLocalSecrets } from './load-secrets.mjs';
import fs from 'node:fs';
import net from 'node:net';
import path from 'node:path';
@@ -15,6 +16,7 @@ import process from 'node:process';
import { fileURLToPath } from 'node:url';
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
loadLocalSecrets(projectRoot);
const LOG_DIR = path.join(projectRoot, 'logs');
const LOG_FILE = path.join(LOG_DIR, 'dev.out.log');
const PORT = Number(process.env.PORT || 3000);
+179
View File
@@ -0,0 +1,179 @@
#!/usr/bin/env node
/**
* 从《增删卜易卦例初探》(朱辰彬)整理文本里抽取前 N 例,生成前台「案例」页的数据。
*
* node scripts/extract-zengshan-cases.mjs <源txt> [数量]
*
* 输出:public/data/zengshan-cases.json(静态资源,页面按需 fetch,不进 JS bundle)
*
* 只做结构化:例号 / 古筮知识 / 占问 / 干支旬空 / 本卦变卦 / 原注 / 用神·吉凶·应期要点。
* 原文按长度截断,保留「可读的一小段」,不做改写、不做补全。
*/
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import pkg from 'lunar-javascript';
const { Lunar } = pkg;
/**
* 卦名 → 六爻二进制(初爻在下,与 lib/liuyao/najia.ts 同约定)
* 名字规律:第 1 字是上卦的象(天泽火雷风山水地),第 2 字是下卦的象;
* 八纯卦写成「乾为天」,下卦的象落在第 3 字。
*/
const TRIGRAM_BITS = { 乾: '111', 天: '111', 兑: '110', 泽: '110', 离: '101', 火: '101', 震: '100', 雷: '100', 巽: '011', 风: '011', 坎: '010', 水: '010', 艮: '001', 山: '001', 坤: '000', 地: '000' };
function binaryOfName(name) {
if (!name || name.length < 3) return '';
// 「乾为天」→ 上乾下天;「天风姤」→ 上天下风
const lowerChar = name[1] === '为' ? name[2] : name[1];
const upper = TRIGRAM_BITS[name[0]];
const lower = TRIGRAM_BITS[lowerChar];
if (!upper || !lower) return '';
return lower + upper; // 初→上:先下卦三爻,再上卦三爻
}
/** 本卦/变卦 → 六次投掷(6/7/8/9);同位阴阳相异者即动爻 */
function coinsOf(ben, zhi) {
if (!ben) return [];
const out = [];
for (let i = 0; i < 6; i += 1) {
const b = ben[i] === '1';
const z = zhi ? zhi[i] === '1' : b;
const moving = b !== z;
out.push(b ? (moving ? 9 : 7) : moving ? 6 : 8);
}
return out;
}
/**
* 古例只给「月建 + 日柱」,没有公历年。
* 在近若干年里找同月建、同日柱的一天,作为「对应公历」,让盘面的月建/日辰/旬空与原例一致。
*/
function findSolar(monthBranch, dayGz, fromYear = 1990, toYear = 2026) {
if (!monthBranch || !dayGz) return null;
// 取范围内最早的一次,读起来像「历史日期」,也避免出现未来时间
let hit = null;
const d = new Date(Date.UTC(fromYear, 0, 1, 4, 0, 0));
const end = Date.UTC(toYear, 11, 31, 4, 0, 0);
while (d.getTime() <= end) {
const lunar = Lunar.fromDate(d);
if (!hit && lunar.getMonthInGanZhiExact().slice(-1) === monthBranch && lunar.getDayInGanZhiExact() === dayGz) {
const y = d.getUTCFullYear();
const m = String(d.getUTCMonth() + 1).padStart(2, '0');
const day = String(d.getUTCDate()).padStart(2, '0');
hit = `${y}-${m}-${day}T12:00`;
}
d.setUTCDate(d.getUTCDate() + 1);
}
return hit;
}
const [, , src, countArg] = process.argv;
if (!src) {
console.error('用法:node scripts/extract-zengshan-cases.mjs <源txt> [数量]');
process.exit(1);
}
const LIMIT = Number(countArg || 100);
const raw = fs.readFileSync(src, 'utf8').replace(/\r\n?/g, '\n');
/** 截断:保留语义边界附近的整句,超长才加省略号 */
function clip(text, max) {
const s = text.replace(/\s+/g, ' ').trim();
if (s.length <= max) return s;
const cut = s.slice(0, max);
const stop = Math.max(cut.lastIndexOf('。'), cut.lastIndexOf(';'), cut.lastIndexOf(','));
return (stop > max * 0.6 ? cut.slice(0, stop) : cut).trim() + '…';
}
const parts = raw.split(/^例\s*(\d+)\s+/m);
const cases = [];
for (let i = 1; i < parts.length && cases.length < LIMIT; i += 2) {
const id = Number(parts[i]);
const body = parts[i + 1] ?? '';
const lines = body.split('\n');
const headLine = lines[0] ?? '';
const topic = headLine.includes('古筮知识:')
? clip(headLine.split('古筮知识:')[1] ?? '', 60)
: clip(headLine, 60);
// 占问:「辰月戊申日,占父近病,得“乾之小畜”」
const askLine = lines.find((l) => /得[“"].+?[”"]/.test(l)) ?? '';
const askMatch = askLine.match(/得[“"]([^”"]+)[”"]/);
let question = '';
if (askLine) {
const before = askLine.split(/得[“"]/)[0] ?? '';
question = before.replace(/^[^,,]*[,,]/, '').trim().replace(/[,,、;;::。]+$/, '');
if (!question) question = before.trim();
}
const guaPair = askMatch ? askMatch[1] : '';
const ganzhiLine = lines.find((l) => l.includes('干支:')) ?? '';
const ganzhi = ganzhiLine.replace(/^.*?干支:/, '').replace(/\s+/g, ' ').trim();
const voidMatch = ganzhiLine.match(/旬空:([^))]+)/);
// 卦名:`乾宫:乾为天(六冲)` / `巽宫:风天小畜`
const hexes = [...body.matchAll(/([\u4e00-\u9fa5]{1,2})宫:\s*([\u4e00-\u9fa5]{2,4})\s*(?:[((]([^))]+)[))])?/g)].map((m) => ({
palace: m[1],
name: m[2],
tag: (m[3] || '').trim(),
}));
const noteMatch = body.match(/原注:([\s\S]*?)(?=\n\s*1、|\n\s*【|$)/);
const sec = (n) => {
const re = new RegExp(`${n}、[^:]*:([\\s\\S]*?)(?=\\n\\s*[123]、|$)`);
const m = body.match(re);
return m ? m[1].replace(/\s+/g, ' ').trim() : '';
};
const benBinary = binaryOfName(hexes[0]?.name ?? '');
const zhiBinary = binaryOfName(hexes[1]?.name ?? '');
const coins = coinsOf(benBinary, zhiBinary);
// 「辰月」「乙卯月」都算,只取地支
const monthBranch = (ganzhi.match(/([子丑寅卯辰巳午未申酉戌亥])月/) || [])[1] || '';
const dayGz = (ganzhi.match(/[甲乙丙丁戊己庚辛壬癸][子丑寅卯辰巳午未申酉戌亥]日/) || [''])[0].replace('日', '');
cases.push({
id,
topic,
question: question || '(原文未注明)',
ganzhi: ganzhi.replace(/[((]旬空[^))]*[))]/, '').trim(),
void: (voidMatch?.[1] ?? '').trim(),
guaPair,
ben: hexes[0]?.name ?? '',
benPalace: hexes[0]?.palace ?? '',
benTag: hexes[0]?.tag ?? '',
zhi: hexes[1]?.name ?? '',
zhiPalace: hexes[1]?.palace ?? '',
zhiTag: hexes[1]?.tag ?? '',
note: noteMatch ? noteMatch[1].replace(/\s+/g, ' ').trim() : '',
yong: sec(1),
luck: sec(2),
timing: sec(3),
binary: benBinary && zhiBinary ? `${benBinary}>${zhiBinary}` : benBinary,
coins,
solar: findSolar(monthBranch, dayGz),
});
}
const outDir = path.resolve(process.cwd(), 'public', 'data');
fs.mkdirSync(outDir, { recursive: true });
const outFile = path.join(outDir, 'zengshan-cases.json');
fs.writeFileSync(outFile, JSON.stringify({ source: '《增删卜易卦例初探》朱辰彬', count: cases.length, cases }, null, 1), 'utf8');
const missing = {
coins: cases.filter((c) => c.coins.length !== 6).length,
solar: cases.filter((c) => !c.solar).length,
ben: cases.filter((c) => !c.ben).length,
zhi: cases.filter((c) => !c.zhi).length,
note: cases.filter((c) => !c.note).length,
yong: cases.filter((c) => !c.yong).length,
luck: cases.filter((c) => !c.luck).length,
timing: cases.filter((c) => !c.timing).length,
};
console.log(`[extract] ${cases.length} 例 → ${path.relative(process.cwd(), outFile)}`);
console.log('[extract] 缺字段统计:', JSON.stringify(missing));
console.log('[extract] 首例:', JSON.stringify(cases[0], null, 1).slice(0, 700));
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env node
/**
* 从 migrations/*.sql 生成 lib/db/schema.generated.ts。
*
* 为什么要有这一步:
* - 迁移文件是唯一事实源(可交给 D1 CLI / 人工审阅);
* - 但 Workers 运行时不能读文件,所以把 DDL 内联成常量,供本地自举建表。
*
* node scripts/gen-db-schema.mjs # 生成
* node scripts/gen-db-schema.mjs --check # 只校验是否最新(CI 用)
*/
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const migrationsDir = path.join(root, 'migrations');
const outFile = path.join(root, 'lib', 'db', 'schema.generated.ts');
const files = fs
.readdirSync(migrationsDir)
.filter((f) => f.endsWith('.sql'))
.sort();
const sql = files
.map((f) => `-- >>> ${f}\n${fs.readFileSync(path.join(migrationsDir, f), 'utf8').trim()}`)
.join('\n\n');
// 语句切分:本项目 DDL 不含字符串内的分号,按 ; 切即可(生成时会校验)
const statements = sql
.split('\n')
.filter((line) => !line.trim().startsWith('--'))
.join('\n')
.split(';')
.map((s) => s.trim())
.filter(Boolean);
const body = `/* 由 scripts/gen-db-schema.mjs 生成,请勿手改。
* 事实源:migrations/*.sql
*/
export const SCHEMA_SQL = ${JSON.stringify(sql, null, 2)};
export const SCHEMA_STATEMENTS: readonly string[] = ${JSON.stringify(statements, null, 2)};
`;
const existing = fs.existsSync(outFile) ? fs.readFileSync(outFile, 'utf8') : '';
const changed = existing !== body;
if (process.argv.includes('--check')) {
if (changed) {
console.error('[check:schema] lib/db/schema.generated.ts 与 migrations/*.sql 不一致,请运行 npm run gen:schema');
process.exit(1);
}
console.log('[check:schema] OK');
process.exit(0);
}
fs.writeFileSync(outFile, body, 'utf8');
console.log(`[gen:schema] 写入 ${path.relative(root, outFile)}(${files.length} 个迁移,${statements.length} 条语句)`);
+25
View File
@@ -0,0 +1,25 @@
/**
* 本地密钥加载(Node 侧工具脚本共用)。
*
* 读取项目根目录的 `.llm.local`(已 gitignore),只补齐**尚未设置**的环境变量,
* 不覆盖真实环境变量。格式:KEY=VALUE,支持 # 注释与引号。
*
* 为什么不用 `.env.local`:那个文件归 Next 管;vinext/vite 的配置在 Node 侧执行,
* 需要在启动前把变量放进 process.env,才能被 cloudflare.config.ts 映射成文本绑定。
*/
import fs from 'node:fs';
import path from 'node:path';
export function loadLocalSecrets(projectRoot) {
const file = path.join(projectRoot, '.llm.local');
if (!fs.existsSync(file)) return;
for (const raw of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
const line = raw.trim();
if (!line || line.startsWith('#')) continue;
const idx = line.indexOf('=');
if (idx <= 0) continue;
const key = line.slice(0, idx).trim();
const value = line.slice(idx + 1).trim().replace(/^["']|["']$/g, '');
if (key && !process.env[key]) process.env[key] = value;
}
}

Some files were not shown because too many files have changed in this diff Show More