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

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
@@ -0,0 +1,209 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { act, useState } from 'react';
4
+ import { createRoot } from 'react-dom/client';
5
+ import type { Root } from 'react-dom/client';
6
+ import { Overlay } from './Overlay';
7
+ import { getFocusable } from './focus';
8
+ import { registerScrollHost, scrollLockState } from './scroll-lock';
9
+
10
+ let root: Root | undefined;
11
+
12
+ beforeEach(() => {
13
+ const appRoot = document.createElement('div');
14
+ appRoot.id = 'root';
15
+ document.body.append(appRoot);
16
+ });
17
+
18
+ afterEach(async () => {
19
+ await act(async () => root?.unmount());
20
+ root = undefined;
21
+ document.body.innerHTML = '';
22
+ document.body.style.overflow = '';
23
+ });
24
+
25
+ function mount(node: React.ReactElement) {
26
+ if (!root) {
27
+ const container = document.createElement('div');
28
+ document.body.append(container);
29
+ root = createRoot(container);
30
+ }
31
+ return act(async () => {
32
+ root!.render(node);
33
+ });
34
+ }
35
+
36
+ function Sheet({ onDismiss, children }: { onDismiss: () => void; children?: React.ReactNode }) {
37
+ return (
38
+ <Overlay open onDismiss={onDismiss} labelledBy="t" exitMs={20} rootClassName="probe-sheet">
39
+ <h2 id="t">标题</h2>
40
+ <button type="button">操作</button>
41
+ {children}
42
+ </Overlay>
43
+ );
44
+ }
45
+
46
+ function Nested({ opened, onInner }: { opened: boolean; onInner: () => void }) {
47
+ const [outer, setOuter] = useState(true);
48
+ return (
49
+ <>
50
+ <Overlay open={outer} onDismiss={() => setOuter(false)} labelledBy="outer-t" exitMs={20} rootClassName="outer-sheet">
51
+ <h2 id="outer-t">外层</h2>
52
+ <button type="button" onClick={() => setOuter(false)}>关外层</button>
53
+ </Overlay>
54
+ {opened ? (
55
+ <Overlay open onDismiss={onInner} labelledBy="inner-t" exitMs={20} rootClassName="inner-sheet">
56
+ <h2 id="inner-t">内层</h2>
57
+ <button type="button">内层操作</button>
58
+ </Overlay>
59
+ ) : null}
60
+ </>
61
+ );
62
+ }
63
+
64
+ describe('Overlay', () => {
65
+ it('传送进 body,面板带 role/aria 与题注', async () => {
66
+ await mount(<Sheet onDismiss={vi.fn()} />);
67
+ const dialog = document.querySelector('[role="dialog"]') as HTMLElement;
68
+ expect(dialog).not.toBeNull();
69
+ expect(dialog.getAttribute('aria-modal')).toBe('true');
70
+ expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)?.textContent).toBe('标题');
71
+ expect(document.body.contains(dialog)).toBe(true);
72
+ });
73
+
74
+ it('嵌套时 Escape 只关栈顶,且只有一个 dialog 可交互', async () => {
75
+ const onInner = vi.fn();
76
+ await mount(<Nested opened onInner={onInner} />);
77
+ const outer = document.querySelector('.outer-sheet') as HTMLElement;
78
+ expect(outer.inert).toBe(true);
79
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));
80
+ expect(onInner).toHaveBeenCalledTimes(1);
81
+ expect(document.querySelector('.outer-sheet')).not.toBeNull();
82
+ });
83
+
84
+ it('滚动锁按计数解锁,锁住已登记的宿主', async () => {
85
+ const host = document.createElement('div');
86
+ document.body.append(host);
87
+ const unregister = registerScrollHost(host);
88
+ expect(scrollLockState().count).toBe(0);
89
+ await mount(<Sheet onDismiss={vi.fn()} />);
90
+ expect(document.body.style.overflow).toBe('hidden');
91
+ expect(host.style.overflow).toBe('hidden');
92
+ expect(host.style.overscrollBehavior).toBe('none');
93
+ await act(async () => root?.unmount());
94
+ root = undefined;
95
+ expect(document.body.style.overflow).toBe('');
96
+ expect(host.style.overflow).toBe('');
97
+ unregister();
98
+ });
99
+
100
+ it('应用根在弹层打开时惰性,关闭后还原', async () => {
101
+ const appRoot = document.getElementById('root') as HTMLElement;
102
+ expect(appRoot.inert).toBe(false);
103
+ await mount(<Sheet onDismiss={vi.fn()} />);
104
+ expect(appRoot.inert).toBe(true);
105
+ expect(appRoot.getAttribute('aria-hidden')).toBe('true');
106
+ await act(async () => root?.unmount());
107
+ root = undefined;
108
+ expect(appRoot.inert).toBe(false);
109
+ expect(appRoot.getAttribute('aria-hidden')).toBeNull();
110
+ });
111
+
112
+ it('初始焦点落在首个可聚焦元素,关闭后回到打开前的元素', async () => {
113
+ const trigger = document.createElement('button');
114
+ document.body.append(trigger);
115
+ trigger.focus();
116
+ await mount(<Sheet onDismiss={vi.fn()} />);
117
+ await act(async () => {
118
+ await new Promise((resolve) => setTimeout(resolve, 0));
119
+ });
120
+ expect(document.activeElement?.textContent).toBe('操作');
121
+ await act(async () => root?.unmount());
122
+ root = undefined;
123
+ expect(document.activeElement).toBe(trigger);
124
+ });
125
+
126
+ it('退出态放弃 dialog 角色并在动画结束后卸载', async () => {
127
+ function Toggle() {
128
+ const [open, setOpen] = useState(true);
129
+ return (
130
+ <>
131
+ <button type="button" onClick={() => setOpen(false)}>关</button>
132
+ <Overlay open={open} onDismiss={() => setOpen(false)} labelledBy="t" exitMs={20} rootClassName="probe-sheet">
133
+ <h2 id="t">标题</h2>
134
+ </Overlay>
135
+ </>
136
+ );
137
+ }
138
+ await mount(<Toggle />);
139
+ await act(async () => (document.querySelector('.probe-sheet [data-tbox-overlay-panel]') as HTMLElement).querySelector('button'));
140
+ await act(async () => (document.querySelector('[data-tbox-overlay-mask]') as HTMLElement).click());
141
+ const rootEl = document.querySelector('.probe-sheet') as HTMLElement;
142
+ expect(rootEl.getAttribute('data-state')).toBe('closed');
143
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
144
+ await act(async () => {
145
+ rootEl.dispatchEvent(new Event('animationend', { bubbles: true }));
146
+ });
147
+ expect(document.querySelector('.probe-sheet')).toBeNull();
148
+ });
149
+
150
+ it('退场期间遮罩继续吞点击且不再触发关闭,面板自身不可点', async () => {
151
+ const onDismiss = vi.fn();
152
+ function Toggle() {
153
+ const [open, setOpen] = useState(true);
154
+ return (
155
+ <Overlay
156
+ open={open}
157
+ onDismiss={() => {
158
+ onDismiss();
159
+ setOpen(false);
160
+ }}
161
+ labelledBy="t"
162
+ rootClassName="probe-sheet"
163
+ >
164
+ <h2 id="t">标题</h2>
165
+ <button type="button">操作</button>
166
+ </Overlay>
167
+ );
168
+ }
169
+ await mount(<Toggle />);
170
+ await act(async () => (document.querySelector('[data-tbox-overlay-mask]') as HTMLElement).click());
171
+ expect(onDismiss).toHaveBeenCalledTimes(1);
172
+ const rootEl = document.querySelector('.probe-sheet') as HTMLElement;
173
+ const panel = rootEl.querySelector('[data-tbox-overlay-panel]') as HTMLElement;
174
+ expect(rootEl.getAttribute('data-state')).toBe('closed');
175
+ // 根(与遮罩)保持可交互挡住背景;面板自身不再接收点击
176
+ expect(rootEl.className).not.toContain('pointer-events-none');
177
+ expect(panel.className).toContain('pointer-events-none');
178
+ await act(async () => (document.querySelector('[data-tbox-overlay-mask]') as HTMLElement).click());
179
+ expect(onDismiss).toHaveBeenCalledTimes(1);
180
+ });
181
+
182
+ it('遮罩 self-pointerdown 只在按下点落在遮罩本身时关闭', async () => {
183
+ const onDismiss = vi.fn();
184
+ await mount(
185
+ <Overlay open onDismiss={onDismiss} maskDismiss="self-pointerdown" labelledBy="t" rootClassName="probe-sheet">
186
+ <h2 id="t">标题</h2>
187
+ </Overlay>,
188
+ );
189
+ const panel = document.querySelector('[data-tbox-overlay-panel]') as HTMLElement;
190
+ await act(async () => {
191
+ panel.dispatchEvent(new Event('pointerdown', { bubbles: true }));
192
+ });
193
+ expect(onDismiss).not.toHaveBeenCalled();
194
+ await act(async () => {
195
+ (document.querySelector('[data-tbox-overlay-mask]') as HTMLElement).dispatchEvent(new Event('pointerdown', { bubbles: true }));
196
+ });
197
+ expect(onDismiss).toHaveBeenCalledWith('mask');
198
+ });
199
+
200
+ it('可聚焦元素查询跳过 aria-hidden 与 inert 区域', () => {
201
+ const host = document.createElement('div');
202
+ host.innerHTML = '<button>a</button><div aria-hidden="true"><button>b</button></div>';
203
+ const inertBox = document.createElement('div');
204
+ inertBox.inert = true;
205
+ inertBox.innerHTML = '<button>c</button>';
206
+ host.append(inertBox);
207
+ expect(getFocusable(host).map((el) => el.textContent)).toEqual(['a']);
208
+ });
209
+ });
@@ -0,0 +1,86 @@
1
+ /**
2
+ * 进出场存在性 hook:`open` 变 false 后先保持挂载放退出动画,动画结束(或超时)再卸载。
3
+ *
4
+ * 两条硬约束决定了这里的写法(都是踩过的坑):
5
+ * 1. **打开方向同步**:`open` 一变 true 当帧就要渲染内容。若靠 effect `setMounted(true)` 补,
6
+ * 父组件保持挂载、只切 `open` 的场景会先渲染 null,面板 ref 为空,初始焦点落不下去。
7
+ * 2. **退出方向也同步**:`open` 变 false 的那一帧必须仍然渲染(否则根节点先被卸载,
8
+ * effect 拿不到 root 就挂不上 animationend,退出态永远收不了尾)。因此用 `wasOpen` ref
9
+ * 在渲染期参与 `mounted` 计算,effect 只负责计时与监听,动画结束/超时才把 ref 放下。
10
+ *
11
+ * 约定:根节点 `data-state="open|closed"`,CSS 用 `data-[state=closed]:animate-[…]` 表达退出;
12
+ * 退出动画的 `animationend`/`transitionend` 从面板冒泡到根,这里只认根内部的事件。
13
+ * 减少动效时直接 0ms 卸载(CSS 侧同时 `motion-reduce:animate-none`)。
14
+ */
15
+ import { useEffect, useRef, useState } from 'react';
16
+ import type { RefObject } from 'react';
17
+
18
+ export type PresenceState = 'open' | 'closed';
19
+
20
+ export interface PresenceOptions {
21
+ /** 退出兜底时长(毫秒);CSS 动画结束后会提前返回。 */
22
+ exitMs?: number;
23
+ rootRef?: RefObject<HTMLElement | null>;
24
+ /** 退出动画结束(卸载前)回调:宿主自己控制挂载时用它把「真正关闭」推迟到动画之后。 */
25
+ onExited?: () => void;
26
+ }
27
+
28
+ export interface PresenceResult {
29
+ mounted: boolean;
30
+ state: PresenceState;
31
+ }
32
+
33
+ function prefersReducedMotion(): boolean {
34
+ if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
35
+ return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
36
+ }
37
+
38
+ export function usePresence(open: boolean, options: PresenceOptions = {}): PresenceResult {
39
+ const exitMs = options.exitMs ?? 200;
40
+ const rootRef = options.rootRef;
41
+ const [exiting, setExiting] = useState(false);
42
+ const wasOpen = useRef(open);
43
+ const optionsRef = useRef(options);
44
+ optionsRef.current = options;
45
+ if (open) wasOpen.current = true;
46
+ const mounted = open || exiting || wasOpen.current;
47
+
48
+ useEffect(() => {
49
+ if (open) {
50
+ setExiting(false); // 关闭中重新打开:取消退出
51
+ return undefined;
52
+ }
53
+ if (!wasOpen.current) return undefined; // 从未打开过:不进入退出
54
+ setExiting(true);
55
+ const root = rootRef?.current ?? null;
56
+ let finished = false;
57
+ const finish = () => {
58
+ if (finished) return;
59
+ finished = true;
60
+ wasOpen.current = false;
61
+ setExiting(false);
62
+ optionsRef.current.onExited?.();
63
+ };
64
+ const timer =
65
+ typeof window === 'undefined' ? undefined : window.setTimeout(finish, prefersReducedMotion() ? 0 : exitMs);
66
+ const onEnd = (event: Event) => {
67
+ const target = event.target;
68
+ if (!(target instanceof Node)) return;
69
+ if (root && !root.contains(target)) return;
70
+ finish();
71
+ };
72
+ if (root) {
73
+ root.addEventListener('animationend', onEnd);
74
+ root.addEventListener('transitionend', onEnd);
75
+ }
76
+ return () => {
77
+ if (timer !== undefined) window.clearTimeout(timer);
78
+ if (root) {
79
+ root.removeEventListener('animationend', onEnd);
80
+ root.removeEventListener('transitionend', onEnd);
81
+ }
82
+ };
83
+ }, [open, exitMs, rootRef]);
84
+
85
+ return { mounted, state: open ? 'open' : 'closed' };
86
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 弹层滚动锁:计数式(嵌套弹层按最后关闭者的顺序解锁,不会提前放行背景滚动)。
3
+ *
4
+ * 除 `document.body` 外还要锁**应用自己的滚动宿主**(对话壳 `.chat-page__body` 承担滚动,
5
+ * body 本身不滚)。宿主由 ChatPage 经 `registerScrollHost` 登记,模块不再读 kit 内部类名。
6
+ *
7
+ * 不加 touchmove 拦截:本仓兼容基线 = Safari 16.4 / Chromium 105,`overflow:hidden` 与
8
+ * `overscroll-behavior` 已足够;面板内滚动区统一 `overscroll-contain`,遮罩 `touch-none`。
9
+ */
10
+ let lockCount = 0;
11
+ const hosts = new Set<HTMLElement>();
12
+ const saved = new Map<HTMLElement, { overflow: string; overscrollBehavior: string }>();
13
+
14
+ function targets(): HTMLElement[] {
15
+ const out: HTMLElement[] = [];
16
+ if (typeof document !== 'undefined' && document.body) out.push(document.body);
17
+ for (const el of hosts) out.push(el);
18
+ return out;
19
+ }
20
+
21
+ function apply(el: HTMLElement): void {
22
+ if (!saved.has(el)) saved.set(el, { overflow: el.style.overflow, overscrollBehavior: el.style.overscrollBehavior });
23
+ el.style.overflow = 'hidden';
24
+ el.style.overscrollBehavior = 'none';
25
+ }
26
+
27
+ function release(el: HTMLElement): void {
28
+ const previous = saved.get(el);
29
+ if (!previous) return;
30
+ el.style.overflow = previous.overflow;
31
+ el.style.overscrollBehavior = previous.overscrollBehavior;
32
+ saved.delete(el);
33
+ }
34
+
35
+ /** 加锁(计数 +1)。第一次加锁时锁住 body 与全部已登记宿主。 */
36
+ export function lockScroll(): void {
37
+ lockCount += 1;
38
+ if (lockCount === 1) targets().forEach(apply);
39
+ }
40
+
41
+ /** 解锁(计数 -1)。计数归零时才还原所有宿主。 */
42
+ export function unlockScroll(): void {
43
+ if (lockCount === 0) return;
44
+ lockCount -= 1;
45
+ if (lockCount > 0) return;
46
+ for (const el of [...saved.keys()]) release(el);
47
+ }
48
+
49
+ /** 登记应用滚动宿主;返回注销函数。已加锁时立即对新宿主生效。 */
50
+ export function registerScrollHost(el: HTMLElement): () => void {
51
+ hosts.add(el);
52
+ if (lockCount > 0) apply(el);
53
+ return () => {
54
+ release(el);
55
+ hosts.delete(el);
56
+ };
57
+ }
58
+
59
+ /** 只读快照(测试与诊断用)。 */
60
+ export function scrollLockState(): { count: number; locked: HTMLElement[] } {
61
+ return { count: lockCount, locked: [...saved.keys()] };
62
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * 弹层栈:全实例唯一(kit 是宿主唯一副本),只维护顺序与「谁在最上层」。
3
+ *
4
+ * 键盘只挂**一个** document 捕获监听:Escape 与 Tab 焦点循环只分发给栈顶。
5
+ * 这样嵌套弹层不会一起关(旧实现每层各挂 document 监听,stopPropagation 挡不住同节点监听)。
6
+ * 栈非空时恒消费 Escape(即便栈顶 closeOnEscape=false,也不让背景的 Escape 处理器收到)。
7
+ */
8
+ import type { RefObject } from 'react';
9
+ import type { DismissReason } from './layers';
10
+ import { getFocusable } from './focus';
11
+ import { getAppRoot, setElementInert } from './inert';
12
+
13
+ export interface OverlayStackEntry {
14
+ readonly id: symbol;
15
+ onDismiss: (reason: DismissReason) => void;
16
+ closeOnEscape: boolean;
17
+ trapFocus: boolean;
18
+ inertApp: boolean;
19
+ panelRef: RefObject<HTMLElement | null>;
20
+ rootRef: RefObject<HTMLElement | null> | undefined;
21
+ }
22
+
23
+ const stack: OverlayStackEntry[] = [];
24
+ let bound = false;
25
+
26
+ function onKeyDown(event: KeyboardEvent): void {
27
+ const top = stack[stack.length - 1];
28
+ if (!top) return;
29
+ if (event.key === 'Escape') {
30
+ event.preventDefault();
31
+ event.stopPropagation();
32
+ if (top.closeOnEscape) top.onDismiss('escape');
33
+ return;
34
+ }
35
+ if (event.key !== 'Tab' || !top.trapFocus) return;
36
+ const panel = top.panelRef.current;
37
+ if (!panel) return;
38
+ const focusable = getFocusable(panel);
39
+ const first = focusable[0];
40
+ const last = focusable[focusable.length - 1];
41
+ const active = document.activeElement instanceof HTMLElement ? document.activeElement : null;
42
+ if (!first || !last) {
43
+ event.preventDefault();
44
+ panel.focus({ preventScroll: true });
45
+ return;
46
+ }
47
+ if (event.shiftKey) {
48
+ if (active === first || !active || !panel.contains(active)) {
49
+ event.preventDefault();
50
+ last.focus();
51
+ }
52
+ return;
53
+ }
54
+ if (active === last || !active || !panel.contains(active)) {
55
+ event.preventDefault();
56
+ first.focus();
57
+ }
58
+ }
59
+
60
+ function bind(): void {
61
+ if (bound || typeof document === 'undefined') return;
62
+ // document 捕获阶段:真实按键从聚焦元素冒泡上来时最先到这里,能抢先消费 Escape;
63
+ // 测试直接 `document.dispatchEvent(new KeyboardEvent(...))` 也命中(target 自身同样触发捕获监听)。
64
+ document.addEventListener('keydown', onKeyDown, true);
65
+ bound = true;
66
+ }
67
+
68
+ function unbind(): void {
69
+ if (!bound || typeof document === 'undefined') return;
70
+ document.removeEventListener('keydown', onKeyDown, true);
71
+ bound = false;
72
+ }
73
+
74
+ export function pushOverlay(entry: OverlayStackEntry): () => void {
75
+ stack.push(entry);
76
+ bind();
77
+ notifyOverlays();
78
+ return () => {
79
+ const index = stack.indexOf(entry);
80
+ if (index >= 0) stack.splice(index, 1);
81
+ if (stack.length === 0) unbind();
82
+ notifyOverlays();
83
+ };
84
+ }
85
+
86
+ /**
87
+ * 按栈重算惰性:应用根在所有栈顶之外的弹层打开时惰性;每个弹层的根节点除栈顶外一律惰性。
88
+ * 幂等,可在任意栈变化后重复调用。
89
+ */
90
+ export function syncOverlayInert(): void {
91
+ const top = stack[stack.length - 1];
92
+ const appRoot = getAppRoot();
93
+ if (appRoot) {
94
+ // 就地渲染的弹层(无 portal 的宿主)会落在应用根内部:此时给根设 inert 会把弹层自己
95
+ // 一起惰性化,弹层就点不动了。有这种条目时改由逐条根的按层惰性负责。
96
+ const inline = stack.some((entry) => {
97
+ const root = entry.rootRef?.current;
98
+ return Boolean(root && appRoot.contains(root));
99
+ });
100
+ setElementInert(appRoot, !inline && stack.some((entry) => entry.inertApp));
101
+ }
102
+ for (const entry of stack) {
103
+ const root = entry.rootRef?.current;
104
+ if (!root || root.contains(appRoot)) continue;
105
+ setElementInert(root, entry !== top);
106
+ }
107
+ }
108
+
109
+ function notifyOverlays(): void {
110
+ syncOverlayInert();
111
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 弹层行为总装 hook:入栈 / 滚动锁 / 惰性 / 初始焦点 / 关闭后焦点恢复。
3
+ *
4
+ * 给需要自管 DOM 的复杂弹层用(例如带 FLIP 形变的详情页);常规弹层直接用 `<Overlay>`。
5
+ * `active` 用**逻辑开关**(等于 `open`):退出动画期间即出栈、解锁、恢复焦点,
6
+ * 但组件靠 `usePresence` 继续挂载到动画结束(此时面板已无 `role=dialog`)。
7
+ */
8
+ import { useEffect, useRef } from 'react';
9
+ import type { RefObject } from 'react';
10
+ import type { DismissReason } from './layers';
11
+ import { focusInitial, restoreFocus } from './focus';
12
+ import type { FocusRestore, InitialFocus } from './focus';
13
+ import { lockScroll, unlockScroll } from './scroll-lock';
14
+ import { pushOverlay } from './stack';
15
+ import type { OverlayStackEntry } from './stack';
16
+
17
+ export interface UseOverlayOptions {
18
+ active: boolean;
19
+ onDismiss: (reason: DismissReason) => void;
20
+ panelRef: RefObject<HTMLElement | null>;
21
+ rootRef?: RefObject<HTMLElement | null>;
22
+ initialFocus?: InitialFocus;
23
+ /** 默认 'previous'(打开前的焦点);false = 不恢复。 */
24
+ restoreFocus?: FocusRestore;
25
+ lockScroll?: boolean;
26
+ inertApp?: boolean;
27
+ trapFocus?: boolean;
28
+ closeOnEscape?: boolean;
29
+ }
30
+
31
+ export function useOverlay(options: UseOverlayOptions): void {
32
+ const { active } = options;
33
+ const latest = useRef(options);
34
+ latest.current = options;
35
+ const entryRef = useRef<OverlayStackEntry | null>(null);
36
+ const lockedRef = useRef(false);
37
+ const previousFocusRef = useRef<HTMLElement | null>(null);
38
+
39
+ // 每次渲染同步可变字段(与仓内既有 `onCloseRef.current = onClose` 同款写法)。
40
+ const entry = entryRef.current;
41
+ if (entry) {
42
+ entry.onDismiss = (reason) => latest.current.onDismiss(reason);
43
+ entry.closeOnEscape = latest.current.closeOnEscape ?? true;
44
+ entry.trapFocus = latest.current.trapFocus ?? true;
45
+ entry.inertApp = latest.current.inertApp ?? true;
46
+ }
47
+
48
+ useEffect(() => {
49
+ if (!active) return undefined;
50
+ if (typeof document === 'undefined') return undefined;
51
+ previousFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
52
+ const created: OverlayStackEntry = {
53
+ id: Symbol('tbox-overlay'),
54
+ onDismiss: (reason) => latest.current.onDismiss(reason),
55
+ closeOnEscape: latest.current.closeOnEscape ?? true,
56
+ trapFocus: latest.current.trapFocus ?? true,
57
+ inertApp: latest.current.inertApp ?? true,
58
+ panelRef: latest.current.panelRef,
59
+ rootRef: latest.current.rootRef,
60
+ };
61
+ entryRef.current = created;
62
+ const remove = pushOverlay(created);
63
+ if (latest.current.lockScroll ?? true) {
64
+ lockScroll();
65
+ lockedRef.current = true;
66
+ }
67
+ // 初始焦点就地设置:本 effect 在 DOM 提交后跑到这里,面板已在文档里。
68
+ focusInitial(created.panelRef.current, latest.current.initialFocus);
69
+ return () => {
70
+ remove();
71
+ entryRef.current = null;
72
+ if (lockedRef.current) {
73
+ unlockScroll();
74
+ lockedRef.current = false;
75
+ }
76
+ const restore = latest.current.restoreFocus ?? 'previous';
77
+ if (restore) restoreFocus(restore === 'previous' ? previousFocusRef.current : restore.current);
78
+ };
79
+ }, [active]);
80
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * KitPreviewProvider:卡片预览面的最小装配根。
3
+ *
4
+ * 预览页直接渲染 SDK CardRenderer,没有应用 store——kit 卡片的 `useCardActions`
5
+ * 会因「KitChatProvider 缺席」抛错(预览 7/7 全红)。这里给一个只读预览 store:
6
+ * 动作写通道是空实现(预览页自己的动作通道另经 bindCardActionChannel 接管),
7
+ * 卡片能渲染、按钮能显示、历史/禁用态照常。
8
+ *
9
+ * 应用接线:app.config.ts 的 `wrapPreview` 返回 `createElement(KitPreviewProvider, null, node)`。
10
+ */
11
+ import { useMemo, type ReactNode } from 'react';
12
+ import { useStore } from 'zustand';
13
+ import { createStore } from 'zustand/vanilla';
14
+ import type { CardComponent } from '@tbox.cn/app-contracts';
15
+ import type { CoreChatState, CoreChatStore } from '@tbox.cn/app-agent-sdk-client';
16
+ import { KitChatProvider } from './store-context';
17
+
18
+ /** 预览用 store:只满足壳与卡片的读取(sendUiAction 空实现、不在生成中)。 */
19
+ export function createPreviewStore(state: Partial<CoreChatState> = {}): CoreChatStore {
20
+ const vanilla = createStore<CoreChatState>(() => ({
21
+ sendUiAction: () => {},
22
+ isGenerating: false,
23
+ ...state,
24
+ } as unknown as CoreChatState));
25
+ const hook = ((selector: (state: CoreChatState) => unknown) =>
26
+ useStore(vanilla, selector)) as unknown as CoreChatStore;
27
+ hook.getState = vanilla.getState;
28
+ hook.setState = vanilla.setState;
29
+ hook.subscribe = vanilla.subscribe;
30
+ return hook;
31
+ }
32
+
33
+ export function KitPreviewProvider({
34
+ cards = {},
35
+ children,
36
+ }: {
37
+ /** 预览页的卡片注册表(缺省空表;动作由预览页接管) */
38
+ cards?: Record<string, CardComponent>;
39
+ children: ReactNode;
40
+ }) {
41
+ const store = useMemo(() => createPreviewStore(), []);
42
+ return (
43
+ <KitChatProvider store={store} cards={cards} rawCards={cards}>
44
+ {children}
45
+ </KitChatProvider>
46
+ );
47
+ }
@@ -0,0 +1,75 @@
1
+ {
2
+ "$comment": "对话壳契约数据(docs/agent/kit.md 与 shell.test.ts 的共同来源;改这里 = 改壳的对外承诺)。regions = ChatPage 渲染的区域;internal = 不承诺稳定的内部结构。",
3
+ "regions": [
4
+ {
5
+ "id": "brand",
6
+ "area": "brand",
7
+ "selector": ".chat-page__brand",
8
+ "drivenBy": ["chat.json identity.name", "chat.json identity.tagline", "HELLO_ACK mallScope.mallName(缺省回落)"],
9
+ "brandable": true
10
+ },
11
+ {
12
+ "id": "welcome",
13
+ "area": "welcome",
14
+ "selector": ".chat-page__welcome",
15
+ "drivenBy": ["chat.json welcome.title", "chat.json welcome.subtitle", "chat.json identity(缺省回落)"],
16
+ "brandable": true
17
+ },
18
+ {
19
+ "id": "messages",
20
+ "area": "messages",
21
+ "selector": ".chat-page__body",
22
+ "drivenBy": ["chat store messages / historyMessages"],
23
+ "brandable": false
24
+ },
25
+ {
26
+ "id": "history-entry",
27
+ "area": "history",
28
+ "selector": ".history-entry",
29
+ "drivenBy": ["chat store historyHasMore / isLoadingHistory"],
30
+ "brandable": false
31
+ },
32
+ {
33
+ "id": "home-slot",
34
+ "area": "home",
35
+ "selector": ".chat-page__home-slot",
36
+ "drivenBy": ["客户端槽 home"],
37
+ "brandable": false
38
+ },
39
+ {
40
+ "id": "conversation-overlay",
41
+ "area": "conversation-overlay",
42
+ "selector": ".chat-page__conversation-overlay",
43
+ "drivenBy": ["客户端槽 conversationOverlay"],
44
+ "brandable": false
45
+ },
46
+ {
47
+ "id": "quick-commands",
48
+ "area": "quick-commands",
49
+ "selector": ".quick-commands",
50
+ "drivenBy": ["chat.json quickCommands"],
51
+ "brandable": true
52
+ },
53
+ {
54
+ "id": "input",
55
+ "area": "input",
56
+ "selector": ".tbox-chat-input",
57
+ "drivenBy": ["chat.json(enableTTS 等)", "chat store runtimeStatus / isGenerating"],
58
+ "brandable": false
59
+ }
60
+ ],
61
+ "controls": [
62
+ { "id": "new-chat", "selector": "[data-tbox-control='new-chat']", "name": "新建对话", "minHit": 44 },
63
+ { "id": "voice-toggle", "selector": "[data-tbox-control='voice-toggle']", "name": "语音输入", "minHit": 44, "capability": "input.voice" },
64
+ { "id": "send", "selector": "[data-tbox-control='send']", "name": "发送", "minHit": 44 },
65
+ { "id": "stop", "selector": "[data-tbox-control='stop']", "name": "停止生成", "minHit": 44 },
66
+ { "id": "media-add", "selector": "[data-tbox-control='media-add']", "name": "添加图片或视频", "minHit": 44, "capability": ["input.image", "input.video"] },
67
+ { "id": "history", "selector": "[data-tbox-control='history']", "name": "历史记录", "minHit": 44 },
68
+ { "id": "scroll-bottom", "selector": "[data-tbox-control='scroll-bottom']", "name": "回到底部", "minHit": 44 }
69
+ ],
70
+ "internal": [
71
+ "MessageBubble 内部结构(.msg-row / .msg-main / .msg-thinking)",
72
+ "ChatInput 内部结构(.tbox-media-picker、发送按钮)",
73
+ "卡片渲染器内部结构(.tbox-card-*)"
74
+ ]
75
+ }