@tbox.cn/app-agent-ui-kit 0.0.0-stage → 1.0.0-alpha.1
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 +16 -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 +55 -3
- package/src/ChatPage.less +62 -0
- package/src/ChatPage.tsx +305 -0
- package/src/chat-config.test.ts +82 -0
- package/src/chat-config.ts +62 -0
- package/src/components/ActionBar/DebugButton.test.tsx +84 -0
- package/src/components/ActionBar/DebugButton.tsx +53 -0
- package/src/components/ActionBar/index.less +123 -0
- package/src/components/ActionBar/index.test.tsx +83 -0
- package/src/components/ActionBar/index.tsx +159 -0
- package/src/components/CardRenderer.tsx +36 -0
- package/src/components/ChatHeader/index.less +148 -0
- package/src/components/ChatHeader/index.test.tsx +74 -0
- package/src/components/ChatHeader/index.tsx +75 -0
- package/src/components/ChatInput/index.less +394 -0
- package/src/components/ChatInput/index.test.tsx +156 -0
- package/src/components/ChatInput/index.tsx +284 -0
- package/src/components/ChatInput/voice/VoicePressField.tsx +34 -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.less +49 -0
- package/src/components/HistoryEntry/index.tsx +42 -0
- package/src/components/MediaList/index.less +241 -0
- package/src/components/MediaList/index.tsx +256 -0
- package/src/components/MessageBubble/index.less +325 -0
- package/src/components/MessageBubble/index.test.tsx +134 -0
- package/src/components/MessageBubble/index.tsx +177 -0
- package/src/components/PullDownIndicator/index.less +32 -0
- package/src/components/PullDownIndicator/index.tsx +32 -0
- package/src/components/QuickCommands/index.less +63 -0
- package/src/components/QuickCommands/index.test.tsx +99 -0
- package/src/components/QuickCommands/index.tsx +52 -0
- package/src/components/ReasoningBlock/index.less +90 -0
- package/src/components/ReasoningBlock/index.tsx +56 -0
- package/src/components/ScrollToBottomButton/index.less +32 -0
- package/src/components/ScrollToBottomButton/index.tsx +10 -0
- package/src/components/ToolCallBlock/detail.test.ts +346 -0
- package/src/components/ToolCallBlock/detail.ts +204 -0
- package/src/components/ToolCallBlock/index.less +312 -0
- package/src/components/ToolCallBlock/index.test.tsx +261 -0
- package/src/components/ToolCallBlock/index.tsx +212 -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/index.ts +69 -0
- package/src/store-context.tsx +92 -0
- package/src/test/setup.ts +7 -0
- package/src/theme/contract.json +72 -0
- package/src/theme/global.less +99 -0
- package/src/theme/motion.less +19 -0
- package/src/theme/theme-contract.test.ts +69 -0
- package/src/theme/theme.ts +17 -0
- package/src/theme/tokens.less +79 -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/imagePreview.ts +10 -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.ts +15 -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,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 下拉加载历史 React 薄包装(机器见 pull-down-machine.ts)。
|
|
3
|
+
* wrapper 职责:machine 存 ref、状态镜像 useState、noMore 定时 reset、取消手势 reset、
|
|
4
|
+
* hasMore false→true 跃迁 reset(G9:分页游标重置后手势死区复活)及异步加载 in-flight 门控。
|
|
5
|
+
* 滚动位置真源在页面(isAtTopRef 只读透传);store 的 isLoadingHistory 仍是跨调用业务防抖权威。
|
|
6
|
+
*/
|
|
7
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
8
|
+
import { createPullDownMachine, NO_MORE_HOLD_MS, WHEEL_IDLE_RESET_MS } from '../utils/pull-down-machine';
|
|
9
|
+
import { useDragGesture } from './use-drag-gesture';
|
|
10
|
+
import { hapticTap } from '../utils/haptics';
|
|
11
|
+
import type { PullStatus } from '../utils/pull-down-machine';
|
|
12
|
+
|
|
13
|
+
export interface UsePullDownHistoryOptions {
|
|
14
|
+
isAtTopRef: React.MutableRefObject<boolean>;
|
|
15
|
+
isLoadingHistory: boolean;
|
|
16
|
+
hasMore: boolean;
|
|
17
|
+
onLoad: () => Promise<void>;
|
|
18
|
+
/** 鉴权或运行时尚未就绪时禁用手势,避免发出归属不明的历史请求。 */
|
|
19
|
+
disabled?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* 滚动容器 ref。传入后整套手势由容器上的原生监听接管(pointer 优先、touch 回退、非 passive):
|
|
22
|
+
* React 合成事件是 passive 阻止不了原生滚动,且只监听 touch 会漏掉 pointerType=mouse
|
|
23
|
+
* 的输入(开发者工具模拟器与桌面浏览器)。传了就**不要**再往 JSX 绑手势事件,否则走两遍。
|
|
24
|
+
*/
|
|
25
|
+
scrollRef?: React.RefObject<HTMLElement | null>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function usePullDownHistory(opts: UsePullDownHistoryOptions): {
|
|
29
|
+
pullStatus: PullStatus;
|
|
30
|
+
pullDistance: number;
|
|
31
|
+
handleTouchStart: (e: React.TouchEvent) => void;
|
|
32
|
+
handleTouchMove: (e: React.TouchEvent) => void;
|
|
33
|
+
handleTouchEnd: () => void;
|
|
34
|
+
handleTouchCancel: () => void;
|
|
35
|
+
handleWheel: (e: React.WheelEvent) => void;
|
|
36
|
+
} {
|
|
37
|
+
const { isAtTopRef, isLoadingHistory, hasMore, onLoad, disabled, scrollRef } = opts;
|
|
38
|
+
const machineRef = useRef(createPullDownMachine());
|
|
39
|
+
const [pullStatus, setPullStatus] = useState<PullStatus>('idle');
|
|
40
|
+
const [pullDistance, setPullDistance] = useState(0);
|
|
41
|
+
const noMoreTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
42
|
+
const loadInFlightRef = useRef<Promise<void> | null>(null);
|
|
43
|
+
const wheelIdleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
44
|
+
/** 本次连续滚动是否已触发过加载——惯性未停前不允许第二次。 */
|
|
45
|
+
const wheelLockedRef = useRef(false);
|
|
46
|
+
|
|
47
|
+
// 跨过触发线那一刻给一次轻触反馈:手势语义从「还在拉」变成「松手即加载」,
|
|
48
|
+
// 值得一个非视觉的确认信号(fail-soft,平台不支持即静默)。
|
|
49
|
+
const prevStatusRef = useRef<PullStatus>('idle');
|
|
50
|
+
|
|
51
|
+
const sync = useCallback(() => {
|
|
52
|
+
const { status, distance } = machineRef.current.getState();
|
|
53
|
+
if (status === 'ready' && prevStatusRef.current !== 'ready') hapticTap();
|
|
54
|
+
prevStatusRef.current = status;
|
|
55
|
+
setPullStatus(status);
|
|
56
|
+
setPullDistance(distance);
|
|
57
|
+
}, []);
|
|
58
|
+
|
|
59
|
+
const triggerLoad = useCallback(() => {
|
|
60
|
+
if (loadInFlightRef.current) return;
|
|
61
|
+
const task: Promise<void> = onLoad()
|
|
62
|
+
.catch(() => undefined)
|
|
63
|
+
.finally(() => {
|
|
64
|
+
if (loadInFlightRef.current === task) loadInFlightRef.current = null;
|
|
65
|
+
machineRef.current.reset();
|
|
66
|
+
sync();
|
|
67
|
+
});
|
|
68
|
+
loadInFlightRef.current = task;
|
|
69
|
+
}, [onLoad, sync]);
|
|
70
|
+
|
|
71
|
+
const handleTouchStart = useCallback(
|
|
72
|
+
(e: React.TouchEvent) => {
|
|
73
|
+
if (disabled) return;
|
|
74
|
+
const touch = e.touches[0];
|
|
75
|
+
if (!touch) return;
|
|
76
|
+
machineRef.current.touchStart(touch.clientY);
|
|
77
|
+
},
|
|
78
|
+
[disabled],
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
/** 推进机器并返回「是否需要阻止原生滚动」——合成事件与原生监听共用同一条逻辑。 */
|
|
82
|
+
const advanceTouchMove = useCallback(
|
|
83
|
+
(touch: { clientY: number }): boolean => {
|
|
84
|
+
if (disabled) return false;
|
|
85
|
+
const { preventDefault } = machineRef.current.touchMove({
|
|
86
|
+
clientY: touch.clientY,
|
|
87
|
+
isAtTop: isAtTopRef.current,
|
|
88
|
+
hasMore,
|
|
89
|
+
isLoading: isLoadingHistory,
|
|
90
|
+
});
|
|
91
|
+
sync();
|
|
92
|
+
return preventDefault;
|
|
93
|
+
},
|
|
94
|
+
[disabled, hasMore, isLoadingHistory, isAtTopRef, sync],
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
// 容器 ref 在场时由原生监听接管整套手势(pointer 优先,覆盖 mouse/touch/pen)
|
|
98
|
+
useDragGesture({
|
|
99
|
+
scrollRef,
|
|
100
|
+
disabled,
|
|
101
|
+
onStart: (point) => machineRef.current.touchStart(point.clientY),
|
|
102
|
+
onMove: advanceTouchMove,
|
|
103
|
+
onEnd: () => {
|
|
104
|
+
const { shouldLoad, holdNoMore } = machineRef.current.touchEnd({ hasMore });
|
|
105
|
+
if (shouldLoad) {
|
|
106
|
+
triggerLoad();
|
|
107
|
+
} else if (holdNoMore) {
|
|
108
|
+
if (noMoreTimerRef.current) clearTimeout(noMoreTimerRef.current);
|
|
109
|
+
noMoreTimerRef.current = setTimeout(() => {
|
|
110
|
+
machineRef.current.reset();
|
|
111
|
+
sync();
|
|
112
|
+
}, NO_MORE_HOLD_MS);
|
|
113
|
+
}
|
|
114
|
+
sync();
|
|
115
|
+
},
|
|
116
|
+
onCancel: () => {
|
|
117
|
+
machineRef.current.reset();
|
|
118
|
+
sync();
|
|
119
|
+
},
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const handleTouchMove = useCallback(
|
|
123
|
+
(e: React.TouchEvent) => {
|
|
124
|
+
const touch = e.touches[0];
|
|
125
|
+
if (!touch) return;
|
|
126
|
+
if (advanceTouchMove(touch)) {
|
|
127
|
+
try {
|
|
128
|
+
e.preventDefault();
|
|
129
|
+
} catch {
|
|
130
|
+
/* React 合成事件为 passive:此路径下阻止不了,容器 ref 形态才是权威 */
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
[advanceTouchMove],
|
|
135
|
+
);
|
|
136
|
+
|
|
137
|
+
const handleTouchEnd = useCallback(() => {
|
|
138
|
+
if (disabled) return;
|
|
139
|
+
const { shouldLoad, holdNoMore } = machineRef.current.touchEnd({ hasMore });
|
|
140
|
+
if (shouldLoad) {
|
|
141
|
+
triggerLoad();
|
|
142
|
+
} else if (holdNoMore) {
|
|
143
|
+
if (noMoreTimerRef.current) clearTimeout(noMoreTimerRef.current);
|
|
144
|
+
noMoreTimerRef.current = setTimeout(() => {
|
|
145
|
+
machineRef.current.reset();
|
|
146
|
+
sync();
|
|
147
|
+
}, NO_MORE_HOLD_MS);
|
|
148
|
+
}
|
|
149
|
+
sync();
|
|
150
|
+
}, [disabled, hasMore, sync, triggerLoad]);
|
|
151
|
+
|
|
152
|
+
const handleTouchCancel = useCallback(() => {
|
|
153
|
+
machineRef.current.reset();
|
|
154
|
+
sync();
|
|
155
|
+
}, [sync]);
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* wheel 没有「松手」事件,用「静默 WHEEL_IDLE_RESET_MS」代替手势结束:
|
|
159
|
+
* 到期才复位视觉并解锁。惯性期间每个事件都会重设它,因此锁一直有效。
|
|
160
|
+
*/
|
|
161
|
+
const scheduleWheelIdle = useCallback(() => {
|
|
162
|
+
if (wheelIdleTimerRef.current) clearTimeout(wheelIdleTimerRef.current);
|
|
163
|
+
wheelIdleTimerRef.current = setTimeout(() => {
|
|
164
|
+
machineRef.current.wheelIdle();
|
|
165
|
+
wheelIdleTimerRef.current = null;
|
|
166
|
+
wheelLockedRef.current = false;
|
|
167
|
+
sync();
|
|
168
|
+
}, WHEEL_IDLE_RESET_MS);
|
|
169
|
+
}, [sync]);
|
|
170
|
+
|
|
171
|
+
/** 推进 wheel 并返回「是否需要吞掉本次滚动」。原生监听与合成事件共用。 */
|
|
172
|
+
const advanceWheel = useCallback(
|
|
173
|
+
(deltaY: number): boolean => {
|
|
174
|
+
if (disabled) return false;
|
|
175
|
+
// 触发后到滚动停止之间:吞掉惯性。加载会把 scrollTop 抬到前插位置,
|
|
176
|
+
// 上方随即出现可滚空间,残余惯性会继续把它带走——落位就白设了。
|
|
177
|
+
if (wheelLockedRef.current) {
|
|
178
|
+
scheduleWheelIdle();
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
181
|
+
const { shouldLoad } = machineRef.current.wheel({
|
|
182
|
+
deltaY,
|
|
183
|
+
isAtTop: isAtTopRef.current,
|
|
184
|
+
hasMore,
|
|
185
|
+
isLoading: isLoadingHistory,
|
|
186
|
+
});
|
|
187
|
+
sync();
|
|
188
|
+
if (shouldLoad) {
|
|
189
|
+
wheelLockedRef.current = true;
|
|
190
|
+
triggerLoad();
|
|
191
|
+
scheduleWheelIdle();
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
scheduleWheelIdle();
|
|
195
|
+
return false;
|
|
196
|
+
},
|
|
197
|
+
[disabled, hasMore, isLoadingHistory, isAtTopRef, scheduleWheelIdle, sync, triggerLoad],
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
// 原生非 passive 绑定:React 的 onWheel 同样是 passive,preventDefault 无效,
|
|
201
|
+
// 吞不掉惯性。与 touch 通道同理(见 use-drag-gesture 文件头)。
|
|
202
|
+
useEffect(() => {
|
|
203
|
+
const el = scrollRef?.current;
|
|
204
|
+
if (!el || disabled) return undefined;
|
|
205
|
+
const onWheel = (e: WheelEvent) => {
|
|
206
|
+
if (advanceWheel(e.deltaY) && e.cancelable) e.preventDefault();
|
|
207
|
+
};
|
|
208
|
+
el.addEventListener('wheel', onWheel, { passive: false });
|
|
209
|
+
return () => el.removeEventListener('wheel', onWheel);
|
|
210
|
+
}, [advanceWheel, disabled, scrollRef]);
|
|
211
|
+
|
|
212
|
+
const handleWheel = useCallback(
|
|
213
|
+
(e: React.WheelEvent) => {
|
|
214
|
+
if (disabled) return;
|
|
215
|
+
// 传了 scrollRef 时手势已由原生监听接管,此路径仅为不传 ref 的旧用法保留
|
|
216
|
+
if (scrollRef?.current) return;
|
|
217
|
+
advanceWheel(e.deltaY);
|
|
218
|
+
},
|
|
219
|
+
[advanceWheel, disabled, scrollRef],
|
|
220
|
+
);
|
|
221
|
+
|
|
222
|
+
// G9:hasMore false→true 跃迁(分页游标重置)→ 机器复位(noMore 残留死区复活)
|
|
223
|
+
const prevHasMoreRef = useRef(hasMore);
|
|
224
|
+
useEffect(() => {
|
|
225
|
+
if (prevHasMoreRef.current === false && hasMore) {
|
|
226
|
+
machineRef.current.reset();
|
|
227
|
+
sync();
|
|
228
|
+
}
|
|
229
|
+
prevHasMoreRef.current = hasMore;
|
|
230
|
+
}, [hasMore, sync]);
|
|
231
|
+
|
|
232
|
+
// unmount 清理 noMore 定时器
|
|
233
|
+
useEffect(() => {
|
|
234
|
+
return () => {
|
|
235
|
+
if (noMoreTimerRef.current) clearTimeout(noMoreTimerRef.current);
|
|
236
|
+
if (wheelIdleTimerRef.current) clearTimeout(wheelIdleTimerRef.current);
|
|
237
|
+
};
|
|
238
|
+
}, []);
|
|
239
|
+
|
|
240
|
+
return { pullStatus, pullDistance, handleTouchStart, handleTouchMove, handleTouchEnd, handleTouchCancel, handleWheel };
|
|
241
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
/**
|
|
3
|
+
* wheel 原生通道用例。核心契约:触发加载后到滚动停止之间,惯性 wheel 必须被 preventDefault
|
|
4
|
+
* 吞掉——加载会把 scrollTop 抬到前插位置,上方随即出现可滚空间,残余惯性会把落位带走。
|
|
5
|
+
*/
|
|
6
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { createRoot } from 'react-dom/client';
|
|
8
|
+
import { flushSync } from 'react-dom';
|
|
9
|
+
import { createElement, useRef } from 'react';
|
|
10
|
+
import { usePullDownHistory } from './use-pull-down-history';
|
|
11
|
+
import { WHEEL_TRIGGER_ACCUM } from '../utils/pull-down-machine';
|
|
12
|
+
|
|
13
|
+
function wheelEvent(deltaY: number) {
|
|
14
|
+
const e = new Event('wheel', { bubbles: true, cancelable: true }) as WheelEvent;
|
|
15
|
+
Object.defineProperty(e, 'deltaY', { value: deltaY });
|
|
16
|
+
return e;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function setup(onLoad: () => Promise<void>) {
|
|
20
|
+
const el = document.createElement('div');
|
|
21
|
+
document.body.appendChild(el);
|
|
22
|
+
const Host = () => {
|
|
23
|
+
const isAtTopRef = useRef(true);
|
|
24
|
+
usePullDownHistory({
|
|
25
|
+
isAtTopRef,
|
|
26
|
+
isLoadingHistory: false,
|
|
27
|
+
hasMore: true,
|
|
28
|
+
onLoad,
|
|
29
|
+
scrollRef: { current: el },
|
|
30
|
+
});
|
|
31
|
+
return null;
|
|
32
|
+
};
|
|
33
|
+
const host = document.createElement('div');
|
|
34
|
+
document.body.appendChild(host);
|
|
35
|
+
flushSync(() => createRoot(host).render(createElement(Host)));
|
|
36
|
+
return el;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('usePullDownHistory:wheel 原生通道', () => {
|
|
40
|
+
it('N1 未触发时不吞滚动(页面照常滚)', () => {
|
|
41
|
+
const el = setup(async () => {});
|
|
42
|
+
const e = wheelEvent(-10);
|
|
43
|
+
el.dispatchEvent(e);
|
|
44
|
+
expect(e.defaultPrevented).toBe(false);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('N2 越阈触发后吞掉后续惯性,落位不被带走', async () => {
|
|
48
|
+
const onLoad = vi.fn(async () => {});
|
|
49
|
+
const el = setup(onLoad);
|
|
50
|
+
|
|
51
|
+
const trigger = wheelEvent(-(WHEEL_TRIGGER_ACCUM + 20));
|
|
52
|
+
el.dispatchEvent(trigger);
|
|
53
|
+
expect(onLoad).toHaveBeenCalledTimes(1);
|
|
54
|
+
expect(trigger.defaultPrevented).toBe(true);
|
|
55
|
+
|
|
56
|
+
// 惯性尾巴:既不得二次触发,也不得让原生滚动继续
|
|
57
|
+
for (let i = 0; i < 5; i += 1) {
|
|
58
|
+
const inertia = wheelEvent(-80);
|
|
59
|
+
el.dispatchEvent(inertia);
|
|
60
|
+
expect(inertia.defaultPrevented).toBe(true);
|
|
61
|
+
}
|
|
62
|
+
expect(onLoad).toHaveBeenCalledTimes(1);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { createLogger } from '@tbox.cn/app-agent-sdk-client';
|
|
2
|
+
|
|
3
|
+
const mediaLogger = createLogger('media');
|
|
4
|
+
|
|
5
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
6
|
+
import { useUploadAdapter, useRefreshSession, chooseImage, chooseVideo } from '@tbox.cn/app-agent-sdk-client';
|
|
7
|
+
|
|
8
|
+
import { isSessionExpiredError } from '../utils/session-error';
|
|
9
|
+
import { toast } from '../utils/toast';
|
|
10
|
+
import type { MediaItem, MediaType, MediaConfig } from '../types';
|
|
11
|
+
|
|
12
|
+
let seq = 0;
|
|
13
|
+
const nid = () => `media_${Date.now()}_${seq++}`;
|
|
14
|
+
const MAX_SIM_PROGRESS = 90; // 模拟进度上限;真正完成才到 100
|
|
15
|
+
|
|
16
|
+
/** 释放 blob: ObjectURL(仅浏览器环境;移除/清空媒体时调用防内存泄漏) */
|
|
17
|
+
const revokeIfBlob = (src?: string) => {
|
|
18
|
+
if (src && src.startsWith('blob:') && typeof URL !== 'undefined') {
|
|
19
|
+
URL.revokeObjectURL(src);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
function fileToType(f: File): MediaType {
|
|
24
|
+
if (f.type.startsWith('image')) return 'image';
|
|
25
|
+
if (f.type.startsWith('video')) return 'video';
|
|
26
|
+
if (f.type.startsWith('audio')) return 'audio';
|
|
27
|
+
return 'file';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const typeLabel = (t: MediaType) =>
|
|
31
|
+
t === 'image' ? '图片' : t === 'video' ? '视频' : t === 'audio' ? '音频' : '文件';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 媒体选取 + 上传(走 upload adapter,对齐原模板行为)。
|
|
35
|
+
* - 浏览器:addFiles(File[])(来自 <input type=file>);支付宝壳:addFromBridge('image'|'camera'|'video')
|
|
36
|
+
* - 上传中模拟进度(驱动圆形进度环);成功填 fileId;safed===false → illegal(未过审);
|
|
37
|
+
* session 过期自动 refresh + 重试一次;失败可 retry。
|
|
38
|
+
* - 无 upload adapter(session 未就绪)时 Toast 提示,不静默吞掉。
|
|
39
|
+
*/
|
|
40
|
+
export function useMediaUpload(maxTotal = 9, mediaConfig?: MediaConfig) {
|
|
41
|
+
const adapter = useUploadAdapter();
|
|
42
|
+
const refreshSession = useRefreshSession();
|
|
43
|
+
const [items, setItems] = useState<MediaItem[]>([]);
|
|
44
|
+
const itemsRef = useRef(items);
|
|
45
|
+
itemsRef.current = items;
|
|
46
|
+
const sourceRef = useRef<Map<string, { source: File | string; type: MediaType; name?: string }>>(new Map());
|
|
47
|
+
const timersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
|
|
48
|
+
|
|
49
|
+
const patch = useCallback((id: string, p: Partial<MediaItem>) => {
|
|
50
|
+
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...p } : it)));
|
|
51
|
+
}, []);
|
|
52
|
+
|
|
53
|
+
const clearTimer = (id: string) => {
|
|
54
|
+
const t = timersRef.current.get(id);
|
|
55
|
+
if (t !== undefined) {
|
|
56
|
+
clearTimeout(t);
|
|
57
|
+
timersRef.current.delete(id);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// 进度模拟:随机间隔 100-500ms、步长 5-15,累加到 MAX_SIM_PROGRESS
|
|
62
|
+
const startProgressSim = (id: string) => {
|
|
63
|
+
clearTimer(id);
|
|
64
|
+
let cur = 0;
|
|
65
|
+
const next = () => {
|
|
66
|
+
const delay = Math.floor(Math.random() * 401) + 100;
|
|
67
|
+
const t = setTimeout(() => {
|
|
68
|
+
cur = Math.min(cur + Math.floor(Math.random() * 11) + 5, MAX_SIM_PROGRESS);
|
|
69
|
+
patch(id, { uploadProgress: cur });
|
|
70
|
+
if (cur < MAX_SIM_PROGRESS) next();
|
|
71
|
+
else timersRef.current.delete(id);
|
|
72
|
+
}, delay);
|
|
73
|
+
timersRef.current.set(id, t);
|
|
74
|
+
};
|
|
75
|
+
next();
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
useEffect(
|
|
79
|
+
() => () => {
|
|
80
|
+
timersRef.current.forEach((t) => clearTimeout(t));
|
|
81
|
+
timersRef.current.clear();
|
|
82
|
+
},
|
|
83
|
+
[],
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
const doUpload = useCallback(
|
|
87
|
+
(id: string) => {
|
|
88
|
+
const rec = sourceRef.current.get(id);
|
|
89
|
+
if (!adapter || !rec) return;
|
|
90
|
+
patch(id, { isUploading: true, uploadProgress: 0, uploadFailed: false, uploadError: undefined, illegal: false });
|
|
91
|
+
startProgressSim(id);
|
|
92
|
+
|
|
93
|
+
const done = (res: { fileId: string; mimeType?: string; safed?: boolean }) => {
|
|
94
|
+
clearTimer(id);
|
|
95
|
+
patch(id, {
|
|
96
|
+
fileId: res.fileId,
|
|
97
|
+
mimeType: res.mimeType,
|
|
98
|
+
isUploading: false,
|
|
99
|
+
uploadProgress: 100,
|
|
100
|
+
...(res.safed === false ? { illegal: true } : {}),
|
|
101
|
+
});
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
(async () => {
|
|
105
|
+
try {
|
|
106
|
+
done(await adapter.upload(rec.source, { type: rec.type, name: rec.name }));
|
|
107
|
+
} catch (err) {
|
|
108
|
+
// session 过期 → 刷新并重试一次
|
|
109
|
+
if (isSessionExpiredError(err) && refreshSession) {
|
|
110
|
+
try {
|
|
111
|
+
const next = await refreshSession();
|
|
112
|
+
if (next.upload) {
|
|
113
|
+
done(await next.upload.upload(rec.source, { type: rec.type, name: rec.name }));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
} catch (retryErr) {
|
|
117
|
+
mediaLogger.warn(`上传重试失败:err=${(retryErr as Error).message}`);
|
|
118
|
+
/* 重试失败 → 落到下方失败处理 */
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
clearTimer(id);
|
|
122
|
+
patch(id, { isUploading: false, uploadFailed: true, uploadError: String((err as Error)?.message || err) });
|
|
123
|
+
}
|
|
124
|
+
})();
|
|
125
|
+
},
|
|
126
|
+
[adapter, refreshSession, patch],
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
const enqueue = useCallback(
|
|
130
|
+
(source: File | string, meta: { type: MediaType; src: string; name?: string; size?: number }) => {
|
|
131
|
+
if (!adapter) {
|
|
132
|
+
toast('上传暂不可用(未登录或未配置 TBOX 凭证)');
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const id = nid();
|
|
136
|
+
sourceRef.current.set(id, { source, type: meta.type, name: meta.name });
|
|
137
|
+
setItems((prev) => [
|
|
138
|
+
...prev,
|
|
139
|
+
{ id, type: meta.type, src: meta.src, name: meta.name, size: meta.size, isUploading: true, uploadProgress: 0 },
|
|
140
|
+
]);
|
|
141
|
+
doUpload(id);
|
|
142
|
+
},
|
|
143
|
+
[adapter, doUpload],
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const retry = useCallback((id: string) => doUpload(id), [doUpload]);
|
|
147
|
+
|
|
148
|
+
const room = () => Math.max(0, maxTotal - itemsRef.current.length);
|
|
149
|
+
|
|
150
|
+
// 校验单个待加项:超总数/分类型数量→'stop'(停止本批);超单文件大小→'skip'(跳过该文件)。
|
|
151
|
+
// 对齐原模板 useFileUpload 的 checkLimit + checkFileSize。
|
|
152
|
+
const validate = useCallback(
|
|
153
|
+
(
|
|
154
|
+
type: MediaType,
|
|
155
|
+
size: number | undefined,
|
|
156
|
+
total: number,
|
|
157
|
+
typeCount: number,
|
|
158
|
+
): 'ok' | 'skip' | 'stop' => {
|
|
159
|
+
if (total >= maxTotal) {
|
|
160
|
+
toast(`最多添加 ${maxTotal} 个文件`);
|
|
161
|
+
return 'stop';
|
|
162
|
+
}
|
|
163
|
+
const tc = mediaConfig?.[type];
|
|
164
|
+
if (tc && typeCount >= tc.maxCount) {
|
|
165
|
+
toast(`最多添加 ${tc.maxCount} 个${typeLabel(type)}`);
|
|
166
|
+
return 'stop';
|
|
167
|
+
}
|
|
168
|
+
if (tc && size && size > tc.maxSize) {
|
|
169
|
+
toast(`文件大小不能超过 ${(tc.maxSize / 1048576).toFixed(0)}MB`);
|
|
170
|
+
return 'skip';
|
|
171
|
+
}
|
|
172
|
+
return 'ok';
|
|
173
|
+
},
|
|
174
|
+
[maxTotal, mediaConfig],
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
const addFiles = useCallback(
|
|
178
|
+
(files: File[]) => {
|
|
179
|
+
let total = itemsRef.current.length;
|
|
180
|
+
const typeCounts: Record<string, number> = {};
|
|
181
|
+
for (const it of itemsRef.current) typeCounts[it.type] = (typeCounts[it.type] || 0) + 1;
|
|
182
|
+
for (const f of files) {
|
|
183
|
+
const type = fileToType(f);
|
|
184
|
+
const v = validate(type, f.size, total, typeCounts[type] || 0);
|
|
185
|
+
if (v === 'stop') break;
|
|
186
|
+
if (v === 'skip') continue;
|
|
187
|
+
enqueue(f, { type, src: URL.createObjectURL(f), name: f.name, size: f.size });
|
|
188
|
+
total += 1;
|
|
189
|
+
typeCounts[type] = (typeCounts[type] || 0) + 1;
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
[enqueue, validate],
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
const addFromBridge = useCallback(
|
|
196
|
+
async (kind: 'image' | 'camera' | 'video') => {
|
|
197
|
+
if (!adapter) {
|
|
198
|
+
toast('上传暂不可用(未登录或未配置 TBOX 凭证)');
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
const res =
|
|
203
|
+
kind === 'video'
|
|
204
|
+
? await chooseVideo()
|
|
205
|
+
: await chooseImage(room(), kind === 'camera' ? ['camera'] : undefined);
|
|
206
|
+
const type: MediaType = kind === 'video' ? 'video' : 'image';
|
|
207
|
+
let total = itemsRef.current.length;
|
|
208
|
+
let typeCount = itemsRef.current.filter((it) => it.type === type).length;
|
|
209
|
+
for (const f of res?.files || []) {
|
|
210
|
+
if (!f.data) continue;
|
|
211
|
+
const v = validate(type, f.size, total, typeCount);
|
|
212
|
+
if (v === 'stop') break;
|
|
213
|
+
if (v === 'skip') continue;
|
|
214
|
+
enqueue(f.data, { type, src: f.data, name: f.name, size: f.size });
|
|
215
|
+
total += 1;
|
|
216
|
+
typeCount += 1;
|
|
217
|
+
}
|
|
218
|
+
} catch (err) {
|
|
219
|
+
mediaLogger.warn('bridge pick failed:', err);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
[adapter, enqueue, validate],
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
const removeItem = useCallback((id: string) => {
|
|
226
|
+
clearTimer(id);
|
|
227
|
+
const rec = itemsRef.current.find((it) => it.id === id);
|
|
228
|
+
revokeIfBlob(rec?.src);
|
|
229
|
+
sourceRef.current.delete(id);
|
|
230
|
+
setItems((prev) => prev.filter((it) => it.id !== id));
|
|
231
|
+
}, []);
|
|
232
|
+
const clear = useCallback(() => {
|
|
233
|
+
timersRef.current.forEach((t) => clearTimeout(t));
|
|
234
|
+
timersRef.current.clear();
|
|
235
|
+
itemsRef.current.forEach((it) => revokeIfBlob(it.src));
|
|
236
|
+
sourceRef.current.clear();
|
|
237
|
+
setItems([]);
|
|
238
|
+
}, []);
|
|
239
|
+
const uploading = items.some((it) => it.isUploading);
|
|
240
|
+
|
|
241
|
+
return { items, addFiles, addFromBridge, removeItem, retry, clear, uploading };
|
|
242
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { useEffect } from 'react';
|
|
2
|
+
import type { CoreChatState } from '@tbox.cn/app-agent-sdk-client';
|
|
3
|
+
import { useChatStoreApi } from '../store-context';
|
|
4
|
+
import { useTTSAdapter } from '@tbox.cn/app-agent-sdk-client';
|
|
5
|
+
|
|
6
|
+
const FLUSH_MS = 300; // 累积 delta 后批量送,避免过多 WS 消息
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* TTS 自动播放:开启后订阅流式消息,**边生成边送** TTS 流式播放(对齐原模板的流式自动朗读)。
|
|
10
|
+
* 关闭 / 卸载时停止。
|
|
11
|
+
*/
|
|
12
|
+
export function useTTSAutoPlay(enabled: boolean) {
|
|
13
|
+
const tts = useTTSAdapter();
|
|
14
|
+
const store = useChatStoreApi();
|
|
15
|
+
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!enabled || !tts || !tts.startStreaming) return;
|
|
18
|
+
|
|
19
|
+
let activeId: string | null = null;
|
|
20
|
+
let prevContent = '';
|
|
21
|
+
let pending = '';
|
|
22
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
23
|
+
|
|
24
|
+
const clearTimer = () => {
|
|
25
|
+
if (timer) {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
timer = null;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
const flush = () => {
|
|
31
|
+
clearTimer();
|
|
32
|
+
if (pending) {
|
|
33
|
+
tts.sendText?.(pending);
|
|
34
|
+
pending = '';
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const enqueue = (delta: string) => {
|
|
38
|
+
pending += delta;
|
|
39
|
+
if (!timer) timer = setTimeout(flush, FLUSH_MS);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const handle = (state: CoreChatState) => {
|
|
43
|
+
const { messages, streamingMsgId } = state;
|
|
44
|
+
const msg = messages.find((m) => m.id === streamingMsgId);
|
|
45
|
+
|
|
46
|
+
// 流结束 / 无流式消息 → 结束这轮
|
|
47
|
+
if (!msg || msg.status === 'done') {
|
|
48
|
+
if (activeId) {
|
|
49
|
+
flush();
|
|
50
|
+
tts.finishStreaming?.();
|
|
51
|
+
activeId = null;
|
|
52
|
+
prevContent = '';
|
|
53
|
+
}
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
// 新流式消息 → 开一轮
|
|
57
|
+
if (msg.status === 'streaming' && msg.id !== activeId) {
|
|
58
|
+
tts.stop();
|
|
59
|
+
clearTimer();
|
|
60
|
+
pending = '';
|
|
61
|
+
activeId = msg.id;
|
|
62
|
+
prevContent = '';
|
|
63
|
+
tts.startStreaming?.();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
// 内容增量 → 入队
|
|
67
|
+
if (activeId === msg.id && msg.content.length > prevContent.length) {
|
|
68
|
+
enqueue(msg.content.slice(prevContent.length));
|
|
69
|
+
prevContent = msg.content;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const unsub = store.subscribe(handle);
|
|
74
|
+
handle(store.getState());
|
|
75
|
+
|
|
76
|
+
return () => {
|
|
77
|
+
unsub();
|
|
78
|
+
clearTimer();
|
|
79
|
+
if (activeId) tts.stop();
|
|
80
|
+
};
|
|
81
|
+
}, [enabled, tts, store]);
|
|
82
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @tbox.cn/app-agent-ui-kit:Agent 对话壳 UI 组件包(源码发布,单一模板统一化 W2-1)。
|
|
3
|
+
*
|
|
4
|
+
* 消费面:应用经 `<ChatPage store cards slots .../>` 单点装配(或自组 KitChatProvider 树);
|
|
5
|
+
* 域模块(如 mall-core)经 home 槽渲染函数自持域 UI——kit 组件零域语义。
|
|
6
|
+
* 主题:`@tbox.cn/app-agent-ui-kit/theme`(applyTheme)+ `theme/index.less`(配合纯 CSS 主题包级联)。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
// ── 首屏页面与注入位 ──
|
|
10
|
+
export { ChatPage } from './ChatPage';
|
|
11
|
+
export type { ChatPageProps } from './ChatPage';
|
|
12
|
+
// ── 行为面(W2-3 收口:SDK client 导出退役后宿主——下拉加载历史手势族)──
|
|
13
|
+
export { usePullDownHistory } from './hooks/use-pull-down-history';
|
|
14
|
+
export type { UsePullDownHistoryOptions } from './hooks/use-pull-down-history';
|
|
15
|
+
export {
|
|
16
|
+
KitChatProvider,
|
|
17
|
+
useChatStore,
|
|
18
|
+
useChatStoreApi,
|
|
19
|
+
useChatCards,
|
|
20
|
+
useChatRawCards,
|
|
21
|
+
useClientSlots,
|
|
22
|
+
} from './store-context';
|
|
23
|
+
export type { KitChatContextValue } from './store-context';
|
|
24
|
+
|
|
25
|
+
// ── chat 设置(构建期快照 + HELLO_ACK 水合) ──
|
|
26
|
+
export { configureChatConfigDefaults, useChatConfigStore } from './chat-config';
|
|
27
|
+
export type { QuickCommand } from './chat-config';
|
|
28
|
+
|
|
29
|
+
// ── 主题 ──
|
|
30
|
+
export { applyTheme, currentTheme } from './theme/theme';
|
|
31
|
+
|
|
32
|
+
// ── 卡片渲染(context 注册表注入) ──
|
|
33
|
+
export { CardRenderer, RawCardRenderer } from './components/CardRenderer';
|
|
34
|
+
|
|
35
|
+
// ── 壳组件族 ──
|
|
36
|
+
export { MessageBubble } from './components/MessageBubble';
|
|
37
|
+
export { ChatInput } from './components/ChatInput';
|
|
38
|
+
export { QuickCommands } from './components/QuickCommands';
|
|
39
|
+
export { MediaList } from './components/MediaList';
|
|
40
|
+
export { ActionBar, CopyButton, getMessageCopyText } from './components/ActionBar';
|
|
41
|
+
export { DebugButton } from './components/ActionBar/DebugButton';
|
|
42
|
+
export { default as ChatHeader } from './components/ChatHeader';
|
|
43
|
+
export { default as HistoryEntry } from './components/HistoryEntry';
|
|
44
|
+
export { default as PullDownIndicator } from './components/PullDownIndicator';
|
|
45
|
+
export { default as ReasoningBlock } from './components/ReasoningBlock';
|
|
46
|
+
export { default as ScrollToBottomButton } from './components/ScrollToBottomButton';
|
|
47
|
+
export { default as ToolCallBlock } from './components/ToolCallBlock';
|
|
48
|
+
|
|
49
|
+
// ── hooks / utils ──
|
|
50
|
+
export { useTTSAutoPlay } from './hooks/useTTSAutoPlay';
|
|
51
|
+
export { useMediaUpload } from './hooks/useMediaUpload';
|
|
52
|
+
export { toast } from './utils/toast';
|
|
53
|
+
export type { ToastTone } from './utils/toast';
|
|
54
|
+
export { copyText } from './utils/copyText';
|
|
55
|
+
export { previewImages } from './utils/imagePreview';
|
|
56
|
+
|
|
57
|
+
// ── 类型(协议类型 re-export 单一来源 + UI 层约定) ──
|
|
58
|
+
export type {
|
|
59
|
+
ChatInputMessage,
|
|
60
|
+
ChatMessage,
|
|
61
|
+
FileTypeConfig,
|
|
62
|
+
InputMethod,
|
|
63
|
+
MediaConfig,
|
|
64
|
+
MediaItem,
|
|
65
|
+
MediaType,
|
|
66
|
+
MessageRole,
|
|
67
|
+
MessageStatus,
|
|
68
|
+
ToolCallInfo,
|
|
69
|
+
} from './types';
|