@tbox.cn/app-agent-ui-kit 0.0.0-stage → 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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -2
  3. package/assets/keyboard-circle.svg +12 -0
  4. package/assets/more-circle.svg +3 -0
  5. package/assets/new-chat.svg +3 -0
  6. package/assets/quick-command-star.svg +3 -0
  7. package/assets/send-gradient.svg +14 -0
  8. package/assets/stop@2x.png +0 -0
  9. package/assets/voice-circle.svg +3 -0
  10. package/package.json +70 -3
  11. package/src/ChatPage.tsx +400 -0
  12. package/src/card/action-list-pending.test.tsx +91 -0
  13. package/src/card/define-card.test.ts +25 -0
  14. package/src/card/define-card.ts +47 -0
  15. package/src/card/primitives.test.tsx +157 -0
  16. package/src/card/primitives.tsx +717 -0
  17. package/src/card/use-card-actions.ts +86 -0
  18. package/src/card/view-card-inline.test.tsx +42 -0
  19. package/src/card/view-card.test.tsx +79 -0
  20. package/src/card/view-card.tsx +250 -0
  21. package/src/chat-config.test.ts +46 -0
  22. package/src/chat-config.ts +84 -0
  23. package/src/components/ActionBar/DebugButton.test.tsx +87 -0
  24. package/src/components/ActionBar/DebugButton.tsx +48 -0
  25. package/src/components/ActionBar/index.test.tsx +83 -0
  26. package/src/components/ActionBar/index.tsx +158 -0
  27. package/src/components/BottomSheet/index.test.tsx +97 -0
  28. package/src/components/BottomSheet/index.tsx +49 -0
  29. package/src/components/CardRenderer.tsx +36 -0
  30. package/src/components/ChatHeader/index.test.tsx +74 -0
  31. package/src/components/ChatHeader/index.tsx +77 -0
  32. package/src/components/ChatInput/index.test.tsx +156 -0
  33. package/src/components/ChatInput/index.tsx +295 -0
  34. package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
  35. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  36. package/src/components/ChatInput/voice/machine.ts +27 -0
  37. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  38. package/src/components/HistoryEntry/index.tsx +42 -0
  39. package/src/components/MediaList/index.tsx +270 -0
  40. package/src/components/MessageBubble/index.test.tsx +134 -0
  41. package/src/components/MessageBubble/index.tsx +208 -0
  42. package/src/components/PullDownIndicator/index.tsx +31 -0
  43. package/src/components/QuickCommands/index.test.tsx +101 -0
  44. package/src/components/QuickCommands/index.tsx +75 -0
  45. package/src/components/ReasoningBlock/index.tsx +61 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +12 -0
  47. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  48. package/src/components/ToolCallBlock/detail.ts +204 -0
  49. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  50. package/src/components/ToolCallBlock/index.tsx +232 -0
  51. package/src/components/ToolCallBlock/titles.ts +102 -0
  52. package/src/hooks/use-drag-gesture.test.ts +66 -0
  53. package/src/hooks/use-drag-gesture.ts +129 -0
  54. package/src/hooks/use-pull-down-history.ts +241 -0
  55. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  56. package/src/hooks/useMediaUpload.ts +242 -0
  57. package/src/hooks/useTTSAutoPlay.ts +82 -0
  58. package/src/icons.ts +39 -0
  59. package/src/index.ts +143 -0
  60. package/src/overlay/Overlay.tsx +154 -0
  61. package/src/overlay/focus.ts +53 -0
  62. package/src/overlay/index.ts +16 -0
  63. package/src/overlay/inert.ts +27 -0
  64. package/src/overlay/layers.ts +21 -0
  65. package/src/overlay/overlay.ssr.test.tsx +27 -0
  66. package/src/overlay/overlay.test.tsx +209 -0
  67. package/src/overlay/presence.ts +86 -0
  68. package/src/overlay/scroll-lock.ts +62 -0
  69. package/src/overlay/stack.ts +111 -0
  70. package/src/overlay/use-overlay.ts +80 -0
  71. package/src/preview-provider.tsx +47 -0
  72. package/src/shell.contract.json +75 -0
  73. package/src/shell.test.ts +72 -0
  74. package/src/shell.ts +60 -0
  75. package/src/store-context.tsx +92 -0
  76. package/src/surface.test.tsx +35 -0
  77. package/src/surface.tsx +44 -0
  78. package/src/test/setup.ts +7 -0
  79. package/src/theme/base.css +167 -0
  80. package/src/theme/contract.json +193 -0
  81. package/src/theme/motion.css +19 -0
  82. package/src/theme/theme-contract.test.ts +85 -0
  83. package/src/theme/theme.ts +17 -0
  84. package/src/theme/tokens.css +78 -0
  85. package/src/types.ts +29 -0
  86. package/src/utils/copyText.ts +11 -0
  87. package/src/utils/haptics.test.ts +51 -0
  88. package/src/utils/haptics.ts +44 -0
  89. package/src/utils/image-preview-host.tsx +95 -0
  90. package/src/utils/imagePreview.test.ts +32 -0
  91. package/src/utils/imagePreview.ts +19 -0
  92. package/src/utils/pull-down-machine.test.ts +188 -0
  93. package/src/utils/pull-down-machine.ts +157 -0
  94. package/src/utils/session-error.ts +5 -0
  95. package/src/utils/toast.test.ts +64 -0
  96. package/src/utils/toast.ts +108 -0
  97. package/src/utils/tool-call-display.test.ts +240 -0
  98. package/src/utils/tool-call-display.ts +146 -0
  99. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,48 @@
1
+ import { createLogger } from '@tbox.cn/app-agent-sdk-client';
2
+
3
+ const debugLogger = createLogger('DebugButton');
4
+
5
+ import { Bug } from '@phosphor-icons/react';
6
+
7
+ /**
8
+ * 调试按钮:点击把本轮 requestId / conversationId / messageId / messageCreatedAt
9
+ * 通过 postMessage 发给父窗口,平台据此构造日志时间窗、拉取 trace 日志。
10
+ * 显示条件:dev / URL 带 ?debug=1 / 被 iframe 嵌入。
11
+ */
12
+ function shouldShow(): boolean {
13
+ if (typeof window === 'undefined') return false;
14
+ // 只在显式调试请求下显示:dev 构建与 iframe 预览都不再触发(B5)。
15
+ return new URLSearchParams(window.location.search).get('debug') === '1';
16
+ }
17
+
18
+ export function DebugButton({
19
+ requestId,
20
+ conversationId,
21
+ messageId,
22
+ messageCreatedAt,
23
+ }: {
24
+ requestId?: string;
25
+ conversationId?: string;
26
+ messageId?: string;
27
+ messageCreatedAt?: number;
28
+ }) {
29
+ if (!shouldShow() || !requestId) return null;
30
+
31
+ const onClick = () => {
32
+ try {
33
+ window.parent.postMessage(
34
+ { type: 'tbox:debug-trace', requestId, conversationId, messageId, messageCreatedAt },
35
+ '*',
36
+ );
37
+ } catch (err) {
38
+ debugLogger.warn('postMessage failed:', err);
39
+ }
40
+ };
41
+
42
+ return (
43
+ <div className="tbox-debug-btn inline-flex h-[26px] items-center justify-center gap-1 rounded-full bg-white px-[11px] text-secondary-foreground transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] active:scale-[0.97] active:bg-muted" onClick={onClick}>
44
+ <Bug className="tbox-debug-btn__icon size-[14px] shrink-0" size={22} />
45
+ <span className="tbox-debug-btn__text text-xs leading-none">调试</span>
46
+ </div>
47
+ );
48
+ }
@@ -0,0 +1,83 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * ActionBar → DebugButton prop 接线守卫(病因学守卫):
4
+ * 会话 β(31de86f3)删除 conversationId prop 行零红灯复发——本测试锁定
5
+ * message.requestId/conversationId 恒透传至 DebugButton(删除任一 prop 行 → 红)。
6
+ * 捕获式 mock(MessageBubble 测试同款模式)。
7
+ */
8
+ import { act } from 'react';
9
+ import { createRoot } from 'react-dom/client';
10
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
11
+ import type { ChatMessage } from '../../types';
12
+
13
+ const { debugPropsRef } = vi.hoisted(() => ({
14
+ debugPropsRef: {} as { current?: Record<string, unknown> },
15
+ }));
16
+
17
+ vi.mock('./DebugButton', () => ({
18
+ DebugButton: (props: Record<string, unknown>) => {
19
+ debugPropsRef.current = props;
20
+ return null;
21
+ },
22
+ }));
23
+ vi.mock('../../store-context', () => ({
24
+ useChatStore: (selector: (s: Record<string, unknown>) => unknown) =>
25
+ selector({ submitFeedback: vi.fn() }),
26
+ }));
27
+ vi.mock('../../chat-config', () => ({
28
+ useChatConfigStore: (selector: (s: Record<string, unknown>) => unknown) => selector({ enableTTS: false }),
29
+ }));
30
+ vi.mock('@tbox.cn/app-agent-sdk-client', () => ({
31
+ createLogger: () => ({ warn: vi.fn() }),
32
+ useFeedbackAdapter: () => undefined,
33
+ useRefreshSession: () => undefined,
34
+ useTTSAdapter: () => undefined,
35
+ }));
36
+ vi.mock('../../utils/copyText', () => ({ copyText: vi.fn(async () => true) }));
37
+ vi.mock('../../utils/toast', () => ({ toast: vi.fn() }));
38
+
39
+ import { ActionBar } from './index';
40
+
41
+ const doneMessage = (over: Partial<ChatMessage> = {}): ChatMessage => ({
42
+ id: 'm1',
43
+ role: 'assistant',
44
+ content: '答案',
45
+ status: 'done',
46
+ createdAt: 1,
47
+ ...over,
48
+ });
49
+
50
+ describe('ActionBar → DebugButton 接线(病因学守卫)', () => {
51
+ let host: HTMLDivElement;
52
+ let root: ReturnType<typeof createRoot>;
53
+
54
+ beforeEach(() => {
55
+ host = document.createElement('div');
56
+ document.body.appendChild(host);
57
+ root = createRoot(host);
58
+ debugPropsRef.current = undefined;
59
+ });
60
+
61
+ afterEach(() => {
62
+ act(() => root.unmount());
63
+ host.remove();
64
+ });
65
+
66
+ it('A1 done 消息:requestId + conversationId 均透传(删除任一 prop 行 → 红)', () => {
67
+ act(() => {
68
+ root.render(<ActionBar message={doneMessage({ requestId: 'req_1', conversationId: 'conv_1' })} />);
69
+ });
70
+ expect(debugPropsRef.current).toMatchObject({
71
+ requestId: 'req_1',
72
+ conversationId: 'conv_1',
73
+ messageId: 'm1',
74
+ });
75
+ });
76
+
77
+ it('A2 字段缺席:prop 透传 undefined(不抛错、按钮层自守卫)', () => {
78
+ act(() => {
79
+ root.render(<ActionBar message={doneMessage({ requestId: 'req_1' })} />);
80
+ });
81
+ expect(debugPropsRef.current).toMatchObject({ requestId: 'req_1', conversationId: undefined });
82
+ });
83
+ });
@@ -0,0 +1,158 @@
1
+ import { useEffect, useState, useSyncExternalStore } from 'react';
2
+ import { createLogger } from '@tbox.cn/app-agent-sdk-client';
3
+
4
+ const ttsActionLogger = createLogger('tts');
5
+ import { Copy, SpeakerHigh, ThumbsDown, ThumbsUp } from '@phosphor-icons/react';
6
+ import { useChatStore } from '../../store-context';
7
+ import { useChatConfigStore } from '../../chat-config';
8
+ import { useFeedbackAdapter, useRefreshSession, useTTSAdapter } from '@tbox.cn/app-agent-sdk-client';
9
+ import type { ChatMessage } from '../../types';
10
+ import { copyText } from '../../utils/copyText';
11
+ import { toast } from '../../utils/toast';
12
+ import { DebugButton } from './DebugButton';
13
+
14
+ /**
15
+ * 跨所有 ActionBar 实例共享的"正在朗读的消息 id"(对齐原模板 useTTS 的 _playingId)。
16
+ * 保证同一时刻只有发起朗读的那条消息按钮显示波纹/暂停态,切到另一条会自动复位前一条。
17
+ */
18
+ let _playingId: string | null = null;
19
+ const _playingIdListeners = new Set<() => void>();
20
+ const getPlayingId = () => _playingId;
21
+ function subscribePlayingId(cb: () => void) {
22
+ _playingIdListeners.add(cb);
23
+ return () => {
24
+ _playingIdListeners.delete(cb);
25
+ };
26
+ }
27
+ function setPlayingId(id: string | null) {
28
+ if (_playingId === id) return;
29
+ _playingId = id;
30
+ _playingIdListeners.forEach((cb) => cb());
31
+ }
32
+ /** play() 同步执行期间为 true,防止切歌瞬间 adapter 的 idle 事件误清 playingId */
33
+ let _isPlaying = false;
34
+
35
+ /** 助手消息操作栏(对齐原模板):朗读(TTS) + 复制 + 赞 + 踩。 */
36
+ export function getMessageCopyText(message: ChatMessage): string {
37
+ return [message.content, message.error].filter(Boolean).join('\n\n');
38
+ }
39
+
40
+ export function CopyButton({ text }: { text: string }) {
41
+ const copy = async () => {
42
+ const copied = await copyText(text);
43
+ void toast(copied ? '复制成功' : '复制失败,请重试', copied ? 'success' : 'error');
44
+ };
45
+
46
+ return (
47
+ <button type="button" className="tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-white p-0 text-muted-foreground transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted" onClick={copy} aria-label="复制">
48
+ <span className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
49
+ <Copy size={22} />
50
+ </span>
51
+ </button>
52
+ );
53
+ }
54
+
55
+ export function ActionBar({ message }: { message: ChatMessage }) {
56
+ const feedback = useFeedbackAdapter();
57
+ const refreshSession = useRefreshSession();
58
+ const tts = useTTSAdapter();
59
+ const enableTTS = useChatConfigStore((s) => s.enableTTS);
60
+ const submitFeedback = useChatStore((s) => s.submitFeedback);
61
+
62
+ const [ttsState, setTtsState] = useState<'idle' | 'loading' | 'playing' | 'paused'>('idle');
63
+ // 是否轮到本条消息:由共享 playingId 决定(而非各自的本地 state),实现跨实例互斥高亮
64
+ const playingId = useSyncExternalStore(subscribePlayingId, getPlayingId);
65
+ const isMine = playingId === message.id;
66
+ useEffect(() => {
67
+ if (!tts) return;
68
+ return (
69
+ tts.onStateChange((s) => {
70
+ setTtsState(s);
71
+ // 播放自然结束 → 清空全局播放态;_isPlaying 守卫避免切歌瞬间的 idle 误清
72
+ if (s === 'idle' && !_isPlaying) setPlayingId(null);
73
+ }) || undefined
74
+ );
75
+ }, [tts]);
76
+
77
+ const onFeedback = (type: 'like' | 'dislike') => {
78
+ if (!feedback) return;
79
+ const next = message.feedbackState === type ? 'cancel' : type;
80
+ submitFeedback(message.id, next, feedback, refreshSession);
81
+ };
82
+
83
+ const wave = isMine && (ttsState === 'loading' || ttsState === 'playing');
84
+ // 对齐原模板 TTSButton:播放/加载中点击→暂停;暂停中点击→恢复;其余→从头播放
85
+ const onTts = () => {
86
+ if (!tts) return;
87
+ if (isMine) {
88
+ if (ttsState === 'playing' || ttsState === 'loading') {
89
+ tts.pause();
90
+ return;
91
+ }
92
+ if (ttsState === 'paused') {
93
+ tts.resume();
94
+ return;
95
+ }
96
+ }
97
+ _isPlaying = true;
98
+ setPlayingId(message.id);
99
+ tts.speak(message.content, message.id).catch((err: unknown) => {
100
+ ttsActionLogger.warn(`tts.speak 失败:err=${(err as Error)?.message ?? String(err)}`);
101
+ setPlayingId(null);
102
+ });
103
+ _isPlaying = false;
104
+ };
105
+
106
+ // 显示依据 requestId(server 下发、不依赖 session);提交时若无 feedback 适配器则 onFeedback 内部 no-op
107
+ const canFeedback = !!message.requestId;
108
+
109
+ return (
110
+ <div className="tbox-action-bar flex items-center gap-2">
111
+ {enableTTS && tts && (
112
+ <div className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${wave ? ' tbox-tts-btn--playing bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`} onClick={onTts}>
113
+ {wave ? (
114
+ <div className="tbox-tts-wave flex size-[14px] items-center justify-center gap-[1.5px]">
115
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--1 h-[7px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0s]" />
116
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--2 h-[9px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0.15s]" />
117
+ <div className="tbox-tts-wave__bar tbox-tts-wave__bar--3 h-[6px] w-[1.5px] origin-bottom rounded-full bg-primary animate-[tbox-tts-wave_0.8s_ease-in-out_infinite] [animation-delay:0.3s]" />
118
+ </div>
119
+ ) : (
120
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
121
+ <SpeakerHigh size={22} />
122
+ </div>
123
+ )}
124
+ </div>
125
+ )}
126
+
127
+ <CopyButton text={getMessageCopyText(message)} />
128
+
129
+ {canFeedback && (
130
+ <>
131
+ <div
132
+ className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${message.feedbackState === 'like' ? ' tbox-action-btn--active bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`}
133
+ onClick={() => onFeedback('like')}
134
+ >
135
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
136
+ <ThumbsUp size={22} />
137
+ </div>
138
+ </div>
139
+ <div
140
+ className={`tbox-action-btn flex size-[26px] shrink-0 cursor-pointer items-center justify-center rounded-full border-0 p-0 transition-[background-color,transform] duration-[var(--tbox-motion-duration-fast)] ease-[ease] [font-family:inherit] active:scale-[0.97] active:bg-muted ${message.feedbackState === 'dislike' ? ' tbox-action-btn--active bg-primary-foreground text-primary' : ' bg-white text-muted-foreground'}`}
141
+ onClick={() => onFeedback('dislike')}
142
+ >
143
+ <div className="tbox-action-btn__icon-wrap flex size-[14px] shrink-0 items-center justify-center">
144
+ <ThumbsDown size={22} />
145
+ </div>
146
+ </div>
147
+ </>
148
+ )}
149
+
150
+ <DebugButton
151
+ requestId={message.requestId}
152
+ conversationId={message.conversationId}
153
+ messageId={message.id}
154
+ messageCreatedAt={new Date(message.createdAt).getTime()}
155
+ />
156
+ </div>
157
+ );
158
+ }
@@ -0,0 +1,97 @@
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, preloadBottomSheet } 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
+ document.body.style.overflow = '';
14
+ });
15
+
16
+ async function renderSheet(open: boolean, onClose = vi.fn()) {
17
+ if (!root) {
18
+ const container = document.createElement('div');
19
+ document.body.append(container);
20
+ root = createRoot(container);
21
+ }
22
+ await act(async () => {
23
+ root!.render(<BottomSheet open={open} title="奖品详情" onClose={onClose}>
24
+ <button type="button">内容操作</button>
25
+ </BottomSheet>);
26
+ });
27
+ return onClose;
28
+ }
29
+
30
+ describe('BottomSheet', () => {
31
+ it('关闭态不挂载内容;打开通过 portal 展示命名对话框和业务内容', async () => {
32
+ await renderSheet(false);
33
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
34
+ await renderSheet(true);
35
+ const dialog = document.querySelector('[role="dialog"]') as HTMLElement;
36
+ expect(dialog).not.toBeNull();
37
+ expect(dialog.getAttribute('aria-modal')).toBe('true');
38
+ // portal 到 body 直接子节点(不在 React 容器里)
39
+ expect(document.body.contains(dialog)).toBe(true);
40
+ expect(document.getElementById(dialog.getAttribute('aria-labelledby')!)?.textContent).toBe('奖品详情');
41
+ expect(dialog.textContent).toContain('内容操作');
42
+ });
43
+
44
+ it('关闭按钮与 Escape 请求受控关闭,卸载后恢复触发按钮焦点并清理监听', async () => {
45
+ const trigger = document.createElement('button');
46
+ document.body.append(trigger);
47
+ trigger.focus();
48
+ const onClose = await renderSheet(true);
49
+ await act(async () => {
50
+ (document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement).click();
51
+ });
52
+ expect(onClose).toHaveBeenCalledTimes(1);
53
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));
54
+ expect(onClose).toHaveBeenCalledTimes(2);
55
+ await act(async () => root?.unmount());
56
+ root = undefined;
57
+ expect(document.activeElement).toBe(trigger);
58
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
59
+ expect(onClose).toHaveBeenCalledTimes(2);
60
+ });
61
+
62
+ it('Tab 与 Shift+Tab 在弹层内循环,不落到背景页面', async () => {
63
+ await renderSheet(true);
64
+ const close = document.querySelector('[aria-label="关闭奖品详情"]') as HTMLButtonElement;
65
+ const last = document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement;
66
+ last.focus();
67
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', cancelable: true }));
68
+ expect(document.activeElement).toBe(close);
69
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, cancelable: true }));
70
+ expect(document.activeElement).toBe(last);
71
+ });
72
+
73
+ it('遮罩点击请求关闭,内容点击不关闭;打开时锁背景滚动', async () => {
74
+ const onClose = await renderSheet(true);
75
+ expect(document.body.style.overflow).toBe('hidden');
76
+ await act(async () => (document.querySelector('.tbox-bottom-sheet__body button') as HTMLButtonElement).click());
77
+ expect(onClose).not.toHaveBeenCalled();
78
+ await act(async () => (document.querySelector('[data-tbox-overlay-mask]') as HTMLElement).click());
79
+ expect(onClose).toHaveBeenCalledTimes(1);
80
+ });
81
+
82
+ it('关闭后播完退出动画再卸载,且退出期间不再是对话框', async () => {
83
+ await renderSheet(true);
84
+ await renderSheet(false);
85
+ const rootEl = document.querySelector('[data-tbox-overlay]') as HTMLElement;
86
+ expect(rootEl.getAttribute('data-state')).toBe('closed');
87
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
88
+ await act(async () => {
89
+ rootEl.dispatchEvent(new Event('animationend', { bubbles: true }));
90
+ });
91
+ expect(document.querySelector('[data-tbox-overlay]')).toBeNull();
92
+ });
93
+
94
+ it('预热入口保留为空操作(旧模块的 typeof 守卫仍需可用)', async () => {
95
+ await expect(preloadBottomSheet()).resolves.toBeUndefined();
96
+ });
97
+ });
@@ -0,0 +1,49 @@
1
+ import { useId, useRef } from 'react';
2
+ import type { ReactNode } from 'react';
3
+ import { Overlay } from '../../overlay';
4
+
5
+ export interface BottomSheetProps {
6
+ open: boolean;
7
+ title: string;
8
+ onClose: () => void;
9
+ children: ReactNode;
10
+ /** 内容容器的业务样式;弹层外壳由组件统一管理。 */
11
+ className?: string;
12
+ }
13
+
14
+ /**
15
+ * 兼容旧宿主的预热入口:弹层已无第三方运行时,恒立即完成。
16
+ * 保留导出是为了让已发布的旧模块(`typeof preloadBottomSheet === 'function'` 守卫)不报错。
17
+ * @deprecated 弹层不再懒加载,无需预热。
18
+ */
19
+ export async function preloadBottomSheet(): Promise<void> {}
20
+
21
+ /** 受控底部弹层:业务只提供内容与开关,不自行处理遮罩、滚动和焦点。 */
22
+ export function BottomSheet({ open, title, onClose, children, className }: BottomSheetProps) {
23
+ const titleId = useId();
24
+ const closeRef = useRef<HTMLButtonElement>(null);
25
+
26
+ return (
27
+ <Overlay
28
+ open={open}
29
+ onDismiss={onClose}
30
+ placement="bottom"
31
+ labelledBy={titleId}
32
+ initialFocus={closeRef}
33
+ exitMs={200}
34
+ rootClassName="tbox-bottom-sheet-root group"
35
+ panelClassName="tbox-bottom-sheet tbox-bottom-sheet__panel flex max-h-[65vh] w-full max-w-content flex-col overflow-hidden rounded-t-[14px] bg-card text-foreground supports-[height:100dvh]:max-h-[65dvh] animate-[tbox-sheet-in_200ms_ease-out] group-data-[state=closed]:animate-[tbox-sheet-out_200ms_ease-in_both] motion-reduce:animate-none"
36
+ maskClassName="bg-scrim animate-[tbox-fade-in_200ms_ease-out] group-data-[state=closed]:animate-[tbox-fade-out_200ms_ease-in_both] motion-reduce:animate-none"
37
+ >
38
+ <header className="tbox-bottom-sheet__header flex shrink-0 items-center justify-between gap-3 px-3.5 py-3">
39
+ <h2 id={titleId} className="m-0 text-base font-semibold leading-[21px]">{title}</h2>
40
+ <button className="flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-1.5 text-inherit focus-visible:outline-2 focus-visible:outline-primary" ref={closeRef} type="button" aria-label={`关闭${title}`} onClick={onClose}>
41
+ <svg className="size-4.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true">
42
+ <path d="m6 6 12 12M6 18 18 6" />
43
+ </svg>
44
+ </button>
45
+ </header>
46
+ <div className={['tbox-bottom-sheet__body min-h-0 overflow-y-auto overscroll-contain px-3.5 pt-0 pb-[calc(16px+env(safe-area-inset-bottom))] text-sm leading-[19px]', className].filter(Boolean).join(' ')}>{children}</div>
47
+ </Overlay>
48
+ );
49
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 卡片渲染入口(kit 版,自 mall 模板 cards/CardRenderer.tsx 迁入):
3
+ * 注入 context 提供的注册表后委托 SDK 的 CardRenderer;
4
+ * 动作按钮 → 注入 store 的 sendUiAction(token 来自 payload.actionTokens)。
5
+ *
6
+ * - CardRenderer:聊天入口(组合层覆盖注册表 cards);
7
+ * - RawCardRenderer:原始形态(rawCards,无覆盖)——首页详情弹层 body 等防嵌套入口。
8
+ */
9
+ import { CardRenderer as SdkCardRenderer } from '@tbox.cn/app-agent-sdk-client';
10
+ import type { TboxCardPayload, UiAction } from '@tbox.cn/app-contracts';
11
+ import { useChatCards, useChatRawCards, useChatStore } from '../store-context';
12
+
13
+ export function CardRenderer({ card }: { card: TboxCardPayload }) {
14
+ const sendUiAction = useChatStore((s) => s.sendUiAction);
15
+ const cards = useChatCards();
16
+ return (
17
+ <SdkCardRenderer
18
+ card={card}
19
+ registry={cards}
20
+ onAction={(action: UiAction) => sendUiAction(card.id, action)}
21
+ />
22
+ );
23
+ }
24
+
25
+ /** 原始形态渲染(无组合层覆盖):详情弹层 body 专用——弹层自身已提供 hero+主题容器 */
26
+ export function RawCardRenderer({ card }: { card: TboxCardPayload }) {
27
+ const sendUiAction = useChatStore((s) => s.sendUiAction);
28
+ const rawCards = useChatRawCards();
29
+ return (
30
+ <SdkCardRenderer
31
+ card={card}
32
+ registry={rawCards}
33
+ onAction={(action: UiAction) => sendUiAction(card.id, action)}
34
+ />
35
+ );
36
+ }
@@ -0,0 +1,74 @@
1
+ // @vitest-environment happy-dom
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { createRoot } from 'react-dom/client';
4
+ import { flushSync } from 'react-dom';
5
+ import ChatHeader from './index';
6
+
7
+ interface MockChatState {
8
+ helloAck: { mallScope?: Record<string, string> } | null;
9
+ }
10
+
11
+ let mockHelloAck: MockChatState['helloAck'] = null;
12
+
13
+ vi.mock('../../store-context', () => ({
14
+ useChatStore: (selector: (s: MockChatState) => unknown) =>
15
+ selector({ helloAck: mockHelloAck }),
16
+ }));
17
+
18
+ vi.mock('../../chat-config', () => ({
19
+ useChatConfigStore: (selector: (s: { enableTTS: boolean }) => unknown) =>
20
+ selector({ enableTTS: false }),
21
+ }));
22
+
23
+ function renderHeader(container: HTMLDivElement) {
24
+ flushSync(() => {
25
+ createRoot(container).render(
26
+ <ChatHeader ttsAutoPlay={false} onToggleTTS={() => {}} onClearChat={() => {}} />,
27
+ );
28
+ });
29
+ }
30
+
31
+ describe('ChatHeader 品牌区(014 T7:mallScope.mallName 驱动,非 mall 部署降级)', () => {
32
+ beforeEach(() => {
33
+ mockHelloAck = null;
34
+ });
35
+
36
+ it('有 mallScope.mallName → 渲染品牌区(mark + mallName)', () => {
37
+ mockHelloAck = { mallScope: { mallId: 'mall-demo', mallName: '示例商场' } };
38
+ const container = document.createElement('div');
39
+ document.body.appendChild(container);
40
+ try {
41
+ renderHeader(container);
42
+ const brand = container.querySelector('.chat-header__brand');
43
+ expect(brand).not.toBeNull();
44
+ expect(brand?.textContent).toContain('示例商场');
45
+ expect(brand?.getAttribute('aria-label')).toBe('示例商场');
46
+ } finally {
47
+ document.body.removeChild(container);
48
+ }
49
+ });
50
+
51
+ it('无 mallScope(非 mall 部署)→ 不渲染品牌区', () => {
52
+ mockHelloAck = null;
53
+ const container = document.createElement('div');
54
+ document.body.appendChild(container);
55
+ try {
56
+ renderHeader(container);
57
+ expect(container.querySelector('.chat-header__brand')).toBeNull();
58
+ } finally {
59
+ document.body.removeChild(container);
60
+ }
61
+ });
62
+
63
+ it('mallScope 缺 mallName → 不渲染品牌区(回显不完整降级)', () => {
64
+ mockHelloAck = { mallScope: { mallId: 'mall-demo' } };
65
+ const container = document.createElement('div');
66
+ document.body.appendChild(container);
67
+ try {
68
+ renderHeader(container);
69
+ expect(container.querySelector('.chat-header__brand')).toBeNull();
70
+ } finally {
71
+ document.body.removeChild(container);
72
+ }
73
+ });
74
+ });
@@ -0,0 +1,77 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { CaretDown, SpeakerHigh, SpeakerSlash, Trash } from '@phosphor-icons/react';
3
+ import { useChatConfigStore } from '../../chat-config';
4
+ import { useChatStore } from '../../store-context';
5
+
6
+ interface ChatHeaderProps {
7
+ ttsAutoPlay: boolean;
8
+ onToggleTTS: () => void;
9
+ onClearChat: () => void;
10
+ }
11
+
12
+ export default function ChatHeader({ ttsAutoPlay, onToggleTTS, onClearChat }: ChatHeaderProps) {
13
+ const [isExpanded, setIsExpanded] = useState(false);
14
+ const headerRef = useRef<HTMLDivElement>(null);
15
+ const enableTTS = useChatConfigStore((s) => s.enableTTS);
16
+ // 品牌名三级来源:chat.json identity.name → HELLO_ACK 的 mallName(商圈部署回显)→ 不渲染
17
+ const identity = useChatConfigStore((s) => s.identity);
18
+ const mallName = useChatStore((s) => s.helloAck?.mallScope?.mallName);
19
+ const brandName = identity?.name ?? mallName;
20
+
21
+ const handleClear = useCallback(() => {
22
+ onClearChat();
23
+ setIsExpanded(false);
24
+ }, [onClearChat]);
25
+
26
+ useEffect(() => {
27
+ if (!isExpanded || typeof document === 'undefined') return;
28
+ const onOutside = (e: Event) => {
29
+ if (headerRef.current && !headerRef.current.contains(e.target as Node)) setIsExpanded(false);
30
+ };
31
+ document.addEventListener('touchstart', onOutside, true);
32
+ document.addEventListener('mousedown', onOutside, true);
33
+ return () => {
34
+ document.removeEventListener('touchstart', onOutside, true);
35
+ document.removeEventListener('mousedown', onOutside, true);
36
+ };
37
+ }, [isExpanded]);
38
+
39
+ return (
40
+ <div className="chat-header pointer-events-none absolute left-1/2 top-[calc(5px+env(safe-area-inset-top,0px))] z-[100] flex w-full max-w-content -translate-x-1/2 flex-col items-end px-4" ref={headerRef}>
41
+ {brandName ? (
42
+ <div className="chat-header__brand absolute left-4 top-[2px] inline-flex min-h-[22px] items-center text-foreground" aria-label={brandName}>
43
+ <span className="chat-header__brand-mark mr-[7px] h-[17px] w-[3.5px] rounded-[1px] bg-primary" aria-hidden="true" />
44
+ <span className="chat-header__brand-name text-xs font-[760] leading-none tracking-normal">{brandName}</span>
45
+ {identity?.tagline ? <span className="chat-header__brand-tagline ml-[6px] overflow-hidden text-ellipsis whitespace-nowrap text-xs leading-none text-muted-foreground">{identity.tagline}</span> : null}
46
+ </div>
47
+ ) : null}
48
+ <div className={`chat-header__group flex items-center gap-[2px] overflow-hidden rounded-[6px] border-[0.5px] border-border bg-[rgba(255,255,255,0.96)] shadow-sm transition-[opacity,transform] motion-reduce:transition-none ${!isExpanded ? ' chat-header__group--collapsed pointer-events-none mb-0 max-h-0 px-[3px] py-0 opacity-0 [transform:translateY(-4px)]' : ' pointer-events-auto mb-[3px] max-h-10 px-[3px] py-[3px] opacity-100 [transform:translateY(0)]'}`}>
49
+ <button type="button" className="chat-header__btn inline-flex min-h-[26px] appearance-none items-center justify-center gap-[3.5px] rounded-[4px] border-0 bg-transparent px-[7.5px] py-0 text-secondary-foreground [font-family:inherit] active:bg-muted focus-visible:outline-[1.5px] focus-visible:outline-offset-[-1px] focus-visible:outline-[rgba(9,107,250,0.24)]" onClick={handleClear}>
50
+ <Trash size={22} className="chat-header__btn-icon size-[11px] shrink-0 text-primary" />
51
+ <span className="chat-header__btn-text text-inherit text-xs font-[560] leading-none whitespace-nowrap">清空</span>
52
+ </button>
53
+ {enableTTS && (
54
+ <button type="button" className="chat-header__btn inline-flex min-h-[26px] appearance-none items-center justify-center gap-[3.5px] rounded-[4px] border-0 bg-transparent px-[7.5px] py-0 text-secondary-foreground [font-family:inherit] active:bg-muted focus-visible:outline-[1.5px] focus-visible:outline-offset-[-1px] focus-visible:outline-[rgba(9,107,250,0.24)]" onClick={onToggleTTS}>
55
+ {ttsAutoPlay ? (
56
+ <SpeakerHigh size={22} className="chat-header__btn-icon size-[11px] shrink-0 text-primary" />
57
+ ) : (
58
+ <SpeakerSlash size={22} className="chat-header__btn-icon size-[11px] shrink-0 text-primary" />
59
+ )}
60
+ <span className="chat-header__btn-text text-inherit text-xs font-[560] leading-none whitespace-nowrap">{ttsAutoPlay ? '关闭' : '播放'}</span>
61
+ </button>
62
+ )}
63
+ </div>
64
+ <button
65
+ className="chat-header__toggle pointer-events-auto flex h-[22px] w-7 appearance-none items-center justify-center rounded-[4px] border-[0.5px] border-border bg-[rgba(255,255,255,0.92)] text-muted-foreground shadow-sm [font-family:inherit] active:bg-muted focus-visible:outline-[1.5px] focus-visible:outline-offset-[1px] focus-visible:outline-[rgba(9,107,250,0.24)]"
66
+ type="button"
67
+ aria-label={isExpanded ? '收起对话工具' : '展开对话工具'}
68
+ aria-expanded={isExpanded}
69
+ onClick={() => setIsExpanded((p) => !p)}
70
+ >
71
+ <span className={`chat-header__arrow flex items-center justify-center transition-transform duration-[var(--tbox-motion-duration-base)] ease-[var(--tbox-motion-easing-standard)] motion-reduce:transition-none ${isExpanded ? ' chat-header__arrow--up rotate-180' : ''}`}>
72
+ <CaretDown size={14} />
73
+ </span>
74
+ </button>
75
+ </div>
76
+ );
77
+ }