@tbox.cn/app-agent-ui-kit 1.0.0-alpha.1 → 1.0.0-alpha.10

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 (76) hide show
  1. package/README.md +56 -3
  2. package/package.json +22 -7
  3. package/src/ChatPage.tsx +115 -20
  4. package/src/card/action-list-pending.test.tsx +91 -0
  5. package/src/card/define-card.test.ts +25 -0
  6. package/src/card/define-card.ts +47 -0
  7. package/src/card/primitives.test.tsx +157 -0
  8. package/src/card/primitives.tsx +717 -0
  9. package/src/card/use-card-actions.ts +86 -0
  10. package/src/card/view-card-inline.test.tsx +42 -0
  11. package/src/card/view-card.test.tsx +79 -0
  12. package/src/card/view-card.tsx +250 -0
  13. package/src/chat-config.test.ts +35 -71
  14. package/src/chat-config.ts +29 -7
  15. package/src/components/ActionBar/DebugButton.test.tsx +3 -0
  16. package/src/components/ActionBar/DebugButton.tsx +5 -10
  17. package/src/components/ActionBar/index.tsx +13 -14
  18. package/src/components/BottomSheet/index.test.tsx +97 -0
  19. package/src/components/BottomSheet/index.tsx +49 -0
  20. package/src/components/ChatHeader/index.tsx +19 -17
  21. package/src/components/ChatInput/index.test.tsx +2 -2
  22. package/src/components/ChatInput/index.tsx +44 -33
  23. package/src/components/ChatInput/voice/VoicePressField.tsx +12 -3
  24. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +9 -9
  25. package/src/components/ChatInput/voice/useVoicePress.ts +1 -1
  26. package/src/components/HistoryEntry/index.tsx +4 -4
  27. package/src/components/MediaList/index.tsx +42 -28
  28. package/src/components/MessageBubble/index.tsx +59 -28
  29. package/src/components/PullDownIndicator/index.tsx +3 -4
  30. package/src/components/QuickCommands/index.test.tsx +3 -1
  31. package/src/components/QuickCommands/index.tsx +33 -10
  32. package/src/components/ReasoningBlock/index.tsx +14 -9
  33. package/src/components/ScrollToBottomButton/index.tsx +7 -5
  34. package/src/components/ToolCallBlock/index.tsx +58 -38
  35. package/src/icons.ts +39 -0
  36. package/src/index.ts +75 -1
  37. package/src/overlay/Overlay.tsx +154 -0
  38. package/src/overlay/focus.ts +53 -0
  39. package/src/overlay/index.ts +16 -0
  40. package/src/overlay/inert.ts +27 -0
  41. package/src/overlay/layers.ts +21 -0
  42. package/src/overlay/overlay.ssr.test.tsx +27 -0
  43. package/src/overlay/overlay.test.tsx +209 -0
  44. package/src/overlay/presence.ts +86 -0
  45. package/src/overlay/scroll-lock.ts +62 -0
  46. package/src/overlay/stack.ts +111 -0
  47. package/src/overlay/use-overlay.ts +80 -0
  48. package/src/preview-provider.tsx +47 -0
  49. package/src/shell.contract.json +75 -0
  50. package/src/shell.test.ts +72 -0
  51. package/src/shell.ts +60 -0
  52. package/src/surface.test.tsx +35 -0
  53. package/src/surface.tsx +44 -0
  54. package/src/theme/base.css +167 -0
  55. package/src/theme/contract.json +123 -2
  56. package/src/theme/theme-contract.test.ts +19 -3
  57. package/src/theme/{tokens.less → tokens.css} +19 -20
  58. package/src/utils/image-preview-host.tsx +95 -0
  59. package/src/utils/imagePreview.test.ts +32 -0
  60. package/src/utils/imagePreview.ts +14 -5
  61. package/src/utils/toast.test.ts +64 -0
  62. package/src/utils/toast.ts +100 -7
  63. package/src/ChatPage.less +0 -62
  64. package/src/components/ActionBar/index.less +0 -123
  65. package/src/components/ChatHeader/index.less +0 -148
  66. package/src/components/ChatInput/index.less +0 -394
  67. package/src/components/HistoryEntry/index.less +0 -49
  68. package/src/components/MediaList/index.less +0 -241
  69. package/src/components/MessageBubble/index.less +0 -325
  70. package/src/components/PullDownIndicator/index.less +0 -32
  71. package/src/components/QuickCommands/index.less +0 -63
  72. package/src/components/ReasoningBlock/index.less +0 -90
  73. package/src/components/ScrollToBottomButton/index.less +0 -32
  74. package/src/components/ToolCallBlock/index.less +0 -312
  75. package/src/theme/global.less +0 -99
  76. /package/src/theme/{motion.less → motion.css} +0 -0
@@ -6,7 +6,6 @@ import { buildSummaryText, deriveSummary, deriveToolCallItem, prettyDetailText }
6
6
  import type { ToolCallViewItem } from './detail';
7
7
  import { copyText } from '../../utils/copyText';
8
8
  import { toast } from '../../utils/toast';
9
- import './index.less';
10
9
 
11
10
  const EMPTY_TEXT = '(无)';
12
11
 
@@ -16,13 +15,31 @@ const STATUS_TEXT: Record<ToolCallViewItem['status'], string> = {
16
15
  calling: '执行中',
17
16
  };
18
17
 
18
+ /** 行状态 hook(BEM 修饰类保留;状态 → 完整类名映射,避免动态拼接)。 */
19
+ const ITEM_CLASS: Record<ToolCallViewItem['status'], string> = {
20
+ done: 'tool-calls__item--done',
21
+ error: 'tool-calls__item--error',
22
+ calling: 'tool-calls__item--calling',
23
+ };
24
+
25
+ /** 行标题颜色(旧 Less:--calling 次要 / --error 弱化 / 基态次要)。 */
26
+ const ITEM_NAME_COLOR_CLASS: Record<ToolCallViewItem['status'], string> = {
27
+ done: 'text-secondary-foreground',
28
+ error: 'text-muted-foreground',
29
+ calling: 'text-secondary-foreground',
30
+ };
31
+
32
+ /** 详情 IO 展示块(input/output 两个 pre 共用布局;颜色按错误态另给)。 */
33
+ const DETAIL_BODY_CLASS =
34
+ 'tool-calls__detail-body m-0 max-h-[280px] overflow-auto whitespace-pre-wrap break-all rounded-[8px] bg-muted px-3 py-2.5 font-mono text-xs leading-[1.6] [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden';
35
+
19
36
  /**
20
37
  * Codex 风格工具活动日志:紧凑聚合行 / 流内活动列表 / 行内完整 IO。
21
38
  * 语义判定仍在 SDK describeToolCall + detail.ts 视图模型,本组件只管理展示状态;
22
39
  * debug 门控在渲染层(018 tool-debug):prod 恒无出入参展开入口(I4),
23
40
  * dev 行标题附技术名、详情走紧凑单行格式(复制仍为美化全文);
24
41
  * 图标颜色不传 color prop(phosphor 落 SVG fill 属性,var() 低版本 web-view 不可靠),
25
- * 统一走 currentColor + less token 类。
42
+ * 统一走 currentColor + token 类。
26
43
  */
27
44
  export default function ToolCallBlock({
28
45
  toolCalls,
@@ -37,6 +54,8 @@ export default function ToolCallBlock({
37
54
  const listId = useId();
38
55
  const items = useMemo(() => toolCalls.map(deriveToolCallItem), [toolCalls]);
39
56
  const summary = useMemo(() => deriveSummary(items), [items]);
57
+ // 已恢复的失败不打扰用户:只有整批都失败时才展示失败计数与错误图标(B11)。
58
+ const allFailed = summary.failedCount > 0 && summary.failedCount === items.length;
40
59
 
41
60
  const toggleDetail = (id: string) => {
42
61
  setExpandedDetailIds((current) => {
@@ -48,37 +67,40 @@ export default function ToolCallBlock({
48
67
  };
49
68
 
50
69
  return (
51
- <div className="tool-calls">
70
+ <div className="tool-calls mb-1.5 flex flex-col">
52
71
  <button
53
72
  type="button"
54
- className={`tool-calls__summary${summary.calling ? ' tool-calls__summary--calling' : ''}`}
73
+ className={`tool-calls__summary flex min-h-11 w-full cursor-pointer appearance-none items-center justify-between rounded-[8px] border-0 bg-transparent px-0.5 py-[5px] text-left transition-[color,background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(11,15,23,0.035)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none ${summary.calling ? 'tool-calls__summary--calling text-secondary-foreground' : 'text-muted-foreground'}`}
55
74
  aria-expanded={expanded}
56
75
  aria-controls={listId}
57
76
  onClick={() => setExpanded((current) => !current)}
58
77
  >
59
- <span className="tool-calls__left">
78
+ <span className="tool-calls__left flex min-w-0 flex-1 items-center gap-2">
60
79
  {summary.calling ? (
61
- <span className="tool-calls__spinner" aria-hidden="true" />
62
- ) : summary.failedCount > 0 ? (
63
- <X className="tool-calls__icon tool-calls__icon--error" size={16} strokeWidth={2.5} />
80
+ <span
81
+ className="tool-calls__spinner size-3.5 shrink-0 animate-[tool-spin_0.8s_linear_infinite] rounded-full border-2 border-[rgba(9,107,250,0.2)] border-t-primary motion-reduce:animate-none"
82
+ aria-hidden="true"
83
+ />
84
+ ) : allFailed ? (
85
+ <X className="tool-calls__icon tool-calls__icon--error shrink-0 self-center text-muted-foreground" size={16} strokeWidth={2.5} />
64
86
  ) : (
65
- <Check className="tool-calls__icon tool-calls__icon--success" size={16} strokeWidth={2.5} />
87
+ <Check className="tool-calls__icon tool-calls__icon--success shrink-0 self-center text-muted-foreground" size={16} strokeWidth={2.5} />
66
88
  )}
67
- <span className="tool-calls__summary-text">
89
+ <span className="tool-calls__summary-text min-w-0 truncate text-xs font-normal leading-[1.4]">
68
90
  {buildSummaryText(summary).join(' · ')}
69
- {summary.failedCount > 0 && (
70
- <span className="tool-calls__failed"> · {summary.failedCount} 个失败</span>
91
+ {allFailed && (
92
+ <span className="tool-calls__failed text-muted-foreground"> · {summary.failedCount} 个失败</span>
71
93
  )}
72
94
  </span>
73
95
  </span>
74
96
  <CaretDown
75
97
  size={14}
76
- className={`tool-calls__chevron${expanded ? ' tool-calls__chevron--up' : ''}`}
98
+ className={`tool-calls__chevron ml-2 shrink-0 text-muted-foreground transition-transform duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] motion-reduce:transition-none ${expanded ? 'tool-calls__chevron--up rotate-180' : ''}`}
77
99
  />
78
100
  </button>
79
101
 
80
102
  {expanded && (
81
- <div id={listId} className="tool-calls__list">
103
+ <div id={listId} className="tool-calls__list mt-0.5 flex flex-col gap-px pl-0.5">
82
104
  {items.map((item) => {
83
105
  // 018 I4:prod(debug=false)恒无出入参展开入口;dev 才有详情交互
84
106
  const hasDetail = debug && !!item.detail;
@@ -86,41 +108,41 @@ export default function ToolCallBlock({
86
108
  const detailId = `${listId}-${item.id}`;
87
109
  const itemContent = (
88
110
  <>
89
- <span className="tool-calls__item-left">
111
+ <span className="tool-calls__item-left flex min-w-0 items-baseline gap-2">
90
112
  {item.status === 'calling' && (
91
- <span className="tool-calls__spinner tool-calls__spinner--sm" />
113
+ <span className="tool-calls__spinner tool-calls__spinner--sm size-3 shrink-0 animate-[tool-spin_0.8s_linear_infinite] rounded-full border-2 border-[rgba(9,107,250,0.2)] border-t-primary motion-reduce:animate-none" />
92
114
  )}
93
115
  {item.status === 'done' && (
94
- <Check className="tool-calls__icon tool-calls__icon--success" size={14} strokeWidth={2.5} />
116
+ <Check className="tool-calls__icon tool-calls__icon--success shrink-0 self-center text-muted-foreground" size={14} strokeWidth={2.5} />
95
117
  )}
96
118
  {item.status === 'error' && (
97
- <X className="tool-calls__icon tool-calls__icon--error" size={14} strokeWidth={2.5} />
119
+ <X className="tool-calls__icon tool-calls__icon--error shrink-0 self-center text-muted-foreground" size={14} strokeWidth={2.5} />
98
120
  )}
99
- <span className="tool-calls__item-name">
121
+ <span className={`tool-calls__item-name min-w-0 truncate text-xs font-normal leading-[1.4] ${ITEM_NAME_COLOR_CLASS[item.status]}`}>
100
122
  {item.label}
101
123
  {debug && item.techName && (
102
- <span className="tool-calls__item-tech"> · {item.techName}</span>
124
+ <span className="tool-calls__item-tech break-all text-xs leading-[1.4] text-muted-foreground [font-family:inherit]"> · {item.techName}</span>
103
125
  )}
104
126
  </span>
105
127
  {item.badge && (
106
- <span className="tool-calls__badge">· {item.badge}</span>
128
+ <span className="tool-calls__badge shrink-0 text-xs leading-[1.4] text-muted-foreground [font-family:inherit]">· {item.badge}</span>
107
129
  )}
108
130
  </span>
109
131
  {hasDetail && (
110
132
  <CaretDown
111
133
  size={12}
112
- className={`tool-calls__item-chevron${detailExpanded ? ' tool-calls__item-chevron--up' : ''}`}
134
+ className={`tool-calls__item-chevron ml-2 shrink-0 text-muted-foreground transition-transform duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] motion-reduce:transition-none ${detailExpanded ? 'tool-calls__item-chevron--up rotate-180' : ''}`}
113
135
  />
114
136
  )}
115
137
  </>
116
138
  );
117
139
 
118
140
  return (
119
- <div key={item.id} className={`tool-calls__item tool-calls__item--${item.status}`}>
141
+ <div key={item.id} className={`tool-calls__item flex min-w-0 flex-col ${ITEM_CLASS[item.status]}`}>
120
142
  {hasDetail ? (
121
143
  <button
122
144
  type="button"
123
- className="tool-calls__item-trigger"
145
+ className="tool-calls__item-trigger flex min-h-11 w-full cursor-pointer appearance-none items-center justify-between rounded-[8px] border-0 bg-transparent px-0.5 py-[5px] text-left text-secondary-foreground transition-[color,background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(11,15,23,0.035)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none"
124
146
  aria-expanded={detailExpanded}
125
147
  aria-controls={detailId}
126
148
  aria-label={`${item.label},${STATUS_TEXT[item.status]},${detailExpanded ? '收起详情' : '查看详情'}`}
@@ -130,7 +152,7 @@ export default function ToolCallBlock({
130
152
  </button>
131
153
  ) : (
132
154
  <div
133
- className="tool-calls__item-trigger tool-calls__item-trigger--static"
155
+ className="tool-calls__item-trigger tool-calls__item-trigger--static flex min-h-11 w-full cursor-default appearance-none items-center justify-between rounded-[8px] border-0 bg-transparent px-0.5 py-[5px] text-left text-secondary-foreground transition-[color,background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] motion-reduce:transition-none"
134
156
  role="status"
135
157
  aria-label={`${item.label},${STATUS_TEXT[item.status]}`}
136
158
  >
@@ -170,13 +192,13 @@ function ToolCallInlineDetail({ id, item }: { id: string; item: ToolCallViewItem
170
192
  };
171
193
 
172
194
  return (
173
- <div id={id} className="tool-calls__detail">
174
- <div className="tool-calls__detail-section">
175
- <div className="tool-calls__detail-heading">
176
- <span className="tool-calls__detail-label">输入</span>
195
+ <div id={id} className="tool-calls__detail mt-[1px] mb-2 ml-5 flex flex-col gap-2.5 border-l-2 border-l-border pb-[5px] pl-[14px] pt-[5px]">
196
+ <div className="tool-calls__detail-section flex min-w-0 flex-col gap-[5px]">
197
+ <div className="tool-calls__detail-heading flex items-center justify-between gap-2">
198
+ <span className="tool-calls__detail-label text-xs leading-[1.4] text-muted-foreground">输入</span>
177
199
  <button
178
200
  type="button"
179
- className="tool-calls__copy"
201
+ className="tool-calls__copy inline-flex min-h-11 shrink-0 cursor-pointer appearance-none items-center gap-1 rounded-[6px] border-0 bg-transparent px-[5px] py-[3px] text-xs leading-[1.2] text-muted-foreground [font-family:inherit] active:text-secondary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary disabled:cursor-default disabled:opacity-[0.55]"
180
202
  aria-label={`复制${item.label}的输入`}
181
203
  disabled={!formatted.inputPretty}
182
204
  onClick={() => void copyIo(formatted.inputPretty, '输入')}
@@ -185,14 +207,14 @@ function ToolCallInlineDetail({ id, item }: { id: string; item: ToolCallViewItem
185
207
  <span>复制</span>
186
208
  </button>
187
209
  </div>
188
- <pre className="tool-calls__detail-body">{formatted.input || EMPTY_TEXT}</pre>
210
+ <pre className={`${DETAIL_BODY_CLASS} text-secondary-foreground`}>{formatted.input || EMPTY_TEXT}</pre>
189
211
  </div>
190
- <div className="tool-calls__detail-section">
191
- <div className="tool-calls__detail-heading">
192
- <span className="tool-calls__detail-label">输出</span>
212
+ <div className="tool-calls__detail-section flex min-w-0 flex-col gap-[5px]">
213
+ <div className="tool-calls__detail-heading flex items-center justify-between gap-2">
214
+ <span className="tool-calls__detail-label text-xs leading-[1.4] text-muted-foreground">输出</span>
193
215
  <button
194
216
  type="button"
195
- className="tool-calls__copy"
217
+ className="tool-calls__copy inline-flex min-h-11 shrink-0 cursor-pointer appearance-none items-center gap-1 rounded-[6px] border-0 bg-transparent px-[5px] py-[3px] text-xs leading-[1.2] text-muted-foreground [font-family:inherit] active:text-secondary-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary disabled:cursor-default disabled:opacity-[0.55]"
196
218
  aria-label={`复制${item.label}的输出`}
197
219
  disabled={!formatted.outputPretty}
198
220
  onClick={() => void copyIo(formatted.outputPretty, '输出')}
@@ -201,9 +223,7 @@ function ToolCallInlineDetail({ id, item }: { id: string; item: ToolCallViewItem
201
223
  <span>复制</span>
202
224
  </button>
203
225
  </div>
204
- <pre
205
- className={`tool-calls__detail-body${item.detail?.isError ? ' tool-calls__detail-body--error' : ''}`}
206
- >
226
+ <pre className={`${DETAIL_BODY_CLASS} ${item.detail?.isError ? 'tool-calls__detail-body--error text-muted-foreground' : 'text-secondary-foreground'}`}>
207
227
  {formatted.output || EMPTY_TEXT}
208
228
  </pre>
209
229
  </div>
package/src/icons.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * 图标入口:应用侧不再直接依赖 `@phosphor-icons/react`。
3
+ *
4
+ * 只再导出卡片与空态常用的一组,含义稳定、体积可控;需要新图标时在此增补,
5
+ * 应用侧 `import { IconName } from '@tbox.cn/app-agent-ui-kit/icons'`。
6
+ */
7
+ export {
8
+ ArrowRight,
9
+ ArrowsClockwise,
10
+ Calendar,
11
+ CaretDown,
12
+ CaretRight,
13
+ Check,
14
+ CheckCircle,
15
+ Clock,
16
+ Coins,
17
+ Copy,
18
+ CreditCard,
19
+ CurrencyCny,
20
+ Gift,
21
+ Info,
22
+ MapPin,
23
+ MapTrifold,
24
+ Plus,
25
+ QrCode,
26
+ Receipt,
27
+ SealCheck,
28
+ ShareNetwork,
29
+ Sparkle,
30
+ Star,
31
+ Storefront,
32
+ Ticket,
33
+ Trash,
34
+ User,
35
+ UserCircle,
36
+ Warning,
37
+ WarningCircle,
38
+ X,
39
+ } from '@phosphor-icons/react';
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 消费面:应用经 `<ChatPage store cards slots .../>` 单点装配(或自组 KitChatProvider 树);
5
5
  * 域模块(如 mall-core)经 home 槽渲染函数自持域 UI——kit 组件零域语义。
6
- * 主题:`@tbox.cn/app-agent-ui-kit/theme`(applyTheme)+ `theme/index.less`(配合纯 CSS 主题包级联)。
6
+ * 主题:`@tbox.cn/app-agent-ui-kit/theme`(applyTheme)+ `theme/tokens.css` + `theme/base.css`(配合纯 CSS 主题包级联)。
7
7
  */
8
8
 
9
9
  // ── 首屏页面与注入位 ──
@@ -21,6 +21,9 @@ export {
21
21
  useClientSlots,
22
22
  } from './store-context';
23
23
  export type { KitChatContextValue } from './store-context';
24
+ export { KitPreviewProvider, createPreviewStore } from './preview-provider';
25
+ export { createSurfaceHarness } from './surface';
26
+ export type { SurfaceHarness, SurfaceHarnessOptions } from './surface';
24
27
 
25
28
  // ── chat 设置(构建期快照 + HELLO_ACK 水合) ──
26
29
  export { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
@@ -29,9 +32,63 @@ export type { QuickCommand } from './chat-config';
29
32
  // ── 主题 ──
30
33
  export { applyTheme, currentTheme } from './theme/theme';
31
34
 
35
+ // ── 壳契约(区域、可覆写选择器、品牌名来源) ──
36
+ export { SHELL_CONTRACT, resolveBrandName } from './shell';
37
+ export type { ShellArea, ShellContract, ShellRegion } from './shell';
38
+
32
39
  // ── 卡片渲染(context 注册表注入) ──
33
40
  export { CardRenderer, RawCardRenderer } from './components/CardRenderer';
34
41
 
42
+ // ── 应用级卡片工厂与卡片内交互 ──
43
+ export { defineCard } from './card/define-card';
44
+ export { ViewCard } from './card/view-card';
45
+ export type { CardRenderProps, DefinedCard } from './card/define-card';
46
+ export { useCardActions } from './card/use-card-actions';
47
+ export type { CardActions, UseCardActionsOptions } from './card/use-card-actions';
48
+
49
+ // ── 卡片基元(信息类卡片直接拼,零样式文件) ──
50
+ export {
51
+ ActionList,
52
+ ActionRow,
53
+ Bill,
54
+ Card,
55
+ CardButton,
56
+ CardHeader,
57
+ CheckRow,
58
+ ConfirmSheet,
59
+ EmptyState,
60
+ EntityRow,
61
+ Hero,
62
+ KeyValueList,
63
+ MediaRow,
64
+ Notice,
65
+ StatGrid,
66
+ StatusTag,
67
+ Steps,
68
+ TagList,
69
+ Ticket,
70
+ Timeline,
71
+ } from './card/primitives';
72
+ export type {
73
+ ActionRowProps,
74
+ BillLine,
75
+ CardActionSpec,
76
+ CardHeaderProps,
77
+ CardProps,
78
+ CheckRowProps,
79
+ ConfirmSheetProps,
80
+ EntityRowProps,
81
+ HeroProps,
82
+ KeyValueItem,
83
+ MediaRowProps,
84
+ NoticeProps,
85
+ StatItem,
86
+ StepItem,
87
+ TicketProps,
88
+ TimelineItem,
89
+ Tone,
90
+ } from './card/primitives';
91
+
35
92
  // ── 壳组件族 ──
36
93
  export { MessageBubble } from './components/MessageBubble';
37
94
  export { ChatInput } from './components/ChatInput';
@@ -67,3 +124,20 @@ export type {
67
124
  MessageStatus,
68
125
  ToolCallInfo,
69
126
  } from './types';
127
+
128
+ // ── 通用弹层 ──
129
+ export { BottomSheet, preloadBottomSheet } from './components/BottomSheet';
130
+ export type { BottomSheetProps } from './components/BottomSheet';
131
+ export { Overlay, useOverlay, usePresence, registerScrollHost } from './overlay';
132
+ export { OVERLAY_LAYER_CLASS, OVERLAY_LAYER_Z } from './overlay';
133
+ export type {
134
+ DismissReason,
135
+ FocusRestore,
136
+ InitialFocus,
137
+ OverlayLayer,
138
+ OverlayProps,
139
+ PresenceOptions,
140
+ PresenceResult,
141
+ PresenceState,
142
+ UseOverlayOptions,
143
+ } from './overlay';
@@ -0,0 +1,154 @@
1
+ /**
2
+ * 统一弹层外壳:传送 + 根 + 遮罩 + 面板(role/aria)+ 布局预设。
3
+ *
4
+ * DOM 契约(测试与业务 BEM 钩子依赖):
5
+ * div[data-tbox-overlay][data-state] ← 业务 rootClassName 落这里
6
+ * div[data-tbox-overlay-mask] ← 遮罩
7
+ * section[data-tbox-overlay-panel][role=dialog] ← 业务 panelClassName 落这里
8
+ * 退出动画期间(data-state="closed")面板不再带 role/aria-modal,且整层 pointer-events:none。
9
+ * 服务端没有 document:就地渲染(不做 portal),保证 renderToStaticMarkup 证据链可用。
10
+ */
11
+ import { useRef } from 'react';
12
+ import type { HTMLAttributes, PointerEvent as ReactPointerEvent, ReactNode } from 'react';
13
+ import { createPortal } from 'react-dom';
14
+ import { OVERLAY_LAYER_CLASS, OVERLAY_ROOT_CLASS } from './layers';
15
+ import type { DismissReason, OverlayLayer } from './layers';
16
+ import type { FocusRestore, InitialFocus } from './focus';
17
+ import { usePresence } from './presence';
18
+ import { useOverlay } from './use-overlay';
19
+
20
+ const canUseDom = typeof document !== 'undefined' && typeof document.createElement === 'function';
21
+
22
+ const PLACEMENT_CLASS = {
23
+ bottom: 'flex items-end justify-center',
24
+ center: 'flex items-center justify-center p-2',
25
+ none: '',
26
+ } as const;
27
+
28
+ export interface OverlayProps {
29
+ open: boolean;
30
+ onDismiss: (reason: DismissReason) => void;
31
+ /** 'bottom' = 底部贴边居中;'center' = 视口居中;'none' = 调用方自定位面板。 */
32
+ placement?: 'bottom' | 'center' | 'none';
33
+ layer?: OverlayLayer;
34
+ mask?: boolean;
35
+ maskClassName?: string;
36
+ /** 'click'(默认)| 'self-pointerdown':按下点必须落在遮罩本身(防拖拽结束误关)。 */
37
+ maskDismiss?: 'click' | 'self-pointerdown' | false;
38
+ rootClassName?: string;
39
+ panelClassName?: string;
40
+ labelledBy?: string;
41
+ label?: string;
42
+ describedBy?: string;
43
+ panelProps?: HTMLAttributes<HTMLElement>;
44
+ initialFocus?: InitialFocus;
45
+ restoreFocus?: FocusRestore;
46
+ lockScroll?: boolean;
47
+ inertApp?: boolean;
48
+ trapFocus?: boolean;
49
+ closeOnEscape?: boolean;
50
+ /** 退出兜底时长(毫秒),与 CSS 里的退出动画时长一致。 */
51
+ exitMs?: number;
52
+ /** 退出动画结束(卸载前)回调;自管挂载的宿主用它把 onClose 推迟到动画之后。 */
53
+ onExited?: () => void;
54
+ children: ReactNode;
55
+ }
56
+
57
+ export function Overlay({
58
+ open,
59
+ onDismiss,
60
+ placement = 'bottom',
61
+ layer = 'modal',
62
+ mask = true,
63
+ maskClassName,
64
+ maskDismiss = 'click',
65
+ rootClassName,
66
+ panelClassName,
67
+ labelledBy,
68
+ label,
69
+ describedBy,
70
+ panelProps,
71
+ initialFocus,
72
+ restoreFocus,
73
+ lockScroll,
74
+ inertApp,
75
+ trapFocus,
76
+ closeOnEscape,
77
+ exitMs,
78
+ onExited,
79
+ children,
80
+ }: OverlayProps) {
81
+ const rootRef = useRef<HTMLDivElement>(null);
82
+ const panelRef = useRef<HTMLElement>(null);
83
+ const { mounted, state } = usePresence(open, { exitMs, rootRef, onExited });
84
+ useOverlay({
85
+ active: open,
86
+ onDismiss,
87
+ panelRef,
88
+ rootRef,
89
+ initialFocus,
90
+ restoreFocus,
91
+ lockScroll: lockScroll ?? true,
92
+ inertApp: inertApp ?? true,
93
+ trapFocus: trapFocus ?? true,
94
+ closeOnEscape: closeOnEscape ?? true,
95
+ });
96
+
97
+ if (!mounted) return null;
98
+ const openState = state === 'open';
99
+ const rootClass = [
100
+ OVERLAY_ROOT_CLASS,
101
+ OVERLAY_LAYER_CLASS[layer],
102
+ PLACEMENT_CLASS[placement],
103
+ rootClassName,
104
+ ]
105
+ .filter(Boolean)
106
+ .join(' ');
107
+ // 退场期间只吞事件、不再触发关闭:根保持可交互(遮罩继续挡住背景,避免「淡出中还点到底下页面」),
108
+ // 面板自己 pointer-events:none 所以点不到按钮。
109
+ const onMaskClick = maskDismiss === 'click' && openState ? () => onDismiss('mask') : undefined;
110
+ const onMaskPointerDown =
111
+ maskDismiss === 'self-pointerdown' && openState
112
+ ? (event: ReactPointerEvent<HTMLDivElement>) => {
113
+ if (event.target === event.currentTarget) onDismiss('mask');
114
+ }
115
+ : undefined;
116
+
117
+ const content = (
118
+ <div
119
+ ref={rootRef}
120
+ className={rootClass}
121
+ data-tbox-overlay=""
122
+ data-state={state}
123
+ role="presentation"
124
+ aria-hidden={openState ? undefined : true}
125
+ >
126
+ {mask ? (
127
+ <div
128
+ className={['absolute inset-0 touch-none', maskClassName ?? 'bg-scrim'].filter(Boolean).join(' ')}
129
+ data-tbox-overlay-mask=""
130
+ aria-hidden="true"
131
+ onClick={onMaskClick}
132
+ onPointerDown={onMaskPointerDown}
133
+ />
134
+ ) : null}
135
+ <section
136
+ {...panelProps}
137
+ ref={panelRef}
138
+ className={[panelClassName, openState ? '' : 'pointer-events-none'].filter(Boolean).join(' ')}
139
+ data-tbox-overlay-panel=""
140
+ role={openState ? 'dialog' : undefined}
141
+ aria-modal={openState ? true : undefined}
142
+ aria-label={label}
143
+ aria-labelledby={labelledBy}
144
+ aria-describedby={describedBy}
145
+ tabIndex={-1}
146
+ >
147
+ {children}
148
+ </section>
149
+ </div>
150
+ );
151
+
152
+ if (!canUseDom) return content;
153
+ return createPortal(content, document.body);
154
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * 弹层焦点工具:可聚焦元素查询、初始焦点、关闭后焦点恢复。
3
+ *
4
+ * 选择器取现有多份手写实现的并集(button / a[href] / 可编辑控件 / tabindex),
5
+ * 再过滤 `hidden`、`aria-hidden` 祖先与 `inert` 祖先——弹层栈给下层根节点设 inert 后,
6
+ * 这里的过滤让焦点陷阱不会把焦点送进惰性区域。
7
+ */
8
+ export const FOCUSABLE_SELECTOR = [
9
+ 'a[href]',
10
+ 'button:not(:disabled)',
11
+ 'input:not(:disabled):not([type="hidden"])',
12
+ 'select:not(:disabled)',
13
+ 'textarea:not(:disabled)',
14
+ '[tabindex]:not([tabindex="-1"])',
15
+ ].join(', ');
16
+
17
+ export type InitialFocus = { current: HTMLElement | null } | 'panel' | 'first' | undefined;
18
+ export type FocusRestore = { current: HTMLElement | null } | 'previous' | false | undefined;
19
+
20
+ export function getFocusable(root: HTMLElement | null): HTMLElement[] {
21
+ if (!root) return [];
22
+ return [...root.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)].filter((el) => {
23
+ if (el.hidden) return false;
24
+ if (el.closest('[aria-hidden="true"]')) return false;
25
+ if (el.closest('[inert]')) return false;
26
+ return true;
27
+ });
28
+ }
29
+
30
+ /** 打开时的初始焦点:显式目标 → `[data-autofocus]` → 首个可聚焦元素 → 面板自身。 */
31
+ export function focusInitial(panel: HTMLElement | null, target: InitialFocus): void {
32
+ if (!panel) return;
33
+ if (target && target !== 'panel' && target !== 'first') {
34
+ if (target.current?.isConnected) {
35
+ target.current.focus({ preventScroll: true });
36
+ return;
37
+ }
38
+ }
39
+ if (target === 'panel') {
40
+ panel.focus({ preventScroll: true });
41
+ return;
42
+ }
43
+ const auto = panel.querySelector<HTMLElement>('[data-autofocus]');
44
+ const next = auto?.isConnected ? auto : getFocusable(panel)[0];
45
+ if (next) next.focus({ preventScroll: true });
46
+ else panel.focus({ preventScroll: true });
47
+ }
48
+
49
+ /** 关闭后的焦点恢复;目标已从 DOM 移除时静默跳过。 */
50
+ export function restoreFocus(target: HTMLElement | null | undefined): void {
51
+ if (!target || !target.isConnected) return;
52
+ target.focus({ preventScroll: true });
53
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * 弹层能力公开入口(kit 子路径 `./overlay`,同时从根入口再导出)。
3
+ *
4
+ * 分层:内核 hooks(stack/scroll-lock/inert/focus/presence)→ `<Overlay>` 外壳 →
5
+ * `BottomSheet` / `ConfirmSheet` 与业务模块弹层。业务自己管 DOM 时只用 `useOverlay`。
6
+ */
7
+ export { Overlay } from './Overlay';
8
+ export type { OverlayProps } from './Overlay';
9
+ export { useOverlay } from './use-overlay';
10
+ export type { UseOverlayOptions } from './use-overlay';
11
+ export { usePresence } from './presence';
12
+ export type { PresenceOptions, PresenceResult, PresenceState } from './presence';
13
+ export { registerScrollHost } from './scroll-lock';
14
+ export { OVERLAY_LAYER_CLASS, OVERLAY_LAYER_Z } from './layers';
15
+ export type { DismissReason, OverlayLayer } from './layers';
16
+ export type { FocusRestore, InitialFocus } from './focus';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `inert` / `aria-hidden` 管理:弹层打开时把应用根与下层弹层设为惰性,栈顶恢复。
3
+ *
4
+ * React 18 不认识 `inert` 属性(写成 JSX 会被丢弃),因此只在 effect 里操作 DOM,
5
+ * 并保存原值(含 `aria-hidden`)以便逐层还原。
6
+ */
7
+ export function getAppRoot(): HTMLElement | null {
8
+ if (typeof document === 'undefined') return null;
9
+ return document.getElementById('root');
10
+ }
11
+
12
+ const saved = new WeakMap<HTMLElement, { inert: boolean; ariaHidden: string | null }>();
13
+
14
+ export function setElementInert(el: HTMLElement, inert: boolean): void {
15
+ if (inert) {
16
+ if (!saved.has(el)) saved.set(el, { inert: el.inert ?? false, ariaHidden: el.getAttribute('aria-hidden') });
17
+ el.inert = true;
18
+ el.setAttribute('aria-hidden', 'true');
19
+ return;
20
+ }
21
+ const previous = saved.get(el);
22
+ if (!previous) return;
23
+ el.inert = previous.inert;
24
+ if (previous.ariaHidden === null) el.removeAttribute('aria-hidden');
25
+ else el.setAttribute('aria-hidden', previous.ariaHidden);
26
+ saved.delete(el);
27
+ }
@@ -0,0 +1,21 @@
1
+ /** 弹层层级:只有三档(同一档内按打开先后叠放——后打开的在上)。 */
2
+ export const OVERLAY_LAYER_Z = {
3
+ modal: 1100,
4
+ preview: 1200,
5
+ toast: 1300,
6
+ } as const;
7
+
8
+ /** 与 `OVERLAY_LAYER_Z` 同值;Tailwind 只认源码里的字面量类名,因此这里保留静态写法。 */
9
+ export const OVERLAY_LAYER_CLASS = {
10
+ modal: 'z-[1100]',
11
+ preview: 'z-[1200]',
12
+ toast: 'z-[1300]',
13
+ } as const;
14
+
15
+ export type OverlayLayer = keyof typeof OVERLAY_LAYER_Z;
16
+
17
+ /** 关闭原因:Escape 或点遮罩(面板内的业务按钮不经过这里)。 */
18
+ export type DismissReason = 'escape' | 'mask';
19
+
20
+ /** 弹层根节点的块级定位:`fixed inset-0` + 层级(调用方的 rootClassName 叠在其后)。 */
21
+ export const OVERLAY_ROOT_CLASS = 'fixed inset-0';
@@ -0,0 +1,27 @@
1
+ // @vitest-environment node
2
+ import { describe, expect, it } from 'vitest';
3
+ import { renderToStaticMarkup } from 'react-dom/server';
4
+ import { Overlay } from './Overlay';
5
+
6
+ describe('Overlay(服务端)', () => {
7
+ it('无 document 时就地渲染(不 portal),保留对话框语义', () => {
8
+ const html = renderToStaticMarkup(
9
+ <Overlay open onDismiss={() => {}} labelledBy="t" rootClassName="probe-sheet">
10
+ <h2 id="t">标题</h2>
11
+ </Overlay>,
12
+ );
13
+ expect(html).toContain('data-tbox-overlay');
14
+ expect(html).toContain('role="dialog"');
15
+ expect(html).toContain('aria-labelledby="t"');
16
+ expect(html).toContain('标题');
17
+ });
18
+
19
+ it('关闭态不渲染任何标记', () => {
20
+ const html = renderToStaticMarkup(
21
+ <Overlay open={false} onDismiss={() => {}} labelledBy="t">
22
+ <h2 id="t">标题</h2>
23
+ </Overlay>,
24
+ );
25
+ expect(html).toBe('');
26
+ });
27
+ });