@tbox.cn/app-template-agent 1.0.0-alpha.8 → 1.0.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/.gitignore +7 -0
  2. package/.tbox/app.json +1 -1
  3. package/.tbox/default-modules.json +1 -1
  4. package/.tbox/factory/chat.json +9 -0
  5. package/.tbox/miniapp-containers.json +1 -1
  6. package/AGENTS.md +4 -2
  7. package/apps/client/package.json +1 -0
  8. package/apps/client/scripts/._color-scan.test.mjs +0 -0
  9. package/apps/client/scripts/._experience-checks.mjs +0 -0
  10. package/apps/client/scripts/._geometry-kernel.test.mjs +0 -0
  11. package/apps/client/scripts/._in-process-checks.mjs +0 -0
  12. package/apps/client/scripts/._probe-checks.mjs +0 -0
  13. package/apps/client/scripts/._sample-entries.test.mjs +0 -0
  14. package/apps/client/scripts/._storyboard.test.mjs +0 -0
  15. package/apps/client/scripts/._theme-kernel.mjs +0 -0
  16. package/apps/client/scripts/._theme-kernel.test.mjs +0 -0
  17. package/apps/client/scripts/acceptance-changes.test.mjs +97 -0
  18. package/apps/client/scripts/check-evidence.mjs +361 -94
  19. package/apps/client/scripts/color-scan.mjs +66 -0
  20. package/apps/client/scripts/color-scan.test.mjs +25 -0
  21. package/apps/client/scripts/evidence-gate.mjs +248 -46
  22. package/apps/client/scripts/evidence-gate.test.mjs +63 -5
  23. package/apps/client/scripts/experience-checks.mjs +163 -0
  24. package/apps/client/scripts/geometry-kernel.test.mjs +92 -0
  25. package/apps/client/scripts/in-process-checks.mjs +51 -0
  26. package/apps/client/scripts/lib/._card-registry.mjs +0 -0
  27. package/apps/client/scripts/lib/._card-registry.test.mjs +0 -0
  28. package/apps/client/scripts/lib/._evidence-inputs.mjs +0 -0
  29. package/apps/client/scripts/lib/._evidence-inputs.test.mjs +0 -0
  30. package/apps/client/scripts/lib/._static-render.mjs +0 -0
  31. package/apps/client/scripts/lib/._static-render.test.mjs +0 -0
  32. package/apps/client/scripts/lib/card-registry.mjs +81 -0
  33. package/apps/client/scripts/lib/card-registry.test.mjs +59 -0
  34. package/apps/client/scripts/lib/evidence-inputs.mjs +91 -0
  35. package/apps/client/scripts/lib/evidence-inputs.test.mjs +27 -0
  36. package/apps/client/scripts/lib/static-render.mjs +35 -0
  37. package/apps/client/scripts/lib/static-render.test.mjs +21 -0
  38. package/apps/client/scripts/probe-checks.mjs +85 -0
  39. package/apps/client/scripts/render-card.mjs +76 -60
  40. package/apps/client/scripts/sample-entries.test.mjs +31 -0
  41. package/apps/client/scripts/storyboard.test.mjs +149 -0
  42. package/apps/client/scripts/surface-css.mjs +5 -2
  43. package/apps/client/scripts/theme-kernel.mjs +236 -0
  44. package/apps/client/scripts/theme-kernel.test.mjs +136 -0
  45. package/apps/client/src/styles/brand.css +11 -11
  46. package/apps/client/src/styles/tailwind.css +3 -4
  47. package/apps/client/vite.config.ts +2 -1
  48. package/apps/server/scripts/probe.mjs +6 -1
  49. package/apps/server/scripts/scenario-lib.mjs +54 -7
  50. package/apps/server/scripts/scenario.mjs +41 -7
  51. package/config/AGENTS.md +1 -0
  52. package/config/chat.json +21 -9
  53. package/docs/agent/card.md +1 -0
  54. package/docs/agent/kit.md +1 -1
  55. package/docs/agent/shell.md +1 -0
  56. package/docs/agent/style.md +3 -1
  57. package/docs/agent/verify.md +37 -8
  58. package/package.json +9 -6
  59. package/packages/agent-ui-kit/README.md +21 -1
  60. package/packages/agent-ui-kit/catalog.json +1 -1
  61. package/packages/agent-ui-kit/package.json +9 -1
  62. package/packages/agent-ui-kit/src/ChatPage.tsx +30 -1
  63. package/packages/agent-ui-kit/src/card/primitives.test.tsx +10 -0
  64. package/packages/agent-ui-kit/src/card/primitives.tsx +14 -10
  65. package/packages/agent-ui-kit/src/card/view-card.tsx +6 -1
  66. package/packages/agent-ui-kit/src/chat-config.ts +11 -7
  67. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.test.tsx +3 -0
  68. package/packages/agent-ui-kit/src/components/ActionBar/DebugButton.tsx +2 -7
  69. package/packages/agent-ui-kit/src/components/BottomSheet/._index.test.tsx +0 -0
  70. package/packages/agent-ui-kit/src/components/BottomSheet/._index.tsx +0 -0
  71. package/packages/agent-ui-kit/src/components/BottomSheet/index.test.tsx +90 -0
  72. package/packages/agent-ui-kit/src/components/BottomSheet/index.tsx +129 -0
  73. package/packages/agent-ui-kit/src/components/ChatInput/index.test.tsx +2 -2
  74. package/packages/agent-ui-kit/src/components/ChatInput/index.tsx +21 -16
  75. package/packages/agent-ui-kit/src/components/HistoryEntry/index.tsx +1 -0
  76. package/packages/agent-ui-kit/src/components/QuickCommands/index.tsx +2 -2
  77. package/packages/agent-ui-kit/src/components/ScrollToBottomButton/index.tsx +7 -3
  78. package/packages/agent-ui-kit/src/components/ToolCallBlock/index.tsx +4 -2
  79. package/packages/agent-ui-kit/src/index.ts +4 -0
  80. package/packages/agent-ui-kit/src/shell.contract.json +9 -0
  81. package/packages/agent-ui-kit/src/shell.test.ts +10 -0
  82. package/packages/agent-ui-kit/src/shell.ts +15 -0
  83. package/packages/agent-ui-kit/src/theme/contract.json +78 -1
  84. package/packages/agent-ui-kit/src/theme/theme-contract.test.ts +16 -0
  85. package/packages/agent-ui-kit/src/theme/tokens.css +1 -1
  86. package/pnpm-lock.template.yaml +97 -91
  87. package/pnpm-workspace.template.yaml +10 -10
  88. package/profiles/mall/._chat.overrides.json +0 -0
  89. package/profiles/mall/chat.overrides.json +12 -0
  90. package/profiles/mall/config/chat.json +14 -6
  91. package/profiles/mall.json +1 -1
  92. package/scripts/._deliver.mjs +0 -0
  93. package/scripts/._shell-probe.mjs +0 -0
  94. package/scripts/._storyboard.mjs +0 -0
  95. package/scripts/check-fast.mjs +1 -0
  96. package/scripts/checks.json +294 -17
  97. package/scripts/deliver.mjs +183 -0
  98. package/scripts/lib/._chrome-pipe.mjs +0 -0
  99. package/scripts/lib/._geometry-kernel.mjs +0 -0
  100. package/scripts/lib/chrome-pipe.mjs +95 -0
  101. package/scripts/lib/geometry-kernel.mjs +137 -0
  102. package/scripts/shell-probe.mjs +283 -0
  103. package/scripts/storyboard.mjs +350 -0
  104. package/profiles/mall/config/llm_provider.json +0 -5
  105. package/profiles/mall/config/plugins.json +0 -3
  106. package/scripts/gen-tailwind-sources.mjs +0 -55
  107. /package/{profiles/mall/config/._llm_provider.json → .tbox/factory/._chat.json} +0 -0
  108. /package/{profiles/mall/config/._plugins.json → apps/client/scripts/._acceptance-changes.test.mjs} +0 -0
  109. /package/{scripts/._gen-tailwind-sources.mjs → apps/client/scripts/._color-scan.mjs} +0 -0
package/config/chat.json CHANGED
@@ -1,17 +1,29 @@
1
1
  {
2
- "enableImageUpload": true,
3
- "enableVideoUpload": true,
4
- "enableTTS": true,
5
- "enableVoiceInput": true,
6
- "defaultInputMode": "TEXT",
2
+ "identity": {
3
+ "name": "悦享里",
4
+ "tagline": "商圈智能服务"
5
+ },
6
+ "welcome": {
7
+ "title": "今天想逛点什么?",
8
+ "subtitle": "停车、入会、积分、商户、导航、活动和优惠券都能问我"
9
+ },
10
+ "retryOnError": true,
7
11
  "quickCommands": [
8
12
  {
9
- "label": "你能做什么",
10
- "query": "你能帮我做什么?"
13
+ "label": "停车缴费",
14
+ "query": "我要停车缴费"
11
15
  },
12
16
  {
13
- "label": "开始对话",
14
- "query": "你好"
17
+ "label": "碰一下入会",
18
+ "query": "我要碰一下入会"
19
+ },
20
+ {
21
+ "label": "推荐一家餐厅",
22
+ "query": "推荐一家餐厅"
23
+ },
24
+ {
25
+ "label": "今天有什么活动",
26
+ "query": "今天有什么活动"
15
27
  }
16
28
  ]
17
29
  }
@@ -35,6 +35,7 @@ export const card = defineViewCard<ParkingOrder>({
35
35
  ```
36
36
 
37
37
  - 积木:`hero` / `facts` / `bill` / `notice` / `tags` / `steps` / `list` / `ticket` / `timeline` / `empty`;动作规格与 `ActionList` 同形(label / send / invoke / confirm / style)。
38
+ - `hero` 的 `tone`:`primary`(缺省)/ `warm` / `jade` / `inverse`。**要深色主视觉(金额、路线、会员等级)用 `inverse`**——它用 `--tbox-primary-dark` 底 + `--tbox-primary-light` 字,对比度由门禁 `shell.contrast` 兜底;不要为了深色底去写 `bg-[#173F33]` 这类字面量(`style.color-repeat` 会点名)。
38
39
  - 预算写进 schema:积木 ≤4、提示 ≤1、属性 ≤5、列表 ≤3、账单行 ≤8、步骤 ≤5、时间线 ≤6、标签 ≤6、卡级动作 ≤2;作者期 `defineViewCard` 直接报错,生产侧 `cardOfView` 先截断再校验,不整张卡丢弃。
39
40
  - 样例由 `sampleState` 与 `samples` 派生,不用手写大段 `sampleData`。
40
41
  - 出卡用 `cardOfView(card, domainData, note)`:它先跑 `view()`,再走统一的出卡校验。
package/docs/agent/kit.md CHANGED
@@ -28,7 +28,7 @@ import { Card, CardHeader, KeyValueList, StatusTag } from '@tbox.cn/app-agent-ui
28
28
  | `Ticket` | 票券形:券、凭证、卡包条目。 | `amount: ReactNode` `condition?: ReactNode` `meta?: ReactNode` `status?: ReactNode` `tone?: 'primary' \| 'muted'` |
29
29
  | `Steps` | 步骤/路线:取车路线、办理进度。 | `steps: StepItem[]` |
30
30
  | `MediaRow` | 图文条目:门店、商品、活动。 | `title: ReactNode` `meta?: ReactNode` `tags?: ReactNode` `action?: ReactNode` `thumb?: ReactNode` |
31
- | `Hero` | 品牌色块:主数值 + 说明,用于会员、积分、钱包类卡片的头部。 | `eyebrow?: ReactNode` `title: ReactNode` `value?: ReactNode` `unit?: ReactNode` `footnote?: ReactNode` `icon?: ReactNode` `tone?: 'primary' \| 'warm' \| 'jade' \| 'neutral'` |
31
+ | `Hero` | 品牌色块:主数值 + 说明,用于会员、积分、钱包类卡片的头部。 | `eyebrow?: ReactNode` `title: ReactNode` `value?: ReactNode` `unit?: ReactNode` `footnote?: ReactNode` `icon?: ReactNode` `tone?: 'primary' \| 'warm' \| 'jade' \| 'inverse' \| 'neutral'` |
32
32
  | `StatGrid` | 并列数值格(两到三格):积分/余额、车位/时长。 | `items: StatItem[]` |
33
33
  | `EntityRow` | 实体行(MediaRow 的超集):商户、活动、券包条目,支持价格与展开说明。 | `title: ReactNode` `meta?: ReactNode` `tags?: ReactNode` `price?: ReactNode` `action?: ReactNode` `thumb?: ReactNode` `description?: ReactNode` |
34
34
  | `CheckRow` | 勾选行:用券、同意条款、选择车位。 | `label: ReactNode` `description?: ReactNode` `checked: boolean` `onChange?: (checked: boolean) => void` `disabled?: boolean` `trailing?: ReactNode` |
@@ -40,6 +40,7 @@ export default function Index() {
40
40
  | 空会话欢迎区 | `config/chat.json` 的 `welcome.title` / `welcome.subtitle` |
41
41
  | 快捷问题 | `config/chat.json` 的 `quickCommands`(见 [agent-prompt](agent-prompt.md)) |
42
42
  | 出错重试 | `config/chat.json` 的 `retryOnError`(缺省 true):错误气泡上给「重试」,重发上一条用户消息 |
43
+ | 出厂能力开关 | 语音输入/播报、图片/视频上传缺省开启;`chat.json` 不写这些键。只有用户明确要求时才写 `false`——门禁会把它记为「偏离出厂」并要求写明依据 |
43
44
  | 首屏整体替换 | `slots.home`:注册一个渲染函数,替换主屏内容 |
44
45
  | 对话标题 | `apps/client/src/pages/page.tsx` 的 `page.title` |
45
46
  | 外观(颜色、圆角、底色) | `apps/client/src/styles/brand.css` 覆写 `--tbox-*` 变量,见 [style](style.md) |
@@ -14,6 +14,7 @@
14
14
  ```
15
15
 
16
16
  - 顺序不变:先用 kit 基元;基元表达不了的布局,用工具类包一层 `div`。
17
+ - 模块源码由宿主构建链自动登记(以模块 `src/client/index.ts` 为客户端入口);不要手动往 `tailwind.css` 写模块 `@source`。
17
18
  - 类名必须是**完整字面量**——构建期扫源码生成 CSS,`bg-${tone}` 这种拼出来的类不会生成,页面上看到的是「没有样式」而不是报错。
18
19
  - 模板里拼完类名要留一个空格再开插值:`text-xs${cond ? … : …}` 会让扫描器丢掉整条 `text-xs`(`check:fast` 会拦)。
19
20
  - 动态状态只能写成「整串字面量的三元」或「按状态键取的映射表」,两种都是完整类名:
@@ -43,7 +44,8 @@ const TONE = { ok: 'bg-success-soft text-success', warn: 'bg-warning-soft text-w
43
44
  | 描边 | `border-border` `border-border-strong` `border-warn-border` `border-danger-border` |
44
45
  | 主色上的字 | `text-white` `text-primary-foreground` |
45
46
 
46
- - 一次性色值用任意值:`bg-[#fff8e9]`、`text-[#0a6eb8]`、`shadow-[0_2px_16px_rgba(106,119,137,0.08)]`。同一个色值出现在三处以上,说明它该进契约而不是继续复制。
47
+ - 一次性色值用任意值:`bg-[#fff8e9]`、`text-[#0a6eb8]`、`shadow-[0_2px_16px_rgba(106,119,137,0.08)]`。同一个色值出现在三处以上,说明它该进契约而不是继续复制——这条由 `style.color-repeat`(warning)兜住,会点名重复的色值与最像的令牌。
48
+ - 想改配色先跑 `pnpm exec tbox-app theme check`(逐对对比度),不达标用 `theme tune --write`(只调亮度、色相不动),新品牌从种子派生用 `theme derive --seed <hex>`。三个命令只写 `brand.css` 的 `@tbox:tokens-begin/end` 标记区。
47
49
  - 半透明写带 alpha 的任意值:`bg-[rgba(11,15,23,0.02)]`。
48
50
  - 禁用:默认调色板(`bg-red-500` 不生成)、透明度修饰符(`bg-primary/50` 依赖 `color-mix`,旧内核回落为不透明)、`!` 重要性(只在覆写无层的旧规则时用,写在变体尾部如 `rounded-none!`)。
49
51
  - 未知类不会报错、只是不生效;上面这几类禁用项由 `check:fast` 的证据包直接判错(`palette-color` / `color-opacity-modifier` / `font-size-off-scale` / `element-asset-declaration`)。
@@ -30,8 +30,8 @@
30
30
  "warnings": [{ "id": "card-sample-coverage", "message": "parking-card.status 的状态 [\"paid\"] 没有样例" }],
31
31
  "verdict": "deliverable",
32
32
  "acceptance": { "items": 3, "covered": 3, "handoff": 0, "uncovered": [] },
33
- "policy": "static",
34
- "coverage": { "logic": "已验证:2 个场景 / 12 步 / 3 项", "visual": "未运行:当前策略 static" },
33
+ "policy": "visual",
34
+ "coverage": { "logic": "已验证:2 个场景 / 12 步 / 3 项", "visual": "未运行:本轮未执行浏览器" },
35
35
  "handoff": [],
36
36
  "next": "交付条件已满足:总结并结束。不要继续复审或打磨。",
37
37
  "notRun": [] }
@@ -48,13 +48,16 @@
48
48
 
49
49
  ```jsonc
50
50
  {
51
- // 证据策略:本任务允许验到哪一级(static / visual / flow);缺省 static
52
- "policy": "static",
51
+ // 证据策略:本任务允许验到哪一级(static / visual / flow);缺省 visual
52
+ // 降为 static 必须写 policyReason(用户原话);平台可用 TBOX_POLICY 注入
53
+ "policy": "visual",
53
54
  "items": [
54
55
  { "id": "join.reward", "text": "入会后获得 100 积分和一张满100减20券" },
55
56
  { "id": "parking.pay", "text": "用停车券抵 10 元,实付 5 元,得 5 积分" },
56
- { "id": "ui.mobile", "text": "移动端为主,其它尺寸可用", "by": "handoff",
57
- "reason": "当前任务要求快速交付,不起浏览器" }
57
+ { "id": "ui.mobile", "text": "移动端为主,卡片与输入区不溢出", "by": "storyboard",
58
+ "frames": ["card:*@320", "shell.empty@320"] },
59
+ { "id": "ui.brand", "text": "视觉符合商圈氛围", "by": "handoff",
60
+ "reason": "主观判断,机器只能证明它渲染出来了,不能证明好看" }
58
61
  ]
59
62
  }
60
63
  ```
@@ -65,6 +68,10 @@
65
68
  - `by: "handoff"`(旧名 `review` 仍可用)表示**当前策略下验不了**,必须写 `reason`;门禁把它列进 `handoff`,
66
69
  并在 `next` 里要求原样写进交付说明——它不再是一个「待复审」的邀请;
67
70
  - 能由场景判定却标 `handoff` 的项(缺 `reason`)计入 `incomplete`,不能用来绕过覆盖;
71
+ - `by: "storyboard"` 表示界面项由故事板证明:`frames` 列的帧(`pnpm storyboard` 出图,`pnpm deliver` 会自动跑)全部生成且没有几何错误才算覆盖,
72
+ 计数单列在 `acceptance.storyboard`,不与场景覆盖混算;任一帧溢出或渲染失败则该项按未覆盖处理。
73
+ 主观项(「符合氛围」「好看」)只能写 `handoff`——故事板不判美丑;
74
+ - 故事板判据的阈值与 id 见 [checks 报错表](verify.md) 与 `scripts/checks.json` 的 `frames`/`threshold`:`card.overflow-x`(error)、`card.text-clip`/`card.tap-target`/`card.min-font`(warning)、`storyboard.render`(error);
68
75
  - 场景里可写 `expect.state`(对登记状态做子集匹配)验证需求里写明的不变量,例如 `{ "member": true, "points": 100 }`;
69
76
  - 场景缺省按文件隔离用户,需要共享时在场景顶层写 `user`。
70
77
 
@@ -79,7 +86,11 @@
79
86
  | `reopened` | 交付后源码内容又变了 | 重跑确认;只降级一次,不阻断 |
80
87
 
81
88
  摘要里的 `coverage` 给每个维度一个状态(结构 / 逻辑 / 渲染 / 视觉 / 模型路由),`handoff` 是当前策略
82
- 验不了的清单。视觉与模型级验收只在 `policy` 允许时运行;`static` 下它们明确写「未运行」,不留作疑问。
89
+ 验不了的清单。档位缺省 `visual`(静态 + 布局车道);应用把档位降到 `static` 必须写 `policyReason`(用户原话),否则门禁按 `visual` 执行并告警。平台可用 `TBOX_POLICY` 注入档位。
90
+
91
+ 交付用 `pnpm deliver`:它跑 `check:fast`,输出裁决、未运行项、偏离出厂与验收变更,并生成 `DELIVERY.md`;摘要固定给一行「视觉证据:.tbox/evidence/storyboard.png(N 帧,几何问题 k 个)」。`pnpm verify` 只在发布前由人/CI 跑。
92
+
93
+ `pnpm storyboard`:把壳与每张卡的样例在 390 / 320 两个宽度排成一页长图并同时量几何(溢出、截断、点击区、字号)。源文件没变时命中缓存(<2s);没有 Chrome 记 not-run;帧数超预算时截断并注明。看图即可判断「界面到底长什么样」,不需要起 dev server。
83
94
  已经 `deliverable` 之后再跑,`sinceDeliverable` 给出其后的门禁次数与改动文件数;源码内容再变会得到 `reopened`(内容哈希),同一份内容再跑一次恢复 `deliverable`。
84
95
 
85
96
  摘要里的 `delivery` 是交付包:`trace` 逐项覆盖、`facts` 视图卡高度、`drift` 验收/期望漂移、`deferred` 浏览器/模型/未接项。交付时把 `deferred` 原样写进说明。
@@ -129,7 +140,7 @@ pnpm exec tbox-app probe "query-points{}" --user u1 --save points-baseline
129
140
  | `boot.inline-script`(错误) | 入口 HTML 有内联脚本(解析期执行,body 可能还是 null) | 删掉内联脚本;启动逻辑放打包后的模块里([verify](verify.md)) |
130
141
  | `shell.identity`(错误) | 发送者名写死「AI 助手」,已配置的身份没用上 | 从 chat.json identity.name 取,缺省再回落([shell](shell.md)) |
131
142
  | `shell.type-scale`(错误) | 写了档外字号(text-[13px] 之类) | 用 12/14/16/18/20/24/30/36 档:正文 16、卡片正文 14、说明 12([style](style.md)) |
132
- | `css.sentinel`(错误) | 证据 CSS 为空或不完整(样式管线断了) | 确认 tailwind.css 与 @source;证据与 dev/build 共用 surface-css.mjs([style](style.md)) |
143
+ | `css.sentinel`(错误) | 证据 CSS 为空、缺模块源码或模块类未生成 | 确认 `vite.config.ts` 的 `tboxModuleSourcesPlugin` 在 `tailwindcss()` 之前;证据与 dev/build 共用 app-build 的 `collectModuleSourceDirs`([style](style.md)) |
133
144
  | `card.states`(错误) | 卡片历史态渲染失败或为空 | 用 isHistory 只禁用动作,不隐藏内容([card](card.md)) |
134
145
  | `shell.hit-target`(错误) | 可交互元素命中区小于 44px | 用 kit 按钮与 min-h-11;视觉尺寸可小,命中区要足([shell](shell.md)) |
135
146
  | `shell.quick-visible`(错误) | 空态快捷问题没有全部可见(横向溢出或贴底) | 空态用两列 grid,对话态才用单行([shell](shell.md)) |
@@ -138,6 +149,24 @@ pnpm exec tbox-app probe "query-points{}" --user u1 --save points-baseline
138
149
  | `shell.blank`(错误) | 内容块之间空白过大(看起来没做完) | 空态成组居中、补服务入口;只算块间空白,不算首尾对称留白([shell](shell.md)) |
139
150
  | `card.height`(错误) | 视图卡过高(一屏放不下) | 按预算减积木或拆卡;详情用单独的卡承接([card](card.md)) |
140
151
  | `CARD_TYPE_INVALID`(错误) | 卡片类型含路径分隔符或非法字符 | 改成小写 kebab(字母/数字/点/下划线/中划线),不要用 ../ 或斜杠([card](card.md)) |
152
+ | `shell.icon-render`(错误) | 快捷问题图标不可见(遮罩失效或节点被隐藏) | 修正 maskImage 引号或改用可见元素;应用自绘图标时保证按钮内有可见内容([shell](shell.md)) |
153
+ | `shell.controls-semantic`(错误) | 核心控件不是 button/a(键盘与读屏不可用) | 用 button + aria-label + focus-visible;保留原类名([shell](shell.md)) |
154
+ | `shell.control-present`(错误) | 能力开启但对应控件不可见 | 按能力配置渲染控件;关闭能力时才隐藏([shell](shell.md)) |
155
+ | `shell.a11y-name`(错误) | 控件缺可访问名 | aria-label 或可见文本([shell](shell.md)) |
156
+ | `meta.brand`(告警) | 页面标题/主题色未跟品牌 | 由 identity 注入 title 与 theme-color([shell](shell.md)) |
157
+ | `quick.label-query`(告警) | 快捷问题按钮文案与发送文本不一致 | query 缺省等于 label,或让 query 包含 label([shell](shell.md)) |
158
+ | `card.action-primary`(告警) | 卡片动作无主次 | 第一个动作 primary,其余 secondary([card](card.md)) |
159
+ | `kit.color-literal`(告警) | kit 样式里出现令牌之外的颜色字面量 | 改用主题令牌(标签色随主色派生)([style](style.md)) |
160
+ | `style.url-quoted`(告警) | 样式里的 url() 未加引号,data URI 会被 CSSOM 拒绝 | 写 url("…")([style](style.md)) |
161
+ | `checks.registry`(错误) | checks.json 登记了门禁未实现的检查项 | 补实现或删登记;sync-check-docs 会同步报错表([verify](verify.md)) |
162
+ | `shell.turn-visible`(错误) | 新回合把问题顶出视口,用户看不到自己在问什么 | 修回合锚定与浮标;不要用定时器追底([shell](shell.md)) |
163
+ | `shell.console-clean`(错误) | 水合时控制台出现告警/错误(重复注册、未知属性、SSR 警告) | 按告警修源头;不要静音 console([shell](shell.md)) |
164
+ | `storyboard.render`(错误) | 故事板渲染失败(帧没跑完) | 看 storyboard.json 的 reason;多为样例数据不合 schema 或 Chrome 未就绪([verify](verify.md)) |
165
+ | `card.overflow-x`(错误) | 卡片在窄屏横向溢出 | 去掉定宽;长文本允许换行(break-words),图片用 max-w-full([card](card.md)) |
166
+ | `card.text-clip`(告警) | 文本被容器截断且没有省略号 | 加 truncate(省略号)或允许换行;数字与金额不要截断([card](card.md)) |
167
+ | `card.tap-target`(告警) | 卡片上的按钮点击区小于 44px | 用 kit Button;视觉尺寸小时给外层留 min-h-11([card](card.md)) |
168
+ | `card.min-font`(告警) | 卡片里有小于 12px 的文字 | 用 text-xs 及以上;次要信息降级不如减少信息([card](card.md)) |
169
+ | `style.color-repeat`(告警) | 同一色值在卡片/组件里出现 3 次以上(该进令牌) | 换成语义类;确需新色就写进 brand.css 的令牌,再用 bg-[var(--tbox-*)] 或语义类([style](style.md)) |
141
170
  <!-- check-docs:errors end -->
142
171
 
143
172
  ## 用户说「不要测试」时
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-template-agent",
3
- "version": "1.0.0-alpha.8",
3
+ "version": "1.0.0-alpha.9",
4
4
  "description": "tbox AI Agent 全栈模板(多包 pnpm workspace):apps/client + apps/server。唯一模板(W4 单一模板统一化:缺省带 AI 支付体验的 chat 形态;mall 能力经 profiles/mall 加装),能力经 CLI module add 模块扩展(shopping-guide/member 等)。",
5
5
  "engines": {
6
6
  "node": ">=24.0.0 <25.0.0"
@@ -48,9 +48,9 @@
48
48
  "typescript-eslint": "8.67.0",
49
49
  "eslint-plugin-react-hooks": "5.2.0",
50
50
  "vite": "6.4.3",
51
- "@tbox.cn/app-sdk-server": "1.0.0-alpha.8",
52
- "@tbox.cn/app-build": "1.0.0-alpha.8",
53
- "@tbox.cn/app-cli": "1.0.0-alpha.8"
51
+ "@tbox.cn/app-sdk-server": "1.0.0-alpha.9",
52
+ "@tbox.cn/app-build": "1.0.0-alpha.9",
53
+ "@tbox.cn/app-cli": "1.0.0-alpha.9"
54
54
  },
55
55
  "license": "MIT",
56
56
  "publishConfig": {
@@ -64,7 +64,7 @@
64
64
  "scripts": {
65
65
  "dev": "pnpm --filter ./apps/server dev",
66
66
  "dev-alipay": "node scripts/dev-alipay.mjs",
67
- "generate": "node scripts/gen-tailwind-sources.mjs && node scripts/generate.mjs",
67
+ "generate": "node scripts/generate.mjs",
68
68
  "build": "pnpm check && pnpm generate && pnpm --filter ./apps/server build && pnpm --filter ./apps/client build && node scripts/check-css-target.mjs",
69
69
  "build:client": "pnpm check && pnpm generate && pnpm --filter ./apps/client build",
70
70
  "typecheck": "pnpm generate && pnpm -r --filter \"./{apps,packages,modules}/*\" typecheck",
@@ -76,12 +76,15 @@
76
76
  "verify:generated": "node scripts/verify-generated.mjs",
77
77
  "check": "pnpm check:workspace && pnpm check:inspector",
78
78
  "check:fast": "node scripts/check-fast.mjs",
79
+ "deliver": "node scripts/deliver.mjs",
80
+ "probe:shell": "node scripts/shell-probe.mjs",
79
81
  "check:css": "node scripts/check-css-target.mjs",
80
82
  "scenario": "pnpm --filter ./apps/server exec node --import tsx scripts/scenario.mjs",
81
83
  "card:render": "pnpm --filter ./apps/client exec node scripts/render-card.mjs",
82
84
  "check:workspace": "node scripts/check-workspace.mjs",
83
85
  "check:inspector": "tbox-inspector-check",
84
86
  "plugin:inspect": "pnpm --filter ./apps/server exec node --import tsx src/cli/plugin-inspect.ts",
85
- "plugin:doctor": "pnpm --filter ./apps/server exec node --import tsx src/cli/plugin-doctor.ts"
87
+ "plugin:doctor": "pnpm --filter ./apps/server exec node --import tsx src/cli/plugin-doctor.ts",
88
+ "storyboard": "node scripts/storyboard.mjs"
86
89
  }
87
90
  }
@@ -6,12 +6,32 @@ Agent 对话壳 UI 组件包(源码发布)——单一模板统一化 W2-1
6
6
  (name 改写 `@tbox.cn/app-agent-ui-kit` → `@tbox.cn/app-agent-ui-kit`),guard identity 锁定一致。
7
7
  - **消费面**:应用 `<ChatPage store={useChatStore} cards={CHAT_REGISTRY} slots={clientCtx.slots}/>`
8
8
  单点装配;域 UI(如商圈主屏)经 home 槽渲染函数自带。
9
- - **主题**:kit 默认 tokens(`src/theme/tokens.less`);品牌资产包经 `html[data-theme]` 级联覆写 +
9
+ - **主题**:kit 默认 tokens(`src/theme/tokens.css`);品牌资产包经 `html[data-theme]` 级联覆写 +
10
10
  接线三行(`import '<pkg>/index.css'` + `import '<pkg>/brand.js'`[可选] + `applyTheme(id)`;见 docs/reference/templates.md)。
11
11
 
12
+ ## 半屏弹层
13
+
14
+ `BottomSheet` 为统一的受控底部弹层,基于已有 `antd-mobile Popup`,使用 React + Tailwind 工具类 与平台主题变量;不依赖 shadcn/ui。外壳负责 portal、遮罩、滚动锁、安全区、标题、关闭按钮、Escape 和焦点循环/恢复,业务负责请求、加载、错误与内容。
15
+
16
+ ```tsx
17
+ import { BottomSheet } from '@tbox.cn/app-agent-ui-kit/bottom-sheet';
18
+
19
+ <BottomSheet open={open} title="详情" onClose={() => setOpen(false)}>
20
+ <DetailContent />
21
+ </BottomSheet>
22
+ ```
23
+
24
+ 支持 `className` 定制内容区,默认最大高度为视口的 65%,长内容在弹层内部滚动。
25
+
26
+ 模板副本沿用同名 `@tbox.cn/app-agent-ui-kit/bottom-sheet`(`sync-agent-ui-kit` 投影,仅依赖面转 catalog:);仓内模块使用公开名并声明 optional peer,由宿主提供源码包,不从 npm 拉取。
27
+
28
+ **SSR / Node 边界**:`BottomSheet` 对 `antd-mobile` 的 `Popup` 采用浏览器按需加载(`import()`),`bottom-sheet` 子路径在 Vite/Node SSR 里可直接 import,不再触发 antd-mobile CJS 入口的 `global.css` 解析错误。需要首开无等待时,宿主可调用 `preloadBottomSheet()`(根入口或 `bottom-sheet` 子路径)预热;加载失败会在下一次 open 重试。kit **根入口**仍依赖 SVG/PNG/CSS 资产,只承诺 bundler(Vite 等)消费,不承诺 raw-Node 直跑。
29
+
12
30
  ## 验证
13
31
 
14
32
  ```sh
15
33
  pnpm --filter @tbox.cn/app-agent-ui-kit typecheck
16
34
  pnpm --filter @tbox.cn/app-agent-ui-kit test
17
35
  ```
36
+
37
+ 轻提示可从 `@tbox.cn/app-agent-ui-kit/toast` 独立导入 `toast`,避免引入完整聊天壳。
@@ -404,7 +404,7 @@
404
404
  },
405
405
  {
406
406
  "name": "tone",
407
- "type": "'primary' | 'warm' | 'jade' | 'neutral'",
407
+ "type": "'primary' | 'warm' | 'jade' | 'inverse' | 'neutral'",
408
408
  "optional": true
409
409
  }
410
410
  ]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-agent-ui-kit",
3
- "version": "1.0.0-alpha.8",
3
+ "version": "1.0.0-alpha.9",
4
4
  "type": "module",
5
5
  "description": "Agent 对话壳 UI 组件包(源码发布,单一模板统一化 W2-1):ChatPage/壳组件族/主题 tokens。",
6
6
  "exports": {
@@ -18,6 +18,14 @@
18
18
  "./icons": {
19
19
  "types": "./src/icons.ts",
20
20
  "import": "./src/icons.ts"
21
+ },
22
+ "./toast": {
23
+ "types": "./src/utils/toast.ts",
24
+ "import": "./src/utils/toast.ts"
25
+ },
26
+ "./bottom-sheet": {
27
+ "types": "./src/components/BottomSheet/index.tsx",
28
+ "import": "./src/components/BottomSheet/index.tsx"
21
29
  }
22
30
  },
23
31
  "scripts": {
@@ -7,6 +7,9 @@
7
7
  * - 域自持段(首屏数据/门禁/详情弹层/活动预热)经槽渲染函数自带——本页零域语义。
8
8
  */
9
9
  import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
10
+
11
+ // SSR(预览/探针)没有 DOM 可量:useLayoutEffect 会打印不可消除的告警,服务端退化为 useEffect。
12
+ const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;
10
13
  import { consumeAutoSendQuery, runAutoSend } from '@tbox.cn/app-agent-sdk-client';
11
14
  import { usePullDownHistory } from './hooks/use-pull-down-history';
12
15
  import type { TboxCardPayload } from '@tbox.cn/app-contracts';
@@ -89,6 +92,23 @@ function ChatPageInner() {
89
92
  const homeSlot = slots?.resolve('home');
90
93
  const identity = useChatConfigStore((s) => s.identity);
91
94
  const welcome = useChatConfigStore((s) => s.welcome);
95
+
96
+ // 页面元信息跟身份与主题走:标题、主题色不再停在模板出厂值(B9)。
97
+ useEffect(() => {
98
+ if (typeof document === 'undefined') return;
99
+ const name = identity?.name;
100
+ if (name) document.title = name;
101
+ const bg = getComputedStyle(document.documentElement).getPropertyValue('--tbox-bg-page').trim();
102
+ if (bg) {
103
+ let meta = document.querySelector('meta[name="theme-color"]');
104
+ if (!meta) {
105
+ meta = document.createElement('meta');
106
+ meta.setAttribute('name', 'theme-color');
107
+ document.head.appendChild(meta);
108
+ }
109
+ meta.setAttribute('content', bg);
110
+ }
111
+ }, [identity?.name]);
92
112
  // 常驻品牌条:chat.json identity.name → HELLO_ACK 的 mallName → 不渲染(壳契约见 shell.ts)
93
113
  const brandName = resolveBrandName(identity, mallName);
94
114
 
@@ -167,7 +187,7 @@ function ChatPageInner() {
167
187
 
168
188
  // 历史插入发生在当前内容上方:绘制前只补一次新增高度,保持用户原本看到的位置。
169
189
  // 不设置定时器、不钉住 scrollTop;补偿后下一次滚动立即由用户接管。
170
- useLayoutEffect(() => {
190
+ useIsomorphicLayoutEffect(() => {
171
191
  const pending = pendingHistoryViewportRef.current;
172
192
  const anchor = historyAnchorRef.current;
173
193
  if (!pending || !anchor) return;
@@ -255,8 +275,17 @@ function ChatPageInner() {
255
275
  const delta = element.getBoundingClientRect().top - body.getBoundingClientRect().top;
256
276
  body.scrollTop += delta - 8;
257
277
  isNearBottomRef.current = false;
278
+ // 回合锚定后内容通常超出视口:必须让「回到底部」入口出现,否则用户只能靠手势找底。
279
+ if (body.scrollHeight > body.clientHeight + 8) setShowScrollToBottom(true);
258
280
  }, [messages]);
259
281
 
282
+ // 已脱离底部时内容继续变高(流式回复、卡片后挂载):保持浮标可见,不追底。
283
+ useEffect(() => {
284
+ if (isNearBottomRef.current) return;
285
+ const el = bodyRef.current;
286
+ if (el && el.scrollHeight > el.clientHeight + 8) setShowScrollToBottom(true);
287
+ }, [messages, liveCardSignature, orphanCards]);
288
+
260
289
  // 没有新回合、但卡片在文字之后挂载时,内容会继续变高:只在用户本来就在底部时补滚,
261
290
  // 且不改变「本轮问题已在视口内」的锚点。
262
291
  useEffect(() => {
@@ -89,6 +89,16 @@ describe('第二版基元', () => {
89
89
  );
90
90
  expect(markup).toContain('tbox-hero');
91
91
  expect(markup).toContain('我的积分');
92
+ // 深底主视觉:底用 primary-dark、字用 primary-foreground,全部走令牌(无字面量色值)。
93
+ const inverse = html(<Hero eyebrow="ROUTE" title="导航" value={8} unit="分钟" tone="inverse" />);
94
+ expect(inverse).toContain('tbox-hero--inverse');
95
+ expect(inverse).toContain('bg-primary-dark');
96
+ expect(inverse).toContain('text-primary-foreground');
97
+ expect(inverse).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(/);
98
+ // 未知 tone(旧数据 / 新 kit 错配)回落 primary,不拼空类名。
99
+ const unknown = html(<Hero title="兜底" tone={'legacy' as never} />);
100
+ expect(unknown).toContain('tbox-hero--legacy');
101
+ expect(unknown).toContain('from-primary-foreground');
92
102
  expect(markup).toContain('tbox-stats__value');
93
103
  expect(markup).toContain('tbox-timeline__item--gain');
94
104
  expect(markup).toContain('+100');
@@ -18,18 +18,18 @@ export type Tone = 'neutral' | 'info' | 'success' | 'warning' | 'error';
18
18
  /** 状态色:中性走契约语义色,其余是旧 less 里的固定色值(透明度底 + 深色字) */
19
19
  const TAG_TONE: Record<Tone, string> = {
20
20
  neutral: 'bg-muted text-secondary-foreground',
21
- info: 'bg-[rgba(22,119,255,0.12)] text-[var(--tbox-primary,#1677ff)]',
22
- success: 'bg-[rgba(34,160,90,0.12)] text-[#1a7f4b]',
23
- warning: 'bg-[rgba(230,150,0,0.14)] text-[#9a6200]',
24
- error: 'bg-[rgba(220,60,60,0.12)] text-[#b02a2a]',
21
+ info: 'bg-primary-soft text-primary',
22
+ success: 'bg-success-soft text-success',
23
+ warning: 'bg-warning-soft text-warn-ink',
24
+ error: 'bg-danger-soft text-destructive',
25
25
  };
26
26
 
27
27
  const NOTICE_TONE: Record<Tone, string> = {
28
28
  neutral: 'bg-muted',
29
- info: 'bg-muted',
30
- success: 'bg-[rgba(34,160,90,0.1)]',
31
- warning: 'bg-[rgba(230,150,0,0.1)]',
32
- error: 'bg-[rgba(220,60,60,0.1)]',
29
+ info: 'bg-primary-soft',
30
+ success: 'bg-success-soft',
31
+ warning: 'bg-warning-soft',
32
+ error: 'bg-danger-soft',
33
33
  };
34
34
 
35
35
  export interface CardProps {
@@ -288,6 +288,8 @@ const HERO_TONE = {
288
288
  primary: 'bg-linear-to-br from-primary-foreground to-card',
289
289
  warm: 'bg-linear-to-br from-warm to-card',
290
290
  jade: 'bg-linear-to-br from-jade to-card',
291
+ // 深色底:只用契约里的令牌(primary-dark / primary-light),不引入字面量色值。
292
+ inverse: 'bg-primary-dark text-primary-foreground [&_.tbox-hero__eyebrow]:text-primary-foreground [&_.tbox-hero__footnote]:text-primary-foreground [&_.tbox-hero__value_small]:text-primary-foreground',
291
293
  neutral: 'bg-muted',
292
294
  } as const;
293
295
 
@@ -382,13 +384,15 @@ export interface HeroProps {
382
384
  /** 数值下方一句说明 */
383
385
  footnote?: ReactNode;
384
386
  icon?: ReactNode;
385
- tone?: 'primary' | 'warm' | 'jade' | 'neutral';
387
+ tone?: 'primary' | 'warm' | 'jade' | 'inverse' | 'neutral';
386
388
  }
387
389
 
388
390
  /** 品牌色块:主数值 + 说明,用于会员、积分、钱包类卡片的头部。 */
389
391
  export function Hero({ eyebrow, title, value, unit, footnote, icon, tone = 'primary' }: HeroProps) {
392
+ // 旧 kit 与新数据错配时(未知 tone)回落 primary,不拼出空类名。
393
+ const toneClass = HERO_TONE[tone] ?? HERO_TONE.primary;
390
394
  return (
391
- <div className={`tbox-hero tbox-hero--${tone} flex items-center gap-2 rounded-md p-3.5 pb-3.25 ${HERO_TONE[tone]}`}>
395
+ <div className={`tbox-hero tbox-hero--${tone} flex items-center gap-2 rounded-md p-3.5 pb-3.25 ${toneClass}`}>
392
396
  <div className="tbox-hero__text flex min-w-0 flex-1 flex-col gap-1.5">
393
397
  {eyebrow ? <span className="tbox-hero__eyebrow text-xs tracking-wide text-muted-foreground">{eyebrow}</span> : null}
394
398
  <span className="tbox-hero__title text-sm font-semibold">{title}</span>
@@ -237,7 +237,12 @@ export function ViewCard({
237
237
  <div key={block.kind + '-' + index}>{renderBlock(block, inline.trigger, inline.busy)}</div>
238
238
  ))}
239
239
  {safeView.actions && safeView.actions.length > 0 ? (
240
- <ActionList api={api} actions={safeView.actions.map(toSpec)} />
240
+ <ActionList
241
+ api={api}
242
+ actions={safeView.actions.map((action, index) =>
243
+ toSpec(index === 0 ? { ...action, style: action.style ?? 'primary' } : { ...action, style: 'secondary' }),
244
+ )}
245
+ />
241
246
  ) : null}
242
247
  {inline.sheet}
243
248
  </Card>
@@ -40,14 +40,18 @@ interface ChatConfigStore {
40
40
  applyServerSettings: (settings: ChatUiSettings | undefined) => void;
41
41
  }
42
42
 
43
+ // SSR / 探针注入点:浏览器生产环境不设置,零影响(探针看不到配置会误判)。
44
+ const ssrSnapshot = ((globalThis as { __TBOX_CHAT_CONFIG__?: Record<string, unknown> }).__TBOX_CHAT_CONFIG__ ?? {});
43
45
  export const useChatConfigStore = create<ChatConfigStore>()((set) => ({
44
- // kit 内建缺省(应用快照经 configureChatConfigDefaults 覆盖)
45
- enableImageUpload: true,
46
- enableVideoUpload: true,
47
- enableTTS: true,
48
- enableVoiceInput: true,
49
- defaultInputMode: 'TEXT',
50
- quickCommands: [],
46
+ // kit 内建缺省(应用快照经 configureChatConfigDefaults 覆盖;SSR 探针经 globalThis 注入)
47
+ enableImageUpload: (ssrSnapshot['enableImageUpload'] as boolean | undefined) ?? true,
48
+ enableVideoUpload: (ssrSnapshot['enableVideoUpload'] as boolean | undefined) ?? true,
49
+ enableTTS: (ssrSnapshot['enableTTS'] as boolean | undefined) ?? true,
50
+ enableVoiceInput: (ssrSnapshot['enableVoiceInput'] as boolean | undefined) ?? true,
51
+ defaultInputMode: (ssrSnapshot['defaultInputMode'] as 'TEXT' | 'VOICE' | undefined) ?? 'TEXT',
52
+ quickCommands: (ssrSnapshot['quickCommands'] as QuickCommand[] | undefined) ?? [],
53
+ identity: ssrSnapshot['identity'] as ChatIdentity | undefined,
54
+ welcome: ssrSnapshot['welcome'] as ChatWelcome | undefined,
51
55
  retryOnError: true,
52
56
  applyServerSettings: (settings) =>
53
57
  set((cur) => ({
@@ -22,6 +22,8 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
22
22
  let postSpy: ReturnType<typeof vi.fn>;
23
23
 
24
24
  beforeEach(() => {
25
+ // 调试入口只在显式 ?debug=1 下渲染(B5:dev 构建与 iframe 预览不再触发)
26
+ window.history.replaceState({}, '', '/?debug=1');
25
27
  host = document.createElement('div');
26
28
  document.body.appendChild(host);
27
29
  root = createRoot(host);
@@ -33,6 +35,7 @@ describe('DebugButton 平台契约(tbox:debug-trace 载荷锁定)', () => {
33
35
  afterEach(() => {
34
36
  act(() => root.unmount());
35
37
  host.remove();
38
+ window.history.replaceState({}, '', '/');
36
39
  });
37
40
 
38
41
  const clickDebug = () => {
@@ -11,13 +11,8 @@ import { Bug } from '@phosphor-icons/react';
11
11
  */
12
12
  function shouldShow(): boolean {
13
13
  if (typeof window === 'undefined') return false;
14
- if (import.meta.env.DEV) return true;
15
- if (new URLSearchParams(window.location.search).get('debug') === '1') return true;
16
- try {
17
- return window.self !== window.top;
18
- } catch {
19
- return true;
20
- }
14
+ // 只在显式调试请求下显示:dev 构建与 iframe 预览都不再触发(B5)。
15
+ return new URLSearchParams(window.location.search).get('debug') === '1';
21
16
  }
22
17
 
23
18
  export function DebugButton({
@@ -0,0 +1,90 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { act } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import type { Root } from 'react-dom/client';
6
+ import { BottomSheet } from './index';
7
+
8
+ let root: Root | undefined;
9
+ afterEach(async () => {
10
+ await act(async () => root?.unmount());
11
+ root = undefined;
12
+ document.body.innerHTML = '';
13
+ });
14
+
15
+ async function waitForDialog() {
16
+ for (let attempt = 0; attempt < 50; attempt += 1) {
17
+ const dialog = document.querySelector('[role="dialog"]');
18
+ if (dialog) return dialog;
19
+ await act(async () => {
20
+ await new Promise((resolve) => setTimeout(resolve, 0));
21
+ });
22
+ }
23
+ throw new Error('BottomSheet 懒加载后仍未挂载弹层');
24
+ }
25
+
26
+ async function renderSheet(open: boolean, onClose = vi.fn()) {
27
+ if (!root) {
28
+ const container = document.createElement('div');
29
+ document.body.append(container);
30
+ root = createRoot(container);
31
+ }
32
+ await act(async () => {
33
+ root!.render(<BottomSheet open={open} title="奖品详情" onClose={onClose}>
34
+ <button type="button">内容操作</button>
35
+ </BottomSheet>);
36
+ });
37
+ return onClose;
38
+ }
39
+
40
+ describe('BottomSheet', () => {
41
+ it('关闭态不挂载内容;打开通过 portal 展示命名对话框和业务内容', async () => {
42
+ await renderSheet(false);
43
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
44
+ await renderSheet(true);
45
+ const dialog = await waitForDialog();
46
+ expect(dialog.getAttribute('aria-modal')).toBe('true');
47
+ expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)?.textContent).toBe('奖品详情');
48
+ expect(dialog.textContent).toContain('内容操作');
49
+ });
50
+
51
+ it('关闭按钮与 Escape 请求受控关闭,卸载后恢复触发按钮焦点并清理监听', async () => {
52
+ const trigger = document.createElement('button');
53
+ document.body.append(trigger);
54
+ trigger.focus();
55
+ const onClose = await renderSheet(true);
56
+ await waitForDialog();
57
+ await act(async () => {
58
+ (document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement).click();
59
+ });
60
+ expect(onClose).toHaveBeenCalledTimes(1);
61
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));
62
+ expect(onClose).toHaveBeenCalledTimes(2);
63
+ await act(async () => root?.unmount());
64
+ root = undefined;
65
+ expect(document.activeElement).toBe(trigger);
66
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
67
+ expect(onClose).toHaveBeenCalledTimes(2);
68
+ });
69
+
70
+ it('Tab 与 Shift+Tab 在弹层内循环,不落到背景页面', async () => {
71
+ await renderSheet(true);
72
+ await waitForDialog();
73
+ const close = document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement;
74
+ const last = document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement;
75
+ last.focus();
76
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', cancelable: true }));
77
+ expect(document.activeElement).toBe(close);
78
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, cancelable: true }));
79
+ expect(document.activeElement).toBe(last);
80
+ });
81
+
82
+ it('遮罩点击请求关闭,内容点击不关闭', async () => {
83
+ const onClose = await renderSheet(true);
84
+ await waitForDialog();
85
+ await act(async () => (document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement).click());
86
+ expect(onClose).not.toHaveBeenCalled();
87
+ await act(async () => (document.querySelector('.adm-mask') as HTMLElement).click());
88
+ expect(onClose).toHaveBeenCalledTimes(1);
89
+ });
90
+ });