@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.
- 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 +58 -3
- package/src/ChatPage.tsx +332 -0
- package/src/card/define-card.ts +34 -0
- package/src/card/primitives.test.tsx +147 -0
- package/src/card/primitives.tsx +627 -0
- package/src/card/use-card-actions.ts +86 -0
- package/src/chat-config.test.ts +46 -0
- package/src/chat-config.ts +80 -0
- package/src/components/ActionBar/DebugButton.test.tsx +84 -0
- package/src/components/ActionBar/DebugButton.tsx +53 -0
- package/src/components/ActionBar/index.test.tsx +83 -0
- package/src/components/ActionBar/index.tsx +158 -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 +290 -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 +41 -0
- package/src/components/MediaList/index.tsx +270 -0
- package/src/components/MessageBubble/index.test.tsx +134 -0
- package/src/components/MessageBubble/index.tsx +202 -0
- package/src/components/PullDownIndicator/index.tsx +31 -0
- package/src/components/QuickCommands/index.test.tsx +99 -0
- package/src/components/QuickCommands/index.tsx +52 -0
- package/src/components/ReasoningBlock/index.tsx +61 -0
- package/src/components/ScrollToBottomButton/index.tsx +8 -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 +230 -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 +122 -0
- package/src/shell.contract.json +59 -0
- package/src/shell.test.ts +61 -0
- package/src/shell.ts +45 -0
- package/src/store-context.tsx +92 -0
- package/src/test/setup.ts +7 -0
- package/src/theme/base.css +132 -0
- package/src/theme/contract.json +72 -0
- package/src/theme/motion.css +19 -0
- package/src/theme/theme-contract.test.ts +69 -0
- package/src/theme/theme.ts +17 -0
- package/src/theme/tokens.css +81 -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,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 容器级拖拽手势绑定(pointer 优先,touch 回退)。
|
|
3
|
+
*
|
|
4
|
+
* 两条必须绕开 React 合成事件的理由:
|
|
5
|
+
* 1. React 的 touchmove 注册在 root 上且是 passive,其中的 preventDefault() 必然失败——
|
|
6
|
+
* 桌面靠 overscroll-behavior 兜住,web-view(旧 WebKit)会被原生滚动吞掉手势。
|
|
7
|
+
* 2. 触摸设备上需要覆盖单指轻扫与单指拖拽,两者都只经 touch/pointer 通道。
|
|
8
|
+
*
|
|
9
|
+
* 因此统一在容器元素上绑 Pointer Events(非 passive),无 PointerEvent 的运行时回退 touch。
|
|
10
|
+
* 页面不再往 JSX 上绑手势事件,避免同一手势走两遍。
|
|
11
|
+
*
|
|
12
|
+
* **刻意不响应鼠标拖拽**(pointerType === 'mouse'):桌面按住鼠标拖动页面不是自然交互
|
|
13
|
+
* (那里的惯例是选中文本),桌面的下拉意图由触控板双指滑动表达、走 wheel 通道。
|
|
14
|
+
*/
|
|
15
|
+
import { useEffect, useRef } from 'react';
|
|
16
|
+
|
|
17
|
+
export interface DragGestureHandlers {
|
|
18
|
+
onStart: (point: { clientY: number }) => void;
|
|
19
|
+
/** 返回 true 表示本次由手势接管,需阻止原生滚动。 */
|
|
20
|
+
onMove: (point: { clientY: number }) => boolean;
|
|
21
|
+
onEnd: () => void;
|
|
22
|
+
onCancel?: () => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface UseDragGestureOptions extends DragGestureHandlers {
|
|
26
|
+
scrollRef?: React.RefObject<HTMLElement | null>;
|
|
27
|
+
disabled?: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function useDragGesture({
|
|
31
|
+
scrollRef,
|
|
32
|
+
disabled,
|
|
33
|
+
onStart,
|
|
34
|
+
onMove,
|
|
35
|
+
onEnd,
|
|
36
|
+
onCancel,
|
|
37
|
+
}: UseDragGestureOptions): void {
|
|
38
|
+
// handler 存 ref:容器监听只在 disabled/元素变化时重绑,避免每次渲染 add/remove 抖动
|
|
39
|
+
const handlersRef = useRef<DragGestureHandlers>({ onStart, onMove, onEnd, onCancel });
|
|
40
|
+
handlersRef.current = { onStart, onMove, onEnd, onCancel };
|
|
41
|
+
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
const el = scrollRef?.current;
|
|
44
|
+
if (!el || disabled) return undefined;
|
|
45
|
+
|
|
46
|
+
const usePointer = typeof window !== 'undefined' && 'PointerEvent' in window;
|
|
47
|
+
let dragging = false;
|
|
48
|
+
|
|
49
|
+
const preventIfTaken = (event: Event, taken: boolean) => {
|
|
50
|
+
if (taken && event.cancelable) event.preventDefault();
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// ── pointer 路径(mouse / touch / pen 统一)──
|
|
54
|
+
/** 鼠标不参与拖拽手势:桌面下拉意图走 wheel(触控板双指),见文件头说明。 */
|
|
55
|
+
const isDragPointer = (e: PointerEvent) => e.pointerType !== 'mouse';
|
|
56
|
+
|
|
57
|
+
const onPointerDown = (e: PointerEvent) => {
|
|
58
|
+
if (!isDragPointer(e)) return;
|
|
59
|
+
dragging = true;
|
|
60
|
+
handlersRef.current.onStart({ clientY: e.clientY });
|
|
61
|
+
};
|
|
62
|
+
const onPointerMove = (e: PointerEvent) => {
|
|
63
|
+
if (!dragging || !isDragPointer(e)) return;
|
|
64
|
+
preventIfTaken(e, handlersRef.current.onMove({ clientY: e.clientY }));
|
|
65
|
+
};
|
|
66
|
+
const onPointerUp = () => {
|
|
67
|
+
if (!dragging) return;
|
|
68
|
+
dragging = false;
|
|
69
|
+
handlersRef.current.onEnd();
|
|
70
|
+
};
|
|
71
|
+
const onPointerCancel = () => {
|
|
72
|
+
if (!dragging) return;
|
|
73
|
+
dragging = false;
|
|
74
|
+
(handlersRef.current.onCancel ?? handlersRef.current.onEnd)();
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// ── touch 回退(无 PointerEvent 的旧 WebView)──
|
|
78
|
+
const onTouchStart = (e: TouchEvent) => {
|
|
79
|
+
const touch = e.touches[0];
|
|
80
|
+
if (!touch) return;
|
|
81
|
+
dragging = true;
|
|
82
|
+
handlersRef.current.onStart({ clientY: touch.clientY });
|
|
83
|
+
};
|
|
84
|
+
const onTouchMove = (e: TouchEvent) => {
|
|
85
|
+
const touch = e.touches[0];
|
|
86
|
+
if (!touch || !dragging) return;
|
|
87
|
+
preventIfTaken(e, handlersRef.current.onMove({ clientY: touch.clientY }));
|
|
88
|
+
};
|
|
89
|
+
const onTouchEnd = () => {
|
|
90
|
+
if (!dragging) return;
|
|
91
|
+
dragging = false;
|
|
92
|
+
handlersRef.current.onEnd();
|
|
93
|
+
};
|
|
94
|
+
const onTouchCancel = () => {
|
|
95
|
+
if (!dragging) return;
|
|
96
|
+
dragging = false;
|
|
97
|
+
(handlersRef.current.onCancel ?? handlersRef.current.onEnd)();
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
if (usePointer) {
|
|
101
|
+
el.addEventListener('pointerdown', onPointerDown, { passive: true });
|
|
102
|
+
el.addEventListener('pointermove', onPointerMove, { passive: false });
|
|
103
|
+
el.addEventListener('pointerup', onPointerUp, { passive: true });
|
|
104
|
+
el.addEventListener('pointercancel', onPointerCancel, { passive: true });
|
|
105
|
+
// 指针移出容器(鼠标拖到窗口外松开)同样收口,否则位移悬挂
|
|
106
|
+
el.addEventListener('pointerleave', onPointerUp, { passive: true });
|
|
107
|
+
} else {
|
|
108
|
+
el.addEventListener('touchstart', onTouchStart, { passive: true });
|
|
109
|
+
el.addEventListener('touchmove', onTouchMove, { passive: false });
|
|
110
|
+
el.addEventListener('touchend', onTouchEnd, { passive: true });
|
|
111
|
+
el.addEventListener('touchcancel', onTouchCancel, { passive: true });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return () => {
|
|
115
|
+
if (usePointer) {
|
|
116
|
+
el.removeEventListener('pointerdown', onPointerDown);
|
|
117
|
+
el.removeEventListener('pointermove', onPointerMove);
|
|
118
|
+
el.removeEventListener('pointerup', onPointerUp);
|
|
119
|
+
el.removeEventListener('pointercancel', onPointerCancel);
|
|
120
|
+
el.removeEventListener('pointerleave', onPointerUp);
|
|
121
|
+
} else {
|
|
122
|
+
el.removeEventListener('touchstart', onTouchStart);
|
|
123
|
+
el.removeEventListener('touchmove', onTouchMove);
|
|
124
|
+
el.removeEventListener('touchend', onTouchEnd);
|
|
125
|
+
el.removeEventListener('touchcancel', onTouchCancel);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}, [disabled, scrollRef]);
|
|
129
|
+
}
|
|
@@ -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
|
+
}
|