@tbox.cn/app-agent-ui-kit 0.0.0-stage → 1.0.0-alpha.6

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +16 -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 +58 -3
  11. package/src/ChatPage.tsx +332 -0
  12. package/src/card/define-card.ts +34 -0
  13. package/src/card/primitives.test.tsx +147 -0
  14. package/src/card/primitives.tsx +627 -0
  15. package/src/card/use-card-actions.ts +86 -0
  16. package/src/chat-config.test.ts +46 -0
  17. package/src/chat-config.ts +80 -0
  18. package/src/components/ActionBar/DebugButton.test.tsx +84 -0
  19. package/src/components/ActionBar/DebugButton.tsx +53 -0
  20. package/src/components/ActionBar/index.test.tsx +83 -0
  21. package/src/components/ActionBar/index.tsx +158 -0
  22. package/src/components/CardRenderer.tsx +36 -0
  23. package/src/components/ChatHeader/index.test.tsx +74 -0
  24. package/src/components/ChatHeader/index.tsx +77 -0
  25. package/src/components/ChatInput/index.test.tsx +156 -0
  26. package/src/components/ChatInput/index.tsx +290 -0
  27. package/src/components/ChatInput/voice/VoicePressField.tsx +43 -0
  28. package/src/components/ChatInput/voice/VoiceRecordingOverlay.tsx +51 -0
  29. package/src/components/ChatInput/voice/machine.ts +27 -0
  30. package/src/components/ChatInput/voice/useVoicePress.ts +207 -0
  31. package/src/components/HistoryEntry/index.tsx +41 -0
  32. package/src/components/MediaList/index.tsx +270 -0
  33. package/src/components/MessageBubble/index.test.tsx +134 -0
  34. package/src/components/MessageBubble/index.tsx +202 -0
  35. package/src/components/PullDownIndicator/index.tsx +31 -0
  36. package/src/components/QuickCommands/index.test.tsx +99 -0
  37. package/src/components/QuickCommands/index.tsx +52 -0
  38. package/src/components/ReasoningBlock/index.tsx +61 -0
  39. package/src/components/ScrollToBottomButton/index.tsx +8 -0
  40. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  41. package/src/components/ToolCallBlock/detail.ts +204 -0
  42. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  43. package/src/components/ToolCallBlock/index.tsx +230 -0
  44. package/src/components/ToolCallBlock/titles.ts +102 -0
  45. package/src/hooks/use-drag-gesture.test.ts +66 -0
  46. package/src/hooks/use-drag-gesture.ts +129 -0
  47. package/src/hooks/use-pull-down-history.ts +241 -0
  48. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  49. package/src/hooks/useMediaUpload.ts +242 -0
  50. package/src/hooks/useTTSAutoPlay.ts +82 -0
  51. package/src/icons.ts +39 -0
  52. package/src/index.ts +122 -0
  53. package/src/shell.contract.json +59 -0
  54. package/src/shell.test.ts +61 -0
  55. package/src/shell.ts +45 -0
  56. package/src/store-context.tsx +92 -0
  57. package/src/test/setup.ts +7 -0
  58. package/src/theme/base.css +132 -0
  59. package/src/theme/contract.json +72 -0
  60. package/src/theme/motion.css +19 -0
  61. package/src/theme/theme-contract.test.ts +69 -0
  62. package/src/theme/theme.ts +17 -0
  63. package/src/theme/tokens.css +81 -0
  64. package/src/types.ts +29 -0
  65. package/src/utils/copyText.ts +11 -0
  66. package/src/utils/haptics.test.ts +51 -0
  67. package/src/utils/haptics.ts +44 -0
  68. package/src/utils/imagePreview.ts +10 -0
  69. package/src/utils/pull-down-machine.test.ts +188 -0
  70. package/src/utils/pull-down-machine.ts +157 -0
  71. package/src/utils/session-error.ts +5 -0
  72. package/src/utils/toast.ts +15 -0
  73. package/src/utils/tool-call-display.test.ts +240 -0
  74. package/src/utils/tool-call-display.ts +146 -0
  75. package/src/vite-env.d.ts +1 -0
@@ -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
+ }
@@ -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 是 antd-mobile 的纯 H5 实现。
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,41 @@
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
+ className="history-entry__button inline-flex appearance-none items-center gap-[5px] rounded-[25px] border-0 bg-[rgba(15,64,113,0.06)] px-3 py-[3px] text-xs font-normal leading-[16px] text-muted-foreground transition-[background] duration-[var(--tbox-motion-duration-fast)] ease-[var(--tbox-motion-easing-standard)] [font-family:inherit] active:bg-[rgba(15,64,113,0.1)] disabled:cursor-default"
33
+ disabled={disabled}
34
+ onClick={onLoad}
35
+ >
36
+ {(loading || pullStatus === 'loading') && <span className="history-entry__spinner size-[10px] rounded-full border-[1.5px] border-[rgba(15,64,113,0.18)] border-t-primary animate-[history-entry-spin_0.6s_linear_infinite]" />}
37
+ {labelOf(pullStatus, loading)}
38
+ </button>
39
+ </div>
40
+ );
41
+ }
@@ -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
+ }