@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,156 @@
1
+ // @vitest-environment happy-dom
2
+ import { act } from 'react';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import { createRoot } from 'react-dom/client';
5
+ import type { VoiceInteractionState } from './voice/machine';
6
+
7
+ const mocks = vi.hoisted(() => ({
8
+ interactionState: 'idle' as VoiceInteractionState,
9
+ }));
10
+
11
+ vi.mock('@tbox.cn/app-agent-sdk-client', () => ({
12
+ isInAlipayShell: () => false,
13
+ useASRAdapter: () => undefined,
14
+ }));
15
+
16
+ vi.mock('../../hooks/useMediaUpload', () => ({
17
+ useMediaUpload: () => ({
18
+ items: [],
19
+ addFiles: vi.fn(),
20
+ addFromBridge: vi.fn(),
21
+ removeItem: vi.fn(),
22
+ retry: vi.fn(),
23
+ clear: vi.fn(),
24
+ uploading: false,
25
+ }),
26
+ }));
27
+
28
+ vi.mock('../../components/MediaList', () => ({ MediaList: () => null }));
29
+
30
+ vi.mock('./voice/useVoicePress', () => ({
31
+ useVoicePress: () => ({
32
+ interactionState: mocks.interactionState,
33
+ overlayVisible: mocks.interactionState !== 'idle',
34
+ countdown: null,
35
+ handlers: {
36
+ onTouchStart: vi.fn(),
37
+ onTouchMove: vi.fn(),
38
+ onTouchEnd: vi.fn(),
39
+ onTouchCancel: vi.fn(),
40
+ },
41
+ }),
42
+ }));
43
+
44
+ import { ChatInput } from './index';
45
+ import { useChatConfigStore } from '../../chat-config';
46
+
47
+ afterEach(() => {
48
+ mocks.interactionState = 'idle';
49
+ // 重置回构建期快照(对齐模板 config/chat.json 出厂值;派生矩阵用例经 setState 驱动水合模拟)
50
+ useChatConfigStore.setState({
51
+ enableImageUpload: false,
52
+ enableVideoUpload: false,
53
+ enableTTS: false,
54
+ enableVoiceInput: true,
55
+ defaultInputMode: 'TEXT',
56
+ });
57
+ document.body.innerHTML = '';
58
+ });
59
+
60
+ describe('ChatInput 语音活动状态', () => {
61
+ it('idle、识别中和结束时依次向页面投影 false、true、false', async () => {
62
+ const onVoiceActivityChange = vi.fn();
63
+ const container = document.createElement('div');
64
+ document.body.appendChild(container);
65
+ const root = createRoot(container);
66
+ const render = () => root.render(
67
+ <ChatInput onSend={vi.fn()} onVoiceActivityChange={onVoiceActivityChange} />,
68
+ );
69
+
70
+ await act(async () => render());
71
+ expect(onVoiceActivityChange).toHaveBeenLastCalledWith(false);
72
+
73
+ mocks.interactionState = 'processing';
74
+ await act(async () => render());
75
+ expect(onVoiceActivityChange).toHaveBeenLastCalledWith(true);
76
+
77
+ mocks.interactionState = 'idle';
78
+ await act(async () => render());
79
+ expect(onVoiceActivityChange).toHaveBeenLastCalledWith(false);
80
+
81
+ await act(async () => root.unmount());
82
+ });
83
+ });
84
+
85
+ describe('ChatInput 派生模式(服务端 defaultInputMode 水合)', () => {
86
+ /** voice 态投影:录音模式的可访问名为「切换到键盘输入」;text 态为「切换到语音输入」 */
87
+ const inVoiceMode = (container: HTMLElement) =>
88
+ container.querySelector('.tbox-voice-toggle[aria-label="切换到键盘输入"]') !== null;
89
+
90
+ const renderInput = async (root: ReturnType<typeof createRoot>) => {
91
+ await act(async () => root.render(<ChatInput onSend={vi.fn()} />));
92
+ };
93
+
94
+ it('① voice 关 + defaultInputMode=VOICE → 强制 text(语音按钮隐藏)', async () => {
95
+ useChatConfigStore.setState({ enableVoiceInput: false, defaultInputMode: 'VOICE' });
96
+ const container = document.createElement('div');
97
+ document.body.appendChild(container);
98
+ const root = createRoot(container);
99
+ await renderInput(root);
100
+ expect(inVoiceMode(container)).toBe(false);
101
+ await act(async () => root.unmount());
102
+ });
103
+
104
+ it('② voice 开 + defaultInputMode=VOICE → 初始即 voice', async () => {
105
+ useChatConfigStore.setState({ enableVoiceInput: true, defaultInputMode: 'VOICE' });
106
+ const container = document.createElement('div');
107
+ document.body.appendChild(container);
108
+ const root = createRoot(container);
109
+ await renderInput(root);
110
+ expect(inVoiceMode(container)).toBe(true);
111
+ await act(async () => root.unmount());
112
+ });
113
+
114
+ it('③ 初值 TEXT 渲染后水合 VOICE → 派生自动转 voice(useState 捕获竞态修复)', async () => {
115
+ useChatConfigStore.setState({ enableVoiceInput: true, defaultInputMode: 'TEXT' });
116
+ const container = document.createElement('div');
117
+ document.body.appendChild(container);
118
+ const root = createRoot(container);
119
+ await renderInput(root);
120
+ expect(inVoiceMode(container)).toBe(false);
121
+ // 模拟 HELLO_ACK 晚到水合(服务端 defaultInputMode='VOICE')
122
+ useChatConfigStore.setState({ defaultInputMode: 'VOICE' });
123
+ await renderInput(root);
124
+ expect(inVoiceMode(container)).toBe(true);
125
+ await act(async () => root.unmount());
126
+ });
127
+
128
+ it('④ 用户手动切 text 后水合 VOICE 到达 → 显式选择优先,保持 text', async () => {
129
+ useChatConfigStore.setState({ enableVoiceInput: true, defaultInputMode: 'VOICE' });
130
+ const container = document.createElement('div');
131
+ document.body.appendChild(container);
132
+ const root = createRoot(container);
133
+ await renderInput(root);
134
+ expect(inVoiceMode(container)).toBe(true);
135
+ // 用户手动切回 text(voice 态的"键盘"切换钮——div 容器 onClick)
136
+ const keyboardToggle = container.querySelector<HTMLElement>('.tbox-voice-toggle')!;
137
+ await act(async () => keyboardToggle.click());
138
+ await renderInput(root);
139
+ expect(inVoiceMode(container)).toBe(false);
140
+ // 水合再次下发 VOICE(如重连回显)——用户显式选择仍优先
141
+ useChatConfigStore.setState({ defaultInputMode: 'VOICE' });
142
+ await renderInput(root);
143
+ expect(inVoiceMode(container)).toBe(false);
144
+ await act(async () => root.unmount());
145
+ });
146
+
147
+ it('⑤ voice 开 + defaultInputMode=TEXT → text', async () => {
148
+ useChatConfigStore.setState({ enableVoiceInput: true, defaultInputMode: 'TEXT' });
149
+ const container = document.createElement('div');
150
+ document.body.appendChild(container);
151
+ const root = createRoot(container);
152
+ await renderInput(root);
153
+ expect(inVoiceMode(container)).toBe(false);
154
+ await act(async () => root.unmount());
155
+ });
156
+ });
@@ -0,0 +1,295 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { useMediaUpload } from '../../hooks/useMediaUpload';
3
+ import { useASRAdapter, isInAlipayShell } from '@tbox.cn/app-agent-sdk-client';
4
+ import { useChatConfigStore } from '../../chat-config';
5
+
6
+ import type { ChatInputMessage, InputMethod } from '../../types';
7
+ import { MediaList } from '../../components/MediaList';
8
+ import { useVoicePress } from './voice/useVoicePress';
9
+ import { VoicePressField } from './voice/VoicePressField';
10
+ import { VoiceRecordingOverlay } from './voice/VoiceRecordingOverlay';
11
+ import newChatIcon from '../../../assets/new-chat.svg';
12
+ import voiceIcon from '../../../assets/voice-circle.svg';
13
+ import keyboardIcon from '../../../assets/keyboard-circle.svg';
14
+ import sendIcon from '../../../assets/send-gradient.svg';
15
+ import stopIcon from '../../../assets/stop@2x.png';
16
+ import moreIcon from '../../../assets/more-circle.svg';
17
+
18
+ type PickKind = 'image' | 'camera' | 'video';
19
+
20
+ /** 媒体选取菜单图标(远程素材,对齐原模板)。 */
21
+ const OPTION_ICONS: Record<PickKind, { icon: string; label: string }> = {
22
+ image: { icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*DfDhSYAMzoQAAAAAHiAAAAgAel-hAQ/original', label: '相册' },
23
+ camera: { icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*xdKLSabxqmQAAAAAOnAAAAgAel-hAQ/original', label: '拍摄' },
24
+ video: { icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*xdKLSabxqmQAAAAAOnAAAAgAel-hAQ/original', label: '视频' },
25
+ };
26
+
27
+ const MENU_ANIMATION_MS = 250;
28
+
29
+ /** 菜单展开时选项的错峰入场延迟(旧 less 的 `:nth-child(n)` transition-delay)。 */
30
+ const MENU_OPTION_DELAY_CLASS: Record<number, string> = {
31
+ 0: '[.tbox-media-picker-menu--visible_&]:[transition-delay:0.05s]',
32
+ 1: '[.tbox-media-picker-menu--visible_&]:[transition-delay:0.1s]',
33
+ 2: '[.tbox-media-picker-menu--visible_&]:[transition-delay:0.15s]',
34
+ };
35
+
36
+ /** 连接终态阻断(登录失败/scope 拒绝):提示条 + 输入禁用 + 可选重试入口 */
37
+ export interface ChatBlocked {
38
+ message: string;
39
+ onRetry?: () => void;
40
+ }
41
+
42
+ /** 媒体上传默认约束(分类型数量 + 单文件大小)。如需放开/收紧按业务改这里。 */
43
+ const DEFAULT_MEDIA_CONFIG = {
44
+ image: { maxCount: 9, maxSize: 10 * 1024 * 1024 },
45
+ video: { maxCount: 1, maxSize: 50 * 1024 * 1024 },
46
+ file: { maxCount: 5, maxSize: 20 * 1024 * 1024 },
47
+ } as const;
48
+ const MEDIA_MAX_TOTAL = 9;
49
+
50
+ /** 对话输入框(对齐原模板):媒体预览 + 新对话 + 药丸[输入框/按住说话 + 语音切换 + 发送/“+”] + 动画选取菜单 + 免责声明。 */
51
+ export function ChatInput({
52
+ generating,
53
+ blocked,
54
+ onSend,
55
+ onCancel,
56
+ onNewChat,
57
+ onVoiceActivityChange,
58
+ disclaimer = '以上内容由AI生成,请谨慎甄别。',
59
+ }: {
60
+ generating?: boolean;
61
+ blocked?: ChatBlocked;
62
+ onSend: (msg: ChatInputMessage) => void;
63
+ onCancel?: () => void;
64
+ onNewChat?: () => void;
65
+ onVoiceActivityChange?: (active: boolean) => void;
66
+ disclaimer?: string;
67
+ }) {
68
+ const [text, setText] = useState('');
69
+ const imageRef = useRef<HTMLInputElement>(null);
70
+ const cameraRef = useRef<HTMLInputElement>(null);
71
+ const videoRef = useRef<HTMLInputElement>(null);
72
+ const closeTimerRef = useRef<ReturnType<typeof setTimeout>>();
73
+ const { items, addFiles, addFromBridge, removeItem, retry, clear, uploading } = useMediaUpload(
74
+ MEDIA_MAX_TOTAL,
75
+ DEFAULT_MEDIA_CONFIG,
76
+ );
77
+ const asr = useASRAdapter();
78
+ const inShell = isInAlipayShell();
79
+ const enableImage = useChatConfigStore((s) => s.enableImageUpload);
80
+ const enableVideo = useChatConfigStore((s) => s.enableVideoUpload);
81
+ const enableVoice = useChatConfigStore((s) => s.enableVoiceInput);
82
+ const defaultInputMode = useChatConfigStore((s) => s.defaultInputMode);
83
+ // 派生模式(禁 useState 捕获初值——水合晚到时服务端 defaultInputMode 进不了已捕获 state):
84
+ // userMode=null 跟随默认(随水合重渲染更新);显式值 = 用户手动切换优先
85
+ const [userMode, setUserMode] = useState<'text' | 'voice' | null>(null);
86
+ const inputMode: 'text' | 'voice' =
87
+ !enableVoice ? 'text' : userMode ?? (defaultInputMode === 'VOICE' ? 'voice' : 'text');
88
+ const [menuVisible, setMenuVisible] = useState(false);
89
+ const [menuAnimating, setMenuAnimating] = useState(false);
90
+
91
+ const voice = useVoicePress({
92
+ disabled: generating || !!blocked,
93
+ asr,
94
+ onResult: (t) => onSend({ text: t, mediaItems: [], inputMethod: 'voice' }),
95
+ });
96
+ const voiceActive = voice.interactionState !== 'idle';
97
+
98
+ useEffect(() => {
99
+ onVoiceActivityChange?.(voiceActive);
100
+ }, [onVoiceActivityChange, voiceActive]);
101
+
102
+ useEffect(() => () => onVoiceActivityChange?.(false), [onVoiceActivityChange]);
103
+
104
+ const isWebPc = !inShell && typeof window !== 'undefined' && window.innerWidth > 450;
105
+
106
+ const pick = (kind: PickKind) => {
107
+ if (inShell) {
108
+ addFromBridge(kind);
109
+ return;
110
+ }
111
+ (kind === 'image' ? imageRef : kind === 'camera' ? cameraRef : videoRef).current?.click();
112
+ };
113
+
114
+ // 媒体选项:相册 / 拍摄(移动端)/ 视频,按 config 开关
115
+ const menuOptions = [
116
+ enableImage && { type: 'image' as const, ...OPTION_ICONS.image },
117
+ enableImage && !isWebPc && { type: 'camera' as const, ...OPTION_ICONS.camera },
118
+ enableVideo && { type: 'video' as const, ...OPTION_ICONS.video },
119
+ ].filter(Boolean) as { type: PickKind; icon: string; label: string }[];
120
+
121
+ const openMenu = () => {
122
+ setMenuVisible(true);
123
+ requestAnimationFrame(() => requestAnimationFrame(() => setMenuAnimating(true)));
124
+ };
125
+ const closeMenu = () => {
126
+ if (closeTimerRef.current) clearTimeout(closeTimerRef.current);
127
+ setMenuAnimating(false);
128
+ closeTimerRef.current = setTimeout(() => setMenuVisible(false), MENU_ANIMATION_MS);
129
+ };
130
+ const onPlus = () => {
131
+ if (menuVisible) return closeMenu();
132
+ if (menuOptions.length <= 1) return menuOptions[0] && pick(menuOptions[0].type);
133
+ openMenu();
134
+ };
135
+ const onMenuSelect = (kind: PickKind) => {
136
+ closeMenu();
137
+ pick(kind);
138
+ };
139
+
140
+ useEffect(() => {
141
+ if (!menuVisible) return;
142
+ const onDown = (e: MouseEvent | TouchEvent) => {
143
+ const t = e.target as HTMLElement;
144
+ if (t && !t.closest('.tbox-media-picker') && !t.closest('.tbox-media-picker-menu')) closeMenu();
145
+ };
146
+ document.addEventListener('mousedown', onDown);
147
+ document.addEventListener('touchstart', onDown, { passive: true });
148
+ return () => {
149
+ document.removeEventListener('mousedown', onDown);
150
+ document.removeEventListener('touchstart', onDown);
151
+ };
152
+ }, [menuVisible]);
153
+
154
+ useEffect(() => () => closeTimerRef.current && clearTimeout(closeTimerRef.current), []);
155
+
156
+ const canSend = !!(text.trim() || items.length > 0) && !uploading && inputMode === 'text' && !blocked;
157
+
158
+ const submit = () => {
159
+ if (!canSend) return;
160
+ const media = items.filter((it) => it.fileId && !it.illegal);
161
+ const inputMethod: InputMethod = media.length ? media[0].type : 'text';
162
+ onSend({ text: text.trim(), mediaItems: media, inputMethod });
163
+ setText('');
164
+ clear();
165
+ };
166
+
167
+ const onPickFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
168
+ addFiles(e.target.files ? Array.from(e.target.files) : []);
169
+ e.target.value = '';
170
+ };
171
+
172
+ const toggleMode = () => {
173
+ if (blocked) return;
174
+ setUserMode(inputMode === 'text' ? 'voice' : 'text');
175
+ };
176
+
177
+ return (
178
+ <div className="tbox-chat-input relative z-[1] mx-auto w-full max-w-content bg-transparent px-page pt-2 pb-[calc(8px+env(safe-area-inset-bottom,0px))]">
179
+ <MediaList
180
+ items={items}
181
+ onRemove={removeItem}
182
+ onRetry={retry}
183
+ onPickImage={() => pick('image')}
184
+ onPickCamera={() => pick('camera')}
185
+ onPickVideo={() => pick('video')}
186
+ enableImage={enableImage}
187
+ enableVideo={enableVideo}
188
+ isWebPc={isWebPc}
189
+ />
190
+
191
+ <div className="tbox-chat-input__row flex flex-wrap items-end gap-2">
192
+ {onNewChat && (
193
+ <button type="button" data-tbox-control="new-chat" aria-label="新建对话" className="tbox-new-chat-btn flex size-11 shrink-0 cursor-pointer appearance-none items-center justify-center rounded-full border-0 bg-[rgba(255,255,255,0.5)] p-0 shadow-[0_1px_10px_rgba(110,139,180,0.24)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onNewChat}>
194
+ <img className="tbox-new-chat-btn__icon size-[22px]" src={newChatIcon} alt="" />
195
+ </button>
196
+ )}
197
+
198
+ <div className="tbox-chat-input__wrapper flex min-w-0 flex-1 items-end gap-[14px] rounded-[var(--tbox-input-radius)] border border-border bg-[var(--tbox-input-bg)] p-[var(--tbox-input-padding)] shadow-[0_1px_10px_rgba(110,139,180,0.24)] transition-[border-color,box-shadow] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] focus-within:border-primary focus-within:shadow-[0_0_0_1.5px_rgba(9,107,250,0.12)]">
199
+ <input ref={imageRef} type="file" accept="image/*" multiple hidden onChange={onPickFiles} />
200
+ <input ref={cameraRef} type="file" accept="image/*" capture="environment" hidden onChange={onPickFiles} />
201
+ <input ref={videoRef} type="file" accept="video/*" hidden onChange={onPickFiles} />
202
+
203
+ {inputMode === 'voice' ? (
204
+ <VoicePressField
205
+ disabled={generating || !!blocked}
206
+ interactionState={voice.interactionState}
207
+ handlers={voice.handlers}
208
+ />
209
+ ) : (
210
+ <textarea
211
+ className="tbox-chat-input__field min-h-11 min-w-0 flex-1 resize-none border-0 bg-transparent p-0 text-base leading-[24px] text-foreground outline-none max-h-[100px] [font-family:inherit] placeholder:text-muted-foreground disabled:opacity-[0.45]"
212
+ value={text}
213
+ placeholder={blocked?.message ?? '有什么需要问我的吗'}
214
+ rows={1}
215
+ disabled={!!blocked}
216
+ onChange={(e) => setText(e.target.value)}
217
+ onKeyDown={(e) => {
218
+ if (e.key === 'Enter' && !e.shiftKey) {
219
+ e.preventDefault();
220
+ submit();
221
+ }
222
+ }}
223
+ />
224
+ )}
225
+
226
+ {enableVoice && (
227
+ <button type="button" data-tbox-control="voice-toggle" aria-label={inputMode === 'voice' ? '切换到键盘输入' : '切换到语音输入'} aria-pressed={inputMode === 'voice'} className="tbox-voice-toggle flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={toggleMode}>
228
+ <img
229
+ className="tbox-voice-toggle__icon size-[22px]"
230
+ src={inputMode === 'voice' ? keyboardIcon : voiceIcon}
231
+ alt=""
232
+ />
233
+ </button>
234
+ )}
235
+
236
+ {blocked ? null : generating ? (
237
+ <button type="button" data-tbox-control="stop" aria-label="停止生成" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={onCancel}>
238
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={stopIcon} alt="" />
239
+ </button>
240
+ ) : canSend ? (
241
+ <button type="button" data-tbox-control="send" aria-label="发送" className="tbox-chat-input__send tbox-chat-input__send--active flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary" onClick={submit}>
242
+ <img className="tbox-chat-input__send-img block size-[var(--tbox-send-btn-size)]" src={sendIcon} alt="" />
243
+ </button>
244
+ ) : menuOptions.length > 0 ? (
245
+ <div className="tbox-media-picker relative shrink-0">
246
+ <button
247
+ type="button"
248
+ data-tbox-control="media-add"
249
+ aria-label="添加图片或视频"
250
+ aria-haspopup="menu"
251
+ aria-expanded={menuVisible}
252
+ className={`tbox-media-picker__trigger flex size-11 -m-[11px] shrink-0 cursor-pointer appearance-none items-center justify-center border-0 bg-transparent p-0 transition-transform duration-[var(--tbox-motion-duration-base)] ease-[ease] ${menuVisible ? ' tbox-media-picker__trigger--open rotate-45' : ''}`}
253
+ onClick={onPlus}
254
+ >
255
+ <img className="tbox-media-picker__trigger-icon size-[var(--tbox-send-btn-size)]" src={moreIcon} alt="" />
256
+ </button>
257
+ </div>
258
+ ) : null}
259
+ </div>
260
+ {blocked && (
261
+ <div className="tbox-chat-input__blocked flex basis-full items-center gap-[6px] rounded-[6px] bg-[rgba(255,241,241,0.9)] px-[10px] py-[6px] text-xs leading-[16.8px] text-destructive">
262
+ <span className="tbox-chat-input__blocked-msg min-w-0 flex-1">{blocked.message}</span>
263
+ {blocked.onRetry && (
264
+ <button type="button" className="tbox-chat-input__blocked-retry shrink-0 rounded-full border-0 bg-primary px-[10px] py-[3px] text-xs leading-[normal] text-white [font-family:inherit]" onClick={blocked.onRetry}>
265
+ 重试
266
+ </button>
267
+ )}
268
+ </div>
269
+ )}
270
+ </div>
271
+
272
+ {menuVisible && (
273
+ <div className={`tbox-media-picker-menu mt-3 flex h-[66px] flex-row overflow-hidden transition-all will-change-[opacity,transform] ${menuAnimating ? ' tbox-media-picker-menu--visible [transform:translateY(0)] opacity-100 duration-[var(--tbox-motion-duration-base)] ease-out' : ' [transform:translateY(5px)] opacity-0 duration-[var(--tbox-motion-duration-fast)] ease-in'}`}>
274
+ {menuOptions.map((o, index) => (
275
+ <div key={o.type} className={`tbox-media-picker-menu__option flex h-[66px] w-28 shrink-0 items-center justify-center overflow-hidden rounded-[10px] bg-[rgba(0,0,0,0.04)] opacity-0 transition-all duration-[var(--tbox-motion-duration-base)] ease-out will-change-[opacity,transform] [.tbox-media-picker-menu--visible_&]:opacity-100 [.tbox-media-picker-menu--visible_&]:[transform:translateY(0)] ${MENU_OPTION_DELAY_CLASS[index] ?? ''} ${index > 0 ? ' ml-[7.5px]' : ''}`} onClick={() => onMenuSelect(o.type)}>
276
+ <div className="tbox-media-picker-menu__option-content flex h-6 flex-row items-center">
277
+ <img className="tbox-media-picker-menu__option-icon size-6 shrink-0" src={o.icon} alt="" />
278
+ <span className="tbox-media-picker-menu__option-label ml-1 text-sm font-normal leading-[18.5px] text-secondary-foreground">{o.label}</span>
279
+ </div>
280
+ </div>
281
+ ))}
282
+ </div>
283
+ )}
284
+
285
+ {disclaimer && <div className="tbox-chat-input__disclaimer mt-[5px] text-center text-xs leading-[15px] text-muted-foreground">{disclaimer}</div>}
286
+
287
+ <VoiceRecordingOverlay
288
+ visible={voice.overlayVisible}
289
+ interactionState={voice.interactionState}
290
+ countdown={voice.countdown}
291
+ handlers={voice.handlers}
292
+ />
293
+ </div>
294
+ );
295
+ }
@@ -0,0 +1,43 @@
1
+ import type { VoiceInteractionState } from './machine';
2
+ import type { VoicePressHandlers } from './useVoicePress';
3
+
4
+ /** 各交互态的按压条底色(旧 less 的 `--pressing` / `--recording-*` / `--processing` 规则)。 */
5
+ const FIELD_STATE_CLASS: Record<VoiceInteractionState, string> = {
6
+ idle: '',
7
+ pressing: 'bg-[#eef4ff]',
8
+ 'recording-active': 'bg-[#eef4ff]',
9
+ 'recording-cancel': 'bg-[#fff1f1]',
10
+ processing: 'bg-[#f5f7fb]',
11
+ };
12
+
13
+ function fieldText(s: VoiceInteractionState): string {
14
+ if (s === 'recording-cancel') return '松开取消';
15
+ if (s === 'processing') return '识别中...';
16
+ if (s === 'pressing' || s === 'recording-active') return '松开转文字';
17
+ return '按住说话';
18
+ }
19
+
20
+ /** “按住说话”输入条(替代文本框,语音模式下显示)。 */
21
+ export function VoicePressField({
22
+ disabled,
23
+ interactionState,
24
+ handlers,
25
+ }: {
26
+ disabled?: boolean;
27
+ interactionState: VoiceInteractionState;
28
+ handlers: VoicePressHandlers;
29
+ }) {
30
+ return (
31
+ <div
32
+ className={`tbox-voice-press-field tbox-voice-press-field--${interactionState} flex h-6 min-w-0 flex-1 touch-none select-none items-center justify-center overflow-hidden rounded-[25px] [-webkit-touch-callout:none] ${FIELD_STATE_CLASS[interactionState]} ${disabled ? ' tbox-voice-press-field--disabled opacity-[0.35]' : ''}`}
33
+ onTouchStart={disabled ? undefined : handlers.onTouchStart}
34
+ onTouchMove={disabled ? undefined : handlers.onTouchMove}
35
+ onTouchEnd={disabled ? undefined : handlers.onTouchEnd}
36
+ onTouchCancel={disabled ? undefined : handlers.onTouchCancel}
37
+ >
38
+ <div className="tbox-voice-press-field__content flex w-full items-center justify-center px-[10px]">
39
+ <span className="tbox-voice-press-field__text text-base font-semibold leading-[24px] text-foreground">{fieldText(interactionState)}</span>
40
+ </div>
41
+ </div>
42
+ );
43
+ }
@@ -0,0 +1,51 @@
1
+ import type { VoiceInteractionState } from './machine';
2
+ import type { VoicePressHandlers } from './useVoicePress';
3
+
4
+ function overlayTip(s: VoiceInteractionState): string {
5
+ if (s === 'recording-cancel') return '松开取消';
6
+ if (s === 'processing') return '识别中...';
7
+ return '松手发送,上移取消';
8
+ }
9
+
10
+ /** 录音全屏浮层(按压期间显示)。 */
11
+ export function VoiceRecordingOverlay({
12
+ visible,
13
+ interactionState,
14
+ countdown,
15
+ handlers,
16
+ }: {
17
+ visible: boolean;
18
+ interactionState: VoiceInteractionState;
19
+ countdown?: number | null;
20
+ handlers: VoicePressHandlers;
21
+ }) {
22
+ if (!visible) return null;
23
+ const isCancel = interactionState === 'recording-cancel';
24
+
25
+ return (
26
+ <div className="tbox-voice-overlay fixed inset-0 z-[300] touch-none select-none [-webkit-touch-callout:none]">
27
+ <div className="tbox-voice-overlay__mask absolute inset-0 bg-[rgba(255,255,255,0.01)]" />
28
+ <div
29
+ className="tbox-voice-overlay__capture absolute inset-0 flex touch-none select-none items-end justify-center px-page pb-[calc(28px+env(safe-area-inset-bottom,8px))] [-webkit-touch-callout:none]"
30
+ onTouchStart={handlers.onTouchStart}
31
+ onTouchMove={handlers.onTouchMove}
32
+ onTouchEnd={handlers.onTouchEnd}
33
+ onTouchCancel={handlers.onTouchCancel}
34
+ >
35
+ <div className="tbox-voice-overlay__panel flex w-full max-w-content flex-col items-center">
36
+ {countdown != null && interactionState === 'recording-active' && (
37
+ <div className="tbox-voice-overlay__bubble mb-5 flex h-[41px] w-[134px] items-center justify-center bg-no-repeat [background-image:url('https://mdn.alipayobjects.com/huamei\_frp8ut/afts/img/A*O6TCSrNeWvwAAAAAQHAAAAgAet-KAQ/original')] [background-size:100%_100%]">
38
+ <span className="tbox-voice-overlay__bubble-text whitespace-nowrap text-xs font-medium leading-[31px] text-white">{countdown}秒后自动停止录音</span>
39
+ </div>
40
+ )}
41
+ <span className={`tbox-voice-overlay__tip mb-4 text-center text-xs font-medium leading-[24px] ${isCancel ? ' tbox-voice-overlay__tip--cancel text-destructive' : ' text-muted-foreground'}`}>
42
+ {overlayTip(interactionState)}
43
+ </span>
44
+ <div className={`tbox-voice-overlay__button flex h-[50px] w-full items-center justify-center rounded-[26px] shadow-[0_6px_14px_rgba(80,111,255,0.24)] ${isCancel ? ' tbox-voice-overlay__button--cancel [background-image:linear-gradient(162deg,#fd3030_-22%,#f48686_108%)]' : ' [background-image:linear-gradient(162deg,var(--tbox-primary)_-22%,var(--tbox-primary-dark)_108%)]'}`}>
45
+ <div className="tbox-voice-overlay__wave pointer-events-none h-6 w-[242px] bg-no-repeat [background-image:url('https://mdn.alipayobjects.com/huamei\_frp8ut/afts/img/A*5PDvR4j7fBgAAAAAVBAAAAgAet-KAQ/original')] [background-size:100%_100%]" />
46
+ </div>
47
+ </div>
48
+ </div>
49
+ </div>
50
+ );
51
+ }
@@ -0,0 +1,27 @@
1
+ /** 语音按压交互状态机(纯逻辑,移植自原模板 voice-interaction-machine)。 */
2
+ export type VoiceInteractionState =
3
+ | 'idle'
4
+ | 'pressing'
5
+ | 'recording-active'
6
+ | 'recording-cancel'
7
+ | 'processing';
8
+
9
+ export type VoiceReleaseAction = 'stop' | 'cancel' | 'noop';
10
+
11
+ export const CANCEL_GESTURE_THRESHOLD = 25;
12
+
13
+ /** 按压中上滑超过阈值 → 取消态,否则录音态 */
14
+ export function getMoveInteractionState(
15
+ startClientY: number,
16
+ currentClientY: number,
17
+ threshold = CANCEL_GESTURE_THRESHOLD,
18
+ ): VoiceInteractionState {
19
+ return startClientY - currentClientY > threshold ? 'recording-cancel' : 'recording-active';
20
+ }
21
+
22
+ /** 松手动作:取消 / 停止(转文字) / 无操作 */
23
+ export function getReleaseAction(state: VoiceInteractionState): VoiceReleaseAction {
24
+ if (state === 'recording-cancel') return 'cancel';
25
+ if (state === 'pressing' || state === 'recording-active') return 'stop';
26
+ return 'noop';
27
+ }