@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.
- package/LICENSE +21 -0
- package/README.md +69 -2
- package/assets/keyboard-circle.svg +12 -0
- package/assets/more-circle.svg +3 -0
- package/assets/new-chat.svg +3 -0
- package/assets/quick-command-star.svg +3 -0
- package/assets/send-gradient.svg +14 -0
- package/assets/stop@2x.png +0 -0
- package/assets/voice-circle.svg +3 -0
- package/package.json +70 -3
- package/src/ChatPage.tsx +400 -0
- package/src/card/action-list-pending.test.tsx +91 -0
- package/src/card/define-card.test.ts +25 -0
- package/src/card/define-card.ts +47 -0
- package/src/card/primitives.test.tsx +157 -0
- package/src/card/primitives.tsx +717 -0
- package/src/card/use-card-actions.ts +86 -0
- package/src/card/view-card-inline.test.tsx +42 -0
- package/src/card/view-card.test.tsx +79 -0
- package/src/card/view-card.tsx +250 -0
- package/src/chat-config.test.ts +46 -0
- package/src/chat-config.ts +84 -0
- package/src/components/ActionBar/DebugButton.test.tsx +87 -0
- package/src/components/ActionBar/DebugButton.tsx +48 -0
- package/src/components/ActionBar/index.test.tsx +83 -0
- package/src/components/ActionBar/index.tsx +158 -0
- package/src/components/BottomSheet/index.test.tsx +97 -0
- package/src/components/BottomSheet/index.tsx +49 -0
- package/src/components/CardRenderer.tsx +36 -0
- package/src/components/ChatHeader/index.test.tsx +74 -0
- package/src/components/ChatHeader/index.tsx +77 -0
- package/src/components/ChatInput/index.test.tsx +156 -0
- package/src/components/ChatInput/index.tsx +295 -0
- package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
- package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
- package/src/components/ChatInput/voice/machine.ts +27 -0
- package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
- package/src/components/HistoryEntry/index.tsx +42 -0
- package/src/components/MediaList/index.tsx +270 -0
- package/src/components/MessageBubble/index.test.tsx +134 -0
- package/src/components/MessageBubble/index.tsx +208 -0
- package/src/components/PullDownIndicator/index.tsx +31 -0
- package/src/components/QuickCommands/index.test.tsx +101 -0
- package/src/components/QuickCommands/index.tsx +75 -0
- package/src/components/ReasoningBlock/index.tsx +61 -0
- package/src/components/ScrollToBottomButton/index.tsx +12 -0
- package/src/components/ToolCallBlock/detail.test.ts +346 -0
- package/src/components/ToolCallBlock/detail.ts +204 -0
- package/src/components/ToolCallBlock/index.test.tsx +261 -0
- package/src/components/ToolCallBlock/index.tsx +232 -0
- package/src/components/ToolCallBlock/titles.ts +102 -0
- package/src/hooks/use-drag-gesture.test.ts +66 -0
- package/src/hooks/use-drag-gesture.ts +129 -0
- package/src/hooks/use-pull-down-history.ts +241 -0
- package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
- package/src/hooks/useMediaUpload.ts +242 -0
- package/src/hooks/useTTSAutoPlay.ts +82 -0
- package/src/icons.ts +39 -0
- package/src/index.ts +143 -0
- package/src/overlay/Overlay.tsx +154 -0
- package/src/overlay/focus.ts +53 -0
- package/src/overlay/index.ts +16 -0
- package/src/overlay/inert.ts +27 -0
- package/src/overlay/layers.ts +21 -0
- package/src/overlay/overlay.ssr.test.tsx +27 -0
- package/src/overlay/overlay.test.tsx +209 -0
- package/src/overlay/presence.ts +86 -0
- package/src/overlay/scroll-lock.ts +62 -0
- package/src/overlay/stack.ts +111 -0
- package/src/overlay/use-overlay.ts +80 -0
- package/src/preview-provider.tsx +47 -0
- package/src/shell.contract.json +75 -0
- package/src/shell.test.ts +72 -0
- package/src/shell.ts +60 -0
- package/src/store-context.tsx +92 -0
- package/src/surface.test.tsx +35 -0
- package/src/surface.tsx +44 -0
- package/src/test/setup.ts +7 -0
- package/src/theme/base.css +167 -0
- package/src/theme/contract.json +193 -0
- package/src/theme/motion.css +19 -0
- package/src/theme/theme-contract.test.ts +85 -0
- package/src/theme/theme.ts +17 -0
- package/src/theme/tokens.css +78 -0
- package/src/types.ts +29 -0
- package/src/utils/copyText.ts +11 -0
- package/src/utils/haptics.test.ts +51 -0
- package/src/utils/haptics.ts +44 -0
- package/src/utils/image-preview-host.tsx +95 -0
- package/src/utils/imagePreview.test.ts +32 -0
- package/src/utils/imagePreview.ts +19 -0
- package/src/utils/pull-down-machine.test.ts +188 -0
- package/src/utils/pull-down-machine.ts +157 -0
- package/src/utils/session-error.ts +5 -0
- package/src/utils/toast.test.ts +64 -0
- package/src/utils/toast.ts +108 -0
- package/src/utils/tool-call-display.test.ts +240 -0
- package/src/utils/tool-call-display.ts +146 -0
- package/src/vite-env.d.ts +1 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
2
|
+
import type { IASRAdapter } from '@tbox.cn/app-agent-sdk-client';
|
|
3
|
+
import { useRefreshSession } from '@tbox.cn/app-agent-sdk-client';
|
|
4
|
+
import { isSessionExpiredError } from '../../../utils/session-error';
|
|
5
|
+
import { toast } from '../../../utils/toast';
|
|
6
|
+
import {
|
|
7
|
+
getMoveInteractionState,
|
|
8
|
+
getReleaseAction,
|
|
9
|
+
type VoiceInteractionState,
|
|
10
|
+
} from './machine';
|
|
11
|
+
|
|
12
|
+
export interface VoicePressHandlers {
|
|
13
|
+
onTouchStart: (e: React.TouchEvent) => void;
|
|
14
|
+
onTouchMove: (e: React.TouchEvent) => void;
|
|
15
|
+
onTouchEnd: (e: React.TouchEvent) => void;
|
|
16
|
+
onTouchCancel: (e: React.TouchEvent) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const MAX_DURATION = 60; // 录音上限(秒)
|
|
20
|
+
const COUNTDOWN_START = 10; // 剩余 10 秒起显示倒计时
|
|
21
|
+
|
|
22
|
+
// 录音权限被拒/不可用时给用户的提示(补回旧模板丢失的“被拒反馈”——旧版会弹 modal / 触发
|
|
23
|
+
// onPermissionDenied,新版此前是静默回 idle)。两端通用:toast 是纯 DOM 实现,不依赖任何组件库。
|
|
24
|
+
// 到这里的错误来自实际录音引擎(浏览器;或壳内桥失败降级后的 H5——见 FallbackASRAdapter),
|
|
25
|
+
// 故 NotFoundError 可精确判“无设备”,其余(NotAllowedError/未知)用“检查录音权限 + 重试”兜底。
|
|
26
|
+
const MIC_PERMISSION_MSG = '无法使用麦克风,请检查录音权限后重试';
|
|
27
|
+
function micErrorMessage(err: unknown): string {
|
|
28
|
+
const name = (err as { name?: string } | null)?.name;
|
|
29
|
+
if (name === 'NotFoundError' || name === 'DevicesNotFoundError') return '未检测到麦克风设备';
|
|
30
|
+
return MIC_PERMISSION_MSG;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 按住说话交互:按下录音、上滑取消、松手转文字、到 60s 自动停。识别结果通过 onResult 回传。 */
|
|
34
|
+
export function useVoicePress({
|
|
35
|
+
disabled,
|
|
36
|
+
asr,
|
|
37
|
+
onResult,
|
|
38
|
+
}: {
|
|
39
|
+
disabled?: boolean;
|
|
40
|
+
asr?: IASRAdapter;
|
|
41
|
+
onResult: (text: string) => void;
|
|
42
|
+
}) {
|
|
43
|
+
const refreshSession = useRefreshSession();
|
|
44
|
+
const [interactionState, setStateRaw] = useState<VoiceInteractionState>('idle');
|
|
45
|
+
const [duration, setDurationRaw] = useState(0);
|
|
46
|
+
const stateRef = useRef<VoiceInteractionState>('idle');
|
|
47
|
+
const durationRef = useRef(0);
|
|
48
|
+
const startYRef = useRef(0);
|
|
49
|
+
const recordingRef = useRef(false);
|
|
50
|
+
// 本次录音实际使用的 adapter:session 过期重试后会切到刷新出来的新 adapter
|
|
51
|
+
const recordingAsrRef = useRef<IASRAdapter | undefined>(asr);
|
|
52
|
+
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
53
|
+
const finishRef = useRef<() => void>(() => {});
|
|
54
|
+
|
|
55
|
+
const setState = useCallback((s: VoiceInteractionState) => {
|
|
56
|
+
stateRef.current = s;
|
|
57
|
+
setStateRaw(s);
|
|
58
|
+
}, []);
|
|
59
|
+
const setDur = (n: number) => {
|
|
60
|
+
durationRef.current = n;
|
|
61
|
+
setDurationRaw(n);
|
|
62
|
+
};
|
|
63
|
+
const stopTimer = () => {
|
|
64
|
+
if (timerRef.current) {
|
|
65
|
+
clearInterval(timerRef.current);
|
|
66
|
+
timerRef.current = null;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const startTimer = () => {
|
|
70
|
+
stopTimer();
|
|
71
|
+
setDur(0);
|
|
72
|
+
timerRef.current = setInterval(() => {
|
|
73
|
+
setDur(durationRef.current + 1);
|
|
74
|
+
if (durationRef.current >= MAX_DURATION) {
|
|
75
|
+
stopTimer();
|
|
76
|
+
finishRef.current(); // 到上限按"松手"处理(转文字 / 若在取消区则取消)
|
|
77
|
+
}
|
|
78
|
+
}, 1000);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const onTouchStart = useCallback(
|
|
82
|
+
async (e: React.TouchEvent) => {
|
|
83
|
+
if (disabled || !asr || recordingRef.current) return;
|
|
84
|
+
// 长按录音由应用接管,避免移动端浏览器启动原生选择/拖拽手势。
|
|
85
|
+
e.preventDefault();
|
|
86
|
+
startYRef.current = e.touches[0]?.clientY ?? 0;
|
|
87
|
+
setState('pressing');
|
|
88
|
+
|
|
89
|
+
// 权限检查(对齐原模板 useVoiceRecorder):未授权/检查异常 → 提示并回 idle
|
|
90
|
+
if (asr.checkPermission) {
|
|
91
|
+
try {
|
|
92
|
+
if (!(await asr.checkPermission())) {
|
|
93
|
+
toast(MIC_PERMISSION_MSG, 'error');
|
|
94
|
+
setState('idle');
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
toast(MIC_PERMISSION_MSG, 'error');
|
|
99
|
+
setState('idle');
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let active = asr;
|
|
105
|
+
try {
|
|
106
|
+
try {
|
|
107
|
+
await asr.startRecording();
|
|
108
|
+
} catch (err) {
|
|
109
|
+
// session 过期 → 刷新并用新 adapter 重试一次(对齐原模板)
|
|
110
|
+
if (isSessionExpiredError(err) && refreshSession) {
|
|
111
|
+
const next = await refreshSession();
|
|
112
|
+
if (next.asr) {
|
|
113
|
+
active = next.asr;
|
|
114
|
+
await active.startRecording();
|
|
115
|
+
} else {
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
throw err;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
recordingAsrRef.current = active;
|
|
123
|
+
recordingRef.current = true;
|
|
124
|
+
startTimer();
|
|
125
|
+
if (stateRef.current === 'pressing') setState('recording-active');
|
|
126
|
+
} catch (err) {
|
|
127
|
+
recordingRef.current = false;
|
|
128
|
+
toast(isSessionExpiredError(err) ? '登录状态已失效,请稍后重试' : micErrorMessage(err), 'error');
|
|
129
|
+
setState('idle');
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
[disabled, asr, refreshSession, setState],
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
const onTouchMove = useCallback(
|
|
136
|
+
(e: React.TouchEvent) => {
|
|
137
|
+
if (!recordingRef.current) return;
|
|
138
|
+
e.preventDefault();
|
|
139
|
+
const y = e.touches[0]?.clientY ?? 0;
|
|
140
|
+
setState(getMoveInteractionState(startYRef.current, y));
|
|
141
|
+
},
|
|
142
|
+
[setState],
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
const finish = useCallback(async () => {
|
|
146
|
+
stopTimer();
|
|
147
|
+
if (!recordingRef.current) {
|
|
148
|
+
setState('idle');
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
recordingRef.current = false;
|
|
152
|
+
// 用本次录音实际使用的 adapter(可能因 session 重试切换过)
|
|
153
|
+
const active = recordingAsrRef.current ?? asr;
|
|
154
|
+
const action = getReleaseAction(stateRef.current);
|
|
155
|
+
if (action === 'cancel') {
|
|
156
|
+
active?.cancelRecording();
|
|
157
|
+
setState('idle');
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
setState('processing');
|
|
161
|
+
try {
|
|
162
|
+
const text = (await active?.stopRecording()) ?? '';
|
|
163
|
+
if (text) onResult(text);
|
|
164
|
+
} catch {
|
|
165
|
+
/* ignore */
|
|
166
|
+
}
|
|
167
|
+
setState('idle');
|
|
168
|
+
}, [asr, onResult, setState]);
|
|
169
|
+
finishRef.current = finish;
|
|
170
|
+
|
|
171
|
+
const handlers: VoicePressHandlers = {
|
|
172
|
+
onTouchStart,
|
|
173
|
+
onTouchMove,
|
|
174
|
+
onTouchEnd: () => finish(),
|
|
175
|
+
onTouchCancel: () => {
|
|
176
|
+
stopTimer();
|
|
177
|
+
if (recordingRef.current) {
|
|
178
|
+
recordingRef.current = false;
|
|
179
|
+
(recordingAsrRef.current ?? asr)?.cancelRecording();
|
|
180
|
+
}
|
|
181
|
+
setState('idle');
|
|
182
|
+
},
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const counting =
|
|
186
|
+
recordingRef.current &&
|
|
187
|
+
(interactionState === 'recording-active' || interactionState === 'recording-cancel' || interactionState === 'pressing');
|
|
188
|
+
const countdown = counting && duration >= MAX_DURATION - COUNTDOWN_START ? MAX_DURATION - duration : null;
|
|
189
|
+
|
|
190
|
+
useEffect(() => {
|
|
191
|
+
const locked = interactionState !== 'idle';
|
|
192
|
+
document.body.classList.toggle('tbox-voice-page-lock', locked);
|
|
193
|
+
if (!locked) return undefined;
|
|
194
|
+
const preventNativeGesture = (event: Event) => event.preventDefault();
|
|
195
|
+
document.addEventListener('selectstart', preventNativeGesture);
|
|
196
|
+
document.addEventListener('dragstart', preventNativeGesture);
|
|
197
|
+
document.addEventListener('contextmenu', preventNativeGesture);
|
|
198
|
+
return () => {
|
|
199
|
+
document.body.classList.remove('tbox-voice-page-lock');
|
|
200
|
+
document.removeEventListener('selectstart', preventNativeGesture);
|
|
201
|
+
document.removeEventListener('dragstart', preventNativeGesture);
|
|
202
|
+
document.removeEventListener('contextmenu', preventNativeGesture);
|
|
203
|
+
};
|
|
204
|
+
}, [interactionState]);
|
|
205
|
+
|
|
206
|
+
return { interactionState, overlayVisible: interactionState !== 'idle', countdown, handlers };
|
|
207
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// 顶部历史入口胶囊:同时承载点击入口和轻量下拉状态反馈。
|
|
2
|
+
// 常驻渲染是刻意的:运行时未就绪时只禁用,不隐藏——否则就绪后插入 DOM 会把下方欢迎区顶开。
|
|
3
|
+
import type { PullStatus } from '../../utils/pull-down-machine';
|
|
4
|
+
|
|
5
|
+
function labelOf(status: PullStatus, loading: boolean): string {
|
|
6
|
+
if (loading || status === 'loading') return '加载中...';
|
|
7
|
+
if (status === 'pulling') return '下拉查看历史';
|
|
8
|
+
if (status === 'ready') return '松手查看历史';
|
|
9
|
+
if (status === 'noMore') return '没有更多历史记录';
|
|
10
|
+
return '历史记录';
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export default function HistoryEntry({
|
|
14
|
+
visible,
|
|
15
|
+
loading,
|
|
16
|
+
disabled,
|
|
17
|
+
pullStatus,
|
|
18
|
+
onLoad,
|
|
19
|
+
}: {
|
|
20
|
+
visible: boolean;
|
|
21
|
+
loading: boolean;
|
|
22
|
+
disabled: boolean;
|
|
23
|
+
pullStatus: PullStatus;
|
|
24
|
+
onLoad: () => void;
|
|
25
|
+
}) {
|
|
26
|
+
if (!visible) return null;
|
|
27
|
+
|
|
28
|
+
return (
|
|
29
|
+
<div className="history-entry flex justify-center p-0">
|
|
30
|
+
<button
|
|
31
|
+
type="button"
|
|
32
|
+
data-tbox-control="history"
|
|
33
|
+
className="history-entry__button inline-flex min-h-11 appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-muted px-4 py-1 text-sm font-normal leading-[18px] text-muted-foreground transition-colors duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-border disabled:cursor-default"
|
|
34
|
+
disabled={disabled}
|
|
35
|
+
onClick={onLoad}
|
|
36
|
+
>
|
|
37
|
+
{(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-border border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
|
|
38
|
+
{labelOf(pullStatus, loading)}
|
|
39
|
+
</button>
|
|
40
|
+
</div>
|
|
41
|
+
);
|
|
42
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
2
|
+
import { X, Warning, Prohibit, Plus, VideoCamera } from '@phosphor-icons/react';
|
|
3
|
+
import { previewImages } from '../../utils/imagePreview';
|
|
4
|
+
import { toast } from '../../utils/toast';
|
|
5
|
+
import type { MediaItem } from '../../types';
|
|
6
|
+
|
|
7
|
+
/** 媒体选项图标(远程素材,对齐原模板)。 */
|
|
8
|
+
const POPOVER_ICONS: Record<string, { icon: string; label: string; bg: string }> = {
|
|
9
|
+
image: {
|
|
10
|
+
icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*DfDhSYAMzoQAAAAAHiAAAAgAel-hAQ/original',
|
|
11
|
+
label: '相册',
|
|
12
|
+
bg: '#0000001a',
|
|
13
|
+
},
|
|
14
|
+
camera: {
|
|
15
|
+
icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*xdKLSabxqmQAAAAAOnAAAAgAel-hAQ/original',
|
|
16
|
+
label: '拍摄',
|
|
17
|
+
bg: '#096bfa26',
|
|
18
|
+
},
|
|
19
|
+
video: {
|
|
20
|
+
icon: 'https://mdn.alipayobjects.com/huamei_nzq4hr/afts/img/A*DfDhSYAMzoQAAAAAHiAAAAgAel-hAQ/original',
|
|
21
|
+
label: '视频',
|
|
22
|
+
bg: '#096bfa26',
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** 媒体删除按钮:图片卡与文件卡共用(旧 Less 两处规则同值)。 */
|
|
27
|
+
const MEDIA_REMOVE_CLASS =
|
|
28
|
+
'tbox-media-item__remove absolute top-1.5 right-1.5 z-[2] flex size-[18px] items-center justify-center rounded-[9px] bg-[rgba(0,0,0,0.55)] shadow-[0_1px_2px_rgba(0,0,0,0.15)]';
|
|
29
|
+
|
|
30
|
+
function formatSize(bytes?: number): string {
|
|
31
|
+
if (!bytes) return '';
|
|
32
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
33
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
34
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function ImageItemCard({
|
|
38
|
+
item,
|
|
39
|
+
allImages,
|
|
40
|
+
onRemove,
|
|
41
|
+
onRetry,
|
|
42
|
+
}: {
|
|
43
|
+
item: MediaItem;
|
|
44
|
+
allImages: string[];
|
|
45
|
+
onRemove: (id: string) => void;
|
|
46
|
+
onRetry?: (id: string) => void;
|
|
47
|
+
}) {
|
|
48
|
+
const isUploading = !!item.isUploading;
|
|
49
|
+
const isFailed = !!item.uploadFailed;
|
|
50
|
+
const isIllegal = !!item.illegal;
|
|
51
|
+
const progress = item.uploadProgress ?? 0;
|
|
52
|
+
|
|
53
|
+
const onClick = () => {
|
|
54
|
+
if (isUploading) return;
|
|
55
|
+
if (isFailed) return onRetry?.(item.id);
|
|
56
|
+
if (isIllegal) return void toast('内容未过审核');
|
|
57
|
+
previewImages(allImages, allImages.indexOf(item.src));
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
return (
|
|
61
|
+
<div
|
|
62
|
+
className="tbox-media-item tbox-media-item--image relative h-[var(--tbox-media-item-size)] w-[var(--tbox-media-item-size)] min-w-[var(--tbox-media-item-size)] overflow-hidden rounded-[var(--tbox-media-item-radius)] bg-[#f5f5f5]"
|
|
63
|
+
onClick={onClick}
|
|
64
|
+
>
|
|
65
|
+
<img className="tbox-media-item__thumb block h-full w-full object-cover" src={item.src} alt="" />
|
|
66
|
+
|
|
67
|
+
{isUploading && (
|
|
68
|
+
<div className="tbox-media-item__overlay absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-[var(--tbox-media-item-radius)] bg-[rgba(0,0,0,0.5)]">
|
|
69
|
+
<div
|
|
70
|
+
className="tbox-media-item__progress-ring flex size-[30px] items-center justify-center rounded-full transition-[background] duration-[var(--tbox-motion-duration-base)] ease-[ease]"
|
|
71
|
+
style={{ background: `conic-gradient(#fff ${progress}%, rgba(255,255,255,0.25) ${progress}%)` }}
|
|
72
|
+
>
|
|
73
|
+
<div className="tbox-media-item__progress-inner flex size-6 items-center justify-center rounded-full bg-[rgba(0,0,0,0.7)]">
|
|
74
|
+
<span className="tbox-media-item__progress-text text-center text-xs leading-[normal] font-bold text-white">{progress}%</span>
|
|
75
|
+
</div>
|
|
76
|
+
</div>
|
|
77
|
+
</div>
|
|
78
|
+
)}
|
|
79
|
+
|
|
80
|
+
{isFailed && (
|
|
81
|
+
<div className="tbox-media-item__overlay absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-[var(--tbox-media-item-radius)] bg-[rgba(0,0,0,0.5)]">
|
|
82
|
+
<div className="tbox-media-item__status-icon flex items-center justify-center">
|
|
83
|
+
<Warning size={20} color="#fff" />
|
|
84
|
+
</div>
|
|
85
|
+
<span className="tbox-media-item__status-text text-center text-xs leading-[normal] font-medium whitespace-nowrap text-[rgba(255,255,255,0.85)]">点击重试</span>
|
|
86
|
+
</div>
|
|
87
|
+
)}
|
|
88
|
+
|
|
89
|
+
{isIllegal && (
|
|
90
|
+
<div className="tbox-media-item__overlay absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-[var(--tbox-media-item-radius)] bg-[rgba(0,0,0,0.5)]">
|
|
91
|
+
<div className="tbox-media-item__status-icon flex items-center justify-center">
|
|
92
|
+
<Prohibit size={20} color="#fff" />
|
|
93
|
+
</div>
|
|
94
|
+
<span className="tbox-media-item__status-text text-center text-xs leading-[normal] font-medium whitespace-nowrap text-[rgba(255,255,255,0.85)]">未过审核</span>
|
|
95
|
+
</div>
|
|
96
|
+
)}
|
|
97
|
+
|
|
98
|
+
{!isUploading && (
|
|
99
|
+
<div className={MEDIA_REMOVE_CLASS} onClick={(e) => { e.stopPropagation(); onRemove(item.id); }}>
|
|
100
|
+
<X size={14} color="#fff" />
|
|
101
|
+
</div>
|
|
102
|
+
)}
|
|
103
|
+
</div>
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function FileItemCard({
|
|
108
|
+
item,
|
|
109
|
+
onRemove,
|
|
110
|
+
onRetry,
|
|
111
|
+
}: {
|
|
112
|
+
item: MediaItem;
|
|
113
|
+
onRemove: (id: string) => void;
|
|
114
|
+
onRetry?: (id: string) => void;
|
|
115
|
+
}) {
|
|
116
|
+
const isUploading = !!item.isUploading;
|
|
117
|
+
const isFailed = !!item.uploadFailed;
|
|
118
|
+
|
|
119
|
+
const meta = isUploading
|
|
120
|
+
? `上传中...${item.uploadProgress ?? 0}%`
|
|
121
|
+
: isFailed
|
|
122
|
+
? '上传失败'
|
|
123
|
+
: formatSize(item.size);
|
|
124
|
+
|
|
125
|
+
return (
|
|
126
|
+
<div
|
|
127
|
+
className="tbox-file-item relative flex h-[var(--tbox-media-item-size)] min-w-[140px] flex-row items-center gap-1.5 overflow-visible rounded-[var(--tbox-media-item-radius)] bg-[#fcfcfc] p-2"
|
|
128
|
+
onClick={() => isFailed && onRetry?.(item.id)}
|
|
129
|
+
>
|
|
130
|
+
<div className="tbox-file-item__icon flex size-6 shrink-0 items-center justify-center">
|
|
131
|
+
<VideoCamera size={28} color="#506fff" />
|
|
132
|
+
</div>
|
|
133
|
+
<div className="tbox-file-item__info flex min-w-0 flex-1 flex-col justify-center gap-0.5">
|
|
134
|
+
<span className="tbox-file-item__name max-w-full truncate text-xs leading-[normal] font-medium text-[#333]">{item.name ?? '未知文件'}</span>
|
|
135
|
+
<span className={`tbox-file-item__meta whitespace-nowrap text-xs leading-[normal] ${isFailed ? 'tbox-file-item__meta--failed text-destructive' : 'text-[rgba(0,0,0,0.25)]'}`}>{meta}</span>
|
|
136
|
+
</div>
|
|
137
|
+
{!isUploading && (
|
|
138
|
+
<div className={MEDIA_REMOVE_CLASS} onClick={(e) => { e.stopPropagation(); onRemove(item.id); }}>
|
|
139
|
+
<X size={14} color="#fff" />
|
|
140
|
+
</div>
|
|
141
|
+
)}
|
|
142
|
+
</div>
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function MediaPopover({
|
|
147
|
+
visible,
|
|
148
|
+
options,
|
|
149
|
+
onSelect,
|
|
150
|
+
}: {
|
|
151
|
+
visible: boolean;
|
|
152
|
+
options: { type: string; icon: string; label: string; bg: string }[];
|
|
153
|
+
onSelect: (type: string) => void;
|
|
154
|
+
}) {
|
|
155
|
+
return (
|
|
156
|
+
<div
|
|
157
|
+
className={`tbox-media-popover absolute right-0 z-10 w-[var(--tbox-media-item-size)] rounded-[10px] bg-white py-2 shadow-[0_2px_10px_rgba(0,0,0,0.08)] transition-[opacity,transform] duration-[var(--tbox-motion-duration-fast)] ease-out bottom-[calc(var(--tbox-media-item-size)_+_4px)] ${visible ? 'tbox-media-popover--visible pointer-events-auto opacity-100 [transform:translateY(0)]' : 'pointer-events-none opacity-0 [transform:translateY(4px)]'}`}
|
|
158
|
+
>
|
|
159
|
+
{options.map((opt) => (
|
|
160
|
+
<div
|
|
161
|
+
key={opt.type}
|
|
162
|
+
className="tbox-media-popover__item flex h-[30px] flex-row items-center gap-1 px-2 [&+&]:mt-1"
|
|
163
|
+
onClick={(e) => { e.stopPropagation(); onSelect(opt.type); }}
|
|
164
|
+
>
|
|
165
|
+
<div className="tbox-media-popover__icon-wrap flex size-5 shrink-0 items-center justify-center rounded-[4px]" style={{ background: opt.bg }}>
|
|
166
|
+
<img className="tbox-media-popover__icon size-4" src={opt.icon} alt="" />
|
|
167
|
+
</div>
|
|
168
|
+
<span className="tbox-media-popover__label text-sm leading-[1.4] font-normal text-[rgba(31,59,99,0.88)]">{opt.label}</span>
|
|
169
|
+
</div>
|
|
170
|
+
))}
|
|
171
|
+
</div>
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export interface MediaListProps {
|
|
176
|
+
items: MediaItem[];
|
|
177
|
+
onRemove: (id: string) => void;
|
|
178
|
+
onRetry?: (id: string) => void;
|
|
179
|
+
onPickImage?: () => void;
|
|
180
|
+
onPickCamera?: () => void;
|
|
181
|
+
onPickVideo?: () => void;
|
|
182
|
+
enableImage?: boolean;
|
|
183
|
+
enableVideo?: boolean;
|
|
184
|
+
isWebPc?: boolean;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** 已选媒体预览列表(对齐原模板:进度环 / 失败-未过审 overlay / 删除 / 末尾加号 popover)。 */
|
|
188
|
+
export function MediaList({
|
|
189
|
+
items,
|
|
190
|
+
onRemove,
|
|
191
|
+
onRetry,
|
|
192
|
+
onPickImage,
|
|
193
|
+
onPickCamera,
|
|
194
|
+
onPickVideo,
|
|
195
|
+
enableImage,
|
|
196
|
+
enableVideo,
|
|
197
|
+
isWebPc,
|
|
198
|
+
}: MediaListProps) {
|
|
199
|
+
const [popoverVisible, setPopoverVisible] = useState(false);
|
|
200
|
+
const hasCamera = !!enableImage && !isWebPc;
|
|
201
|
+
|
|
202
|
+
const options = [
|
|
203
|
+
enableImage && { type: 'image', ...POPOVER_ICONS.image },
|
|
204
|
+
hasCamera && { type: 'camera', ...POPOVER_ICONS.camera },
|
|
205
|
+
enableVideo && { type: 'video', ...POPOVER_ICONS.video },
|
|
206
|
+
].filter(Boolean) as { type: string; icon: string; label: string; bg: string }[];
|
|
207
|
+
|
|
208
|
+
const allImages = items
|
|
209
|
+
.filter((i) => i.type === 'image' && !i.isUploading && !i.uploadFailed && !i.illegal)
|
|
210
|
+
.map((i) => i.src);
|
|
211
|
+
|
|
212
|
+
const handleAddClick = useCallback(() => {
|
|
213
|
+
if (options.length <= 1) {
|
|
214
|
+
if (enableImage) onPickImage?.();
|
|
215
|
+
else if (enableVideo) onPickVideo?.();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
setPopoverVisible((v) => !v);
|
|
219
|
+
}, [options.length, enableImage, enableVideo, onPickImage, onPickVideo]);
|
|
220
|
+
|
|
221
|
+
const handleSelect = useCallback(
|
|
222
|
+
(type: string) => {
|
|
223
|
+
setPopoverVisible(false);
|
|
224
|
+
if (type === 'image') onPickImage?.();
|
|
225
|
+
else if (type === 'camera') onPickCamera?.();
|
|
226
|
+
else if (type === 'video') onPickVideo?.();
|
|
227
|
+
},
|
|
228
|
+
[onPickImage, onPickCamera, onPickVideo],
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
useEffect(() => {
|
|
232
|
+
if (!popoverVisible) return;
|
|
233
|
+
const onDown = (e: MouseEvent | TouchEvent) => {
|
|
234
|
+
const t = e.target as HTMLElement;
|
|
235
|
+
if (t && !t.closest('.tbox-media-add') && !t.closest('.tbox-media-popover')) setPopoverVisible(false);
|
|
236
|
+
};
|
|
237
|
+
document.addEventListener('mousedown', onDown);
|
|
238
|
+
document.addEventListener('touchstart', onDown, { passive: true });
|
|
239
|
+
return () => {
|
|
240
|
+
document.removeEventListener('mousedown', onDown);
|
|
241
|
+
document.removeEventListener('touchstart', onDown);
|
|
242
|
+
};
|
|
243
|
+
}, [popoverVisible]);
|
|
244
|
+
|
|
245
|
+
if (items.length === 0) return null;
|
|
246
|
+
const showAddButton = options.length > 0;
|
|
247
|
+
|
|
248
|
+
return (
|
|
249
|
+
<div className="tbox-media-list flex items-end gap-2 overflow-visible pb-2">
|
|
250
|
+
<div className="tbox-media-list__scroll flex min-w-0 flex-nowrap gap-2 overflow-x-auto [-webkit-overflow-scrolling:touch] [&::-webkit-scrollbar]:hidden">
|
|
251
|
+
{items.map((item) =>
|
|
252
|
+
item.type === 'image' ? (
|
|
253
|
+
<ImageItemCard key={item.id} item={item} allImages={allImages} onRemove={onRemove} onRetry={onRetry} />
|
|
254
|
+
) : (
|
|
255
|
+
<FileItemCard key={item.id} item={item} onRemove={onRemove} onRetry={onRetry} />
|
|
256
|
+
),
|
|
257
|
+
)}
|
|
258
|
+
</div>
|
|
259
|
+
{showAddButton && (
|
|
260
|
+
<div
|
|
261
|
+
className="tbox-media-add relative flex h-[var(--tbox-media-item-size)] w-[var(--tbox-media-item-size)] min-w-[var(--tbox-media-item-size)] shrink-0 items-center justify-center rounded-[var(--tbox-media-item-radius)] bg-[rgba(255,255,255,0.6)]"
|
|
262
|
+
onClick={handleAddClick}
|
|
263
|
+
>
|
|
264
|
+
<Plus size={22} color="rgba(0,0,0,0.65)" />
|
|
265
|
+
<MediaPopover visible={popoverVisible} options={options} onSelect={handleSelect} />
|
|
266
|
+
</div>
|
|
267
|
+
)}
|
|
268
|
+
</div>
|
|
269
|
+
);
|
|
270
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import { act } from 'react';
|
|
3
|
+
import { createRoot } from 'react-dom/client';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import type { TboxCardPayload } from '@tbox.cn/app-contracts';
|
|
6
|
+
|
|
7
|
+
const mocks = vi.hoisted(() => ({
|
|
8
|
+
state: {
|
|
9
|
+
cardsByMessageId: {} as Record<string, TboxCardPayload[]>,
|
|
10
|
+
},
|
|
11
|
+
debugProps: null as Record<string, unknown> | null,
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
vi.mock('../../store-context', () => ({
|
|
15
|
+
useChatStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state),
|
|
16
|
+
// W2-1:内联卡过滤经 context 注入(域语义保持原 witness:会员门禁卡系剥离,
|
|
17
|
+
// 原直连 '@/components/MemberGateSheet/model' 的 MEMBER_GATE_CARD_TYPES 语义)
|
|
18
|
+
useInlineCardFilter: () =>
|
|
19
|
+
(cards: Array<{ cardType: string }>) =>
|
|
20
|
+
cards.filter((c) => !['member-login-cta', 'member-enrollment-cta'].includes(c.cardType)),
|
|
21
|
+
}));
|
|
22
|
+
vi.mock('../CardRenderer', () => ({
|
|
23
|
+
CardRenderer: ({ card }: { card: TboxCardPayload }) => <div data-card-id={card.id} />,
|
|
24
|
+
}));
|
|
25
|
+
vi.mock('../../components/ReasoningBlock', () => ({ default: () => null }));
|
|
26
|
+
vi.mock('../../components/ToolCallBlock', () => ({ default: () => null }));
|
|
27
|
+
vi.mock('../../components/ActionBar', () => ({
|
|
28
|
+
ActionBar: () => null,
|
|
29
|
+
CopyButton: () => null,
|
|
30
|
+
getMessageCopyText: () => '',
|
|
31
|
+
}));
|
|
32
|
+
vi.mock('../../components/ActionBar/DebugButton', () => ({
|
|
33
|
+
DebugButton: (props: Record<string, unknown>) => {
|
|
34
|
+
mocks.debugProps = props;
|
|
35
|
+
return null;
|
|
36
|
+
},
|
|
37
|
+
}));
|
|
38
|
+
|
|
39
|
+
import { MessageBubble } from './index';
|
|
40
|
+
|
|
41
|
+
function card(id: string, cardType: string): TboxCardPayload {
|
|
42
|
+
return { id, cardType, data: {}, status: 'ready', meta: { createdAt: 1 } };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const emptyAssistantMessage = {
|
|
46
|
+
id: 'assistant-1',
|
|
47
|
+
role: 'assistant' as const,
|
|
48
|
+
content: '',
|
|
49
|
+
status: 'done' as const,
|
|
50
|
+
createdAt: 1,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
describe('MessageBubble member gate card partition', () => {
|
|
54
|
+
let host: HTMLDivElement;
|
|
55
|
+
let root: ReturnType<typeof createRoot>;
|
|
56
|
+
|
|
57
|
+
beforeEach(() => {
|
|
58
|
+
host = document.createElement('div');
|
|
59
|
+
document.body.appendChild(host);
|
|
60
|
+
root = createRoot(host);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
afterEach(() => {
|
|
64
|
+
act(() => root.unmount());
|
|
65
|
+
host.remove();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('does not leave an empty message row for a login-only card', () => {
|
|
69
|
+
mocks.state.cardsByMessageId = {
|
|
70
|
+
'assistant-1': [card('login-1', 'member-login-cta')],
|
|
71
|
+
};
|
|
72
|
+
act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
|
|
73
|
+
expect(host.innerHTML).toBe('');
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('keeps ordinary cards while removing the login card from a mixed carousel', () => {
|
|
77
|
+
mocks.state.cardsByMessageId = {
|
|
78
|
+
'assistant-1': [
|
|
79
|
+
card('login-1', 'member-login-cta'),
|
|
80
|
+
card('coupon-1', 'coupon-detail'),
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
|
|
84
|
+
expect(host.querySelector('[data-card-id="login-1"]')).toBeNull();
|
|
85
|
+
expect(host.querySelector('[data-card-id="coupon-1"]')).not.toBeNull();
|
|
86
|
+
expect(host.querySelector('[aria-label^="第 "]')).toBeNull();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('strips enrollment-cta from inline carousel (module button is a bypassing openLink jump)', () => {
|
|
90
|
+
mocks.state.cardsByMessageId = {
|
|
91
|
+
'assistant-1': [
|
|
92
|
+
card('enroll-1', 'member-enrollment-cta'),
|
|
93
|
+
card('member-card-1', 'member-card-summary'),
|
|
94
|
+
],
|
|
95
|
+
};
|
|
96
|
+
act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
|
|
97
|
+
// 入会卡内联渲染会旁路 gate 闭环(openLink 裸外跳)——必须剥离,由 MemberGateSheet 投影
|
|
98
|
+
expect(host.querySelector('[data-card-id="enroll-1"]')).toBeNull();
|
|
99
|
+
expect(host.querySelector('[data-card-id="member-card-1"]')).not.toBeNull();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('多卡决策出卡 → 纵向按序渲染,无轮播圆点', () => {
|
|
103
|
+
mocks.state.cardsByMessageId = {
|
|
104
|
+
'assistant-1': [
|
|
105
|
+
card('coupon-1', 'coupon-detail'),
|
|
106
|
+
card('member-1', 'member-card-summary'),
|
|
107
|
+
],
|
|
108
|
+
};
|
|
109
|
+
act(() => root.render(<MessageBubble message={emptyAssistantMessage} />));
|
|
110
|
+
const all = host.querySelectorAll('[data-card-id]');
|
|
111
|
+
expect(all.length).toBe(2);
|
|
112
|
+
expect(all[0].getAttribute('data-card-id')).toBe('coupon-1');
|
|
113
|
+
expect(all[1].getAttribute('data-card-id')).toBe('member-1');
|
|
114
|
+
// 纵向铺开:不再有轮播圆点指示器
|
|
115
|
+
expect(host.querySelector('[aria-label^="第 "]')).toBeNull();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
it('error 消息接线:DebugButton 透传 requestId + conversationId(error 分支守卫——不经 ActionBar 的独立渲染路径)', () => {
|
|
119
|
+
mocks.state.cardsByMessageId = {}; // 用例间隔离:清除前序用例的卡片桶残留
|
|
120
|
+
mocks.debugProps = null;
|
|
121
|
+
act(() => {
|
|
122
|
+
root.render(
|
|
123
|
+
<MessageBubble
|
|
124
|
+
message={{ ...emptyAssistantMessage, status: 'error' as const, error: '失败', requestId: 'req_e', conversationId: 'conv_e' }}
|
|
125
|
+
/>,
|
|
126
|
+
);
|
|
127
|
+
});
|
|
128
|
+
expect(mocks.debugProps).toMatchObject({
|
|
129
|
+
requestId: 'req_e',
|
|
130
|
+
conversationId: 'conv_e',
|
|
131
|
+
messageId: 'assistant-1',
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
});
|