@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.
Files changed (79) 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 +55 -3
  11. package/src/ChatPage.less +62 -0
  12. package/src/ChatPage.tsx +305 -0
  13. package/src/chat-config.test.ts +82 -0
  14. package/src/chat-config.ts +62 -0
  15. package/src/components/ActionBar/DebugButton.test.tsx +84 -0
  16. package/src/components/ActionBar/DebugButton.tsx +53 -0
  17. package/src/components/ActionBar/index.less +123 -0
  18. package/src/components/ActionBar/index.test.tsx +83 -0
  19. package/src/components/ActionBar/index.tsx +159 -0
  20. package/src/components/CardRenderer.tsx +36 -0
  21. package/src/components/ChatHeader/index.less +148 -0
  22. package/src/components/ChatHeader/index.test.tsx +74 -0
  23. package/src/components/ChatHeader/index.tsx +75 -0
  24. package/src/components/ChatInput/index.less +394 -0
  25. package/src/components/ChatInput/index.test.tsx +156 -0
  26. package/src/components/ChatInput/index.tsx +284 -0
  27. package/src/components/ChatInput/voice/VoicePressField.tsx +34 -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.less +49 -0
  32. package/src/components/HistoryEntry/index.tsx +42 -0
  33. package/src/components/MediaList/index.less +241 -0
  34. package/src/components/MediaList/index.tsx +256 -0
  35. package/src/components/MessageBubble/index.less +325 -0
  36. package/src/components/MessageBubble/index.test.tsx +134 -0
  37. package/src/components/MessageBubble/index.tsx +177 -0
  38. package/src/components/PullDownIndicator/index.less +32 -0
  39. package/src/components/PullDownIndicator/index.tsx +32 -0
  40. package/src/components/QuickCommands/index.less +63 -0
  41. package/src/components/QuickCommands/index.test.tsx +99 -0
  42. package/src/components/QuickCommands/index.tsx +52 -0
  43. package/src/components/ReasoningBlock/index.less +90 -0
  44. package/src/components/ReasoningBlock/index.tsx +56 -0
  45. package/src/components/ScrollToBottomButton/index.less +32 -0
  46. package/src/components/ScrollToBottomButton/index.tsx +10 -0
  47. package/src/components/ToolCallBlock/detail.test.ts +346 -0
  48. package/src/components/ToolCallBlock/detail.ts +204 -0
  49. package/src/components/ToolCallBlock/index.less +312 -0
  50. package/src/components/ToolCallBlock/index.test.tsx +261 -0
  51. package/src/components/ToolCallBlock/index.tsx +212 -0
  52. package/src/components/ToolCallBlock/titles.ts +102 -0
  53. package/src/hooks/use-drag-gesture.test.ts +66 -0
  54. package/src/hooks/use-drag-gesture.ts +129 -0
  55. package/src/hooks/use-pull-down-history.ts +241 -0
  56. package/src/hooks/use-pull-down-wheel-native.test.ts +64 -0
  57. package/src/hooks/useMediaUpload.ts +242 -0
  58. package/src/hooks/useTTSAutoPlay.ts +82 -0
  59. package/src/index.ts +69 -0
  60. package/src/store-context.tsx +92 -0
  61. package/src/test/setup.ts +7 -0
  62. package/src/theme/contract.json +72 -0
  63. package/src/theme/global.less +99 -0
  64. package/src/theme/motion.less +19 -0
  65. package/src/theme/theme-contract.test.ts +69 -0
  66. package/src/theme/theme.ts +17 -0
  67. package/src/theme/tokens.less +79 -0
  68. package/src/types.ts +29 -0
  69. package/src/utils/copyText.ts +11 -0
  70. package/src/utils/haptics.test.ts +51 -0
  71. package/src/utils/haptics.ts +44 -0
  72. package/src/utils/imagePreview.ts +10 -0
  73. package/src/utils/pull-down-machine.test.ts +188 -0
  74. package/src/utils/pull-down-machine.ts +157 -0
  75. package/src/utils/session-error.ts +5 -0
  76. package/src/utils/toast.ts +15 -0
  77. package/src/utils/tool-call-display.test.ts +240 -0
  78. package/src/utils/tool-call-display.ts +146 -0
  79. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,212 @@
1
+ import { useId, useMemo, useState } from 'react';
2
+ import { CaretDown, Check, Copy, X } from '@phosphor-icons/react';
3
+ import type { ToolCallInfo } from '../../types';
4
+ import { formatCompactToolIo } from '../../utils/tool-call-display';
5
+ import { buildSummaryText, deriveSummary, deriveToolCallItem, prettyDetailText } from './detail';
6
+ import type { ToolCallViewItem } from './detail';
7
+ import { copyText } from '../../utils/copyText';
8
+ import { toast } from '../../utils/toast';
9
+ import './index.less';
10
+
11
+ const EMPTY_TEXT = '(无)';
12
+
13
+ const STATUS_TEXT: Record<ToolCallViewItem['status'], string> = {
14
+ done: '成功',
15
+ error: '失败',
16
+ calling: '执行中',
17
+ };
18
+
19
+ /**
20
+ * Codex 风格工具活动日志:紧凑聚合行 / 流内活动列表 / 行内完整 IO。
21
+ * 语义判定仍在 SDK describeToolCall + detail.ts 视图模型,本组件只管理展示状态;
22
+ * debug 门控在渲染层(018 tool-debug):prod 恒无出入参展开入口(I4),
23
+ * dev 行标题附技术名、详情走紧凑单行格式(复制仍为美化全文);
24
+ * 图标颜色不传 color prop(phosphor 落 SVG fill 属性,var() 低版本 web-view 不可靠),
25
+ * 统一走 currentColor + less token 类。
26
+ */
27
+ export default function ToolCallBlock({
28
+ toolCalls,
29
+ debug = false,
30
+ }: {
31
+ toolCalls: ToolCallInfo[];
32
+ /** 018 tool-debug:dev 视图(出入参展开 + 技术名 + 紧凑格式);prod 缺省 false */
33
+ debug?: boolean;
34
+ }) {
35
+ const [expanded, setExpanded] = useState(false);
36
+ const [expandedDetailIds, setExpandedDetailIds] = useState<Set<string>>(() => new Set());
37
+ const listId = useId();
38
+ const items = useMemo(() => toolCalls.map(deriveToolCallItem), [toolCalls]);
39
+ const summary = useMemo(() => deriveSummary(items), [items]);
40
+
41
+ const toggleDetail = (id: string) => {
42
+ setExpandedDetailIds((current) => {
43
+ const next = new Set(current);
44
+ if (next.has(id)) next.delete(id);
45
+ else next.add(id);
46
+ return next;
47
+ });
48
+ };
49
+
50
+ return (
51
+ <div className="tool-calls">
52
+ <button
53
+ type="button"
54
+ className={`tool-calls__summary${summary.calling ? ' tool-calls__summary--calling' : ''}`}
55
+ aria-expanded={expanded}
56
+ aria-controls={listId}
57
+ onClick={() => setExpanded((current) => !current)}
58
+ >
59
+ <span className="tool-calls__left">
60
+ {summary.calling ? (
61
+ <span className="tool-calls__spinner" aria-hidden="true" />
62
+ ) : summary.failedCount > 0 ? (
63
+ <X className="tool-calls__icon tool-calls__icon--error" size={16} strokeWidth={2.5} />
64
+ ) : (
65
+ <Check className="tool-calls__icon tool-calls__icon--success" size={16} strokeWidth={2.5} />
66
+ )}
67
+ <span className="tool-calls__summary-text">
68
+ {buildSummaryText(summary).join(' · ')}
69
+ {summary.failedCount > 0 && (
70
+ <span className="tool-calls__failed"> · {summary.failedCount} 个失败</span>
71
+ )}
72
+ </span>
73
+ </span>
74
+ <CaretDown
75
+ size={14}
76
+ className={`tool-calls__chevron${expanded ? ' tool-calls__chevron--up' : ''}`}
77
+ />
78
+ </button>
79
+
80
+ {expanded && (
81
+ <div id={listId} className="tool-calls__list">
82
+ {items.map((item) => {
83
+ // 018 I4:prod(debug=false)恒无出入参展开入口;dev 才有详情交互
84
+ const hasDetail = debug && !!item.detail;
85
+ const detailExpanded = hasDetail && expandedDetailIds.has(item.id);
86
+ const detailId = `${listId}-${item.id}`;
87
+ const itemContent = (
88
+ <>
89
+ <span className="tool-calls__item-left">
90
+ {item.status === 'calling' && (
91
+ <span className="tool-calls__spinner tool-calls__spinner--sm" />
92
+ )}
93
+ {item.status === 'done' && (
94
+ <Check className="tool-calls__icon tool-calls__icon--success" size={14} strokeWidth={2.5} />
95
+ )}
96
+ {item.status === 'error' && (
97
+ <X className="tool-calls__icon tool-calls__icon--error" size={14} strokeWidth={2.5} />
98
+ )}
99
+ <span className="tool-calls__item-name">
100
+ {item.label}
101
+ {debug && item.techName && (
102
+ <span className="tool-calls__item-tech"> · {item.techName}</span>
103
+ )}
104
+ </span>
105
+ {item.badge && (
106
+ <span className="tool-calls__badge">· {item.badge}</span>
107
+ )}
108
+ </span>
109
+ {hasDetail && (
110
+ <CaretDown
111
+ size={12}
112
+ className={`tool-calls__item-chevron${detailExpanded ? ' tool-calls__item-chevron--up' : ''}`}
113
+ />
114
+ )}
115
+ </>
116
+ );
117
+
118
+ return (
119
+ <div key={item.id} className={`tool-calls__item tool-calls__item--${item.status}`}>
120
+ {hasDetail ? (
121
+ <button
122
+ type="button"
123
+ className="tool-calls__item-trigger"
124
+ aria-expanded={detailExpanded}
125
+ aria-controls={detailId}
126
+ aria-label={`${item.label},${STATUS_TEXT[item.status]},${detailExpanded ? '收起详情' : '查看详情'}`}
127
+ onClick={() => toggleDetail(item.id)}
128
+ >
129
+ {itemContent}
130
+ </button>
131
+ ) : (
132
+ <div
133
+ className="tool-calls__item-trigger tool-calls__item-trigger--static"
134
+ role="status"
135
+ aria-label={`${item.label},${STATUS_TEXT[item.status]}`}
136
+ >
137
+ {itemContent}
138
+ </div>
139
+ )}
140
+ {detailExpanded && item.detail && (
141
+ <ToolCallInlineDetail id={detailId} item={item} />
142
+ )}
143
+ </div>
144
+ );
145
+ })}
146
+ </div>
147
+ )}
148
+ </div>
149
+ );
150
+ }
151
+
152
+ /**
153
+ * 018 dev 详情区:屏显走 formatCompactToolIo(单行紧凑 + 头尾保留);
154
+ * 复制走 prettyDetailText(美化全文)——屏显紧凑、粘贴友好分工。
155
+ */
156
+ function ToolCallInlineDetail({ id, item }: { id: string; item: ToolCallViewItem }) {
157
+ const formatted = useMemo(
158
+ () => ({
159
+ input: formatCompactToolIo(item.detail?.inputText ?? ''),
160
+ output: formatCompactToolIo(item.detail?.outputText ?? ''),
161
+ inputPretty: prettyDetailText(item.detail?.inputText ?? ''),
162
+ outputPretty: prettyDetailText(item.detail?.outputText ?? ''),
163
+ }),
164
+ [item],
165
+ );
166
+
167
+ const copyIo = async (text: string, label: string) => {
168
+ const copied = await copyText(text);
169
+ void toast(copied ? `${label}已复制` : '复制失败,请重试', copied ? 'success' : 'error');
170
+ };
171
+
172
+ return (
173
+ <div id={id} className="tool-calls__detail">
174
+ <div className="tool-calls__detail-section">
175
+ <div className="tool-calls__detail-heading">
176
+ <span className="tool-calls__detail-label">输入</span>
177
+ <button
178
+ type="button"
179
+ className="tool-calls__copy"
180
+ aria-label={`复制${item.label}的输入`}
181
+ disabled={!formatted.inputPretty}
182
+ onClick={() => void copyIo(formatted.inputPretty, '输入')}
183
+ >
184
+ <Copy size={13} />
185
+ <span>复制</span>
186
+ </button>
187
+ </div>
188
+ <pre className="tool-calls__detail-body">{formatted.input || EMPTY_TEXT}</pre>
189
+ </div>
190
+ <div className="tool-calls__detail-section">
191
+ <div className="tool-calls__detail-heading">
192
+ <span className="tool-calls__detail-label">输出</span>
193
+ <button
194
+ type="button"
195
+ className="tool-calls__copy"
196
+ aria-label={`复制${item.label}的输出`}
197
+ disabled={!formatted.outputPretty}
198
+ onClick={() => void copyIo(formatted.outputPretty, '输出')}
199
+ >
200
+ <Copy size={13} />
201
+ <span>复制</span>
202
+ </button>
203
+ </div>
204
+ <pre
205
+ className={`tool-calls__detail-body${item.detail?.isError ? ' tool-calls__detail-body--error' : ''}`}
206
+ >
207
+ {formatted.output || EMPTY_TEXT}
208
+ </pre>
209
+ </div>
210
+ </div>
211
+ );
212
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Mall 工具活动标题:只改变展示,不改协议中的技术 name。
3
+ * 当前模块工具使用精确中文标题;未知英文工具使用中文通用兜底,避免把技术标识泄漏到用户标题面。
4
+ */
5
+ const TOOL_TITLE_BY_NAME: Readonly<Record<string, string>> = {
6
+ // 会员
7
+ queryPoints: '查询会员积分',
8
+ queryMemberInfo: '查询会员信息',
9
+ queryMemberCard: '查询会员卡',
10
+ queryEnrollmentForm: '查询入会状态',
11
+ queryEnrollmentCta: '准备入会指引',
12
+ queryLoginCta: '准备登录指引',
13
+
14
+ // 商场导购
15
+ recommend: '推荐商品',
16
+ 'search-products': '搜索商品',
17
+ 'product-facets': '查询商品筛选项',
18
+ 'get-product': '查询商品详情',
19
+ 'compare-products': '对比商品',
20
+ 'search-shops': '搜索商场门店',
21
+ 'get-shop': '查询门店详情',
22
+ 'mall-directory': '查询商场楼层',
23
+ 'get-location': '查询门店位置',
24
+ 'list-human-guides': '查询人工导购',
25
+ 'list-browsing-history': '查询浏览记录',
26
+ 'list-nearby-malls': '查询附近商场',
27
+ 'list-categories': '查询商场业态',
28
+ 'search-knowledge': '检索商场知识',
29
+ 'customer-service-faq': '查询客服问题',
30
+ 'mall-context': '加载商场信息',
31
+ 'mall-info': '查询商场信息',
32
+
33
+ // 停车
34
+ queryParkingFee: '查询停车费用',
35
+ listVehicles: '查询已绑车辆',
36
+ listPaymentRecords: '查询停车缴费记录',
37
+ queryParkingInfo: '查询停车场信息',
38
+ queryApplicableBenefits: '查询停车权益',
39
+ locateVehicle: '查找车辆位置',
40
+ listInvoiceableOrders: '查询可开票订单',
41
+ queryParkingPaymentStatus: '查询停车支付状态',
42
+ queryParkingPaymentDetail: '查询停车订单详情',
43
+
44
+ // 优惠活动
45
+ listActivityCategories: '查询活动分类',
46
+ listActivities: '查询商场活动',
47
+ getActivityDetail: '查询活动详情',
48
+ listActivitySessions: '查询活动场次',
49
+ getActivityGuide: '查询活动参与指南',
50
+ searchOffers: '搜索优惠',
51
+ getOfferDetail: '查询优惠详情',
52
+ listEntitlements: '查询我的优惠',
53
+ listPromotions: '查询促销活动',
54
+ getPromotionDetail: '查询促销详情',
55
+ getParticipationGuide: '查询参与步骤',
56
+ listCoupons: '查询优惠券',
57
+ getPackageDetail: '查询礼包详情',
58
+ recommendOffers: '推荐可用优惠',
59
+ calculateBestDeal: '测算最佳优惠',
60
+
61
+ // 碰出惊喜与平台前置工具
62
+ getBumpInActivity: '查询碰出惊喜活动',
63
+ getBumpInActivityBanner: '加载碰出惊喜活动',
64
+ getCurrentTime: '获取当前时间',
65
+
66
+ // 历史命名与确定性 Gallery 别名
67
+ 'member-balance': '查询会员余额',
68
+ 'parking-fee': '查询停车费用',
69
+ 'parking-fee-context': '加载停车费用信息',
70
+ search_stores: '搜索商场门店',
71
+ search_mall_services: '搜索商场服务',
72
+ get_member_points: '查询会员积分',
73
+ load_parking_order: '查询停车订单',
74
+ search_nearby_stores: '搜索附近门店',
75
+ read_store_opening_hours: '查询门店营业时间',
76
+ search_shops_with_member_benefits_and_parking_validation_rules_for_current_mall: '搜索会员权益门店',
77
+ pay_order: '提交支付订单',
78
+ };
79
+
80
+ const HAN_TEXT = /[\u3400-\u9fff]/u;
81
+ const MAX_TITLE_LENGTH = 28;
82
+
83
+ function compactChineseTitle(value: string | undefined): string | undefined {
84
+ if (!value || !HAN_TEXT.test(value)) return undefined;
85
+ const firstClause = value.trim().split(/[\n。;;]/u, 1)[0]?.trim();
86
+ if (!firstClause) return undefined;
87
+ return firstClause.length > MAX_TITLE_LENGTH
88
+ ? `${firstClause.slice(0, MAX_TITLE_LENGTH - 1)}…`
89
+ : firstClause;
90
+ }
91
+
92
+ /** 中文描述 > 已登记中文标题 > 原始中文名 > 中文通用兜底。 */
93
+ export function resolveToolTitle(
94
+ technicalName: string,
95
+ preferredText?: string,
96
+ fallback = '处理工具任务',
97
+ ): string {
98
+ return compactChineseTitle(preferredText)
99
+ ?? TOOL_TITLE_BY_NAME[technicalName]
100
+ ?? compactChineseTitle(technicalName)
101
+ ?? fallback;
102
+ }
@@ -0,0 +1,66 @@
1
+ // @vitest-environment happy-dom
2
+ /**
3
+ * 手势通道用例。核心契约:触摸/笔参与拖拽,鼠标不参与——桌面的下拉意图由触控板双指滑动
4
+ * 经 wheel 表达,按住鼠标拖页面在桌面上是选中文本的惯例,不该触发下拉。
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 } from 'react';
10
+ import { useDragGesture } from './use-drag-gesture';
11
+
12
+ function pointer(type: string, clientY: number, name: string) {
13
+ const e = new Event(name, { bubbles: true, cancelable: true }) as PointerEvent;
14
+ Object.defineProperties(e, {
15
+ pointerType: { value: type },
16
+ clientY: { value: clientY },
17
+ });
18
+ return e;
19
+ }
20
+
21
+ /** 极简 hook 宿主:仓库内既有写法(createRoot + flushSync),不引入额外测试依赖。 */
22
+ function setup() {
23
+ const el = document.createElement('div');
24
+ document.body.appendChild(el);
25
+ const handlers = { onStart: vi.fn(), onMove: vi.fn(() => true), onEnd: vi.fn() };
26
+ const Host = () => {
27
+ useDragGesture({ scrollRef: { current: el }, ...handlers });
28
+ return null;
29
+ };
30
+ const host = document.createElement('div');
31
+ document.body.appendChild(host);
32
+ flushSync(() => createRoot(host).render(createElement(Host)));
33
+ return { el, handlers };
34
+ }
35
+
36
+ describe('useDragGesture', () => {
37
+ it('D1 触摸指针参与拖拽', () => {
38
+ const { el, handlers } = setup();
39
+ el.dispatchEvent(pointer('touch', 100, 'pointerdown'));
40
+ el.dispatchEvent(pointer('touch', 160, 'pointermove'));
41
+ expect(handlers.onStart).toHaveBeenCalledWith({ clientY: 100 });
42
+ expect(handlers.onMove).toHaveBeenCalledWith({ clientY: 160 });
43
+ });
44
+
45
+ it('D2 鼠标拖拽被忽略(桌面单指拖拽不响应,交给 wheel 通道)', () => {
46
+ const { el, handlers } = setup();
47
+ el.dispatchEvent(pointer('mouse', 100, 'pointerdown'));
48
+ el.dispatchEvent(pointer('mouse', 160, 'pointermove'));
49
+ expect(handlers.onStart).not.toHaveBeenCalled();
50
+ expect(handlers.onMove).not.toHaveBeenCalled();
51
+ });
52
+
53
+ it('D3 笔同触摸(手写笔在触屏设备上是等价输入)', () => {
54
+ const { el, handlers } = setup();
55
+ el.dispatchEvent(pointer('pen', 50, 'pointerdown'));
56
+ el.dispatchEvent(pointer('pen', 90, 'pointermove'));
57
+ expect(handlers.onStart).toHaveBeenCalledTimes(1);
58
+ expect(handlers.onMove).toHaveBeenCalledTimes(1);
59
+ });
60
+
61
+ it('D4 未按下时的移动不算拖拽', () => {
62
+ const { el, handlers } = setup();
63
+ el.dispatchEvent(pointer('touch', 160, 'pointermove'));
64
+ expect(handlers.onMove).not.toHaveBeenCalled();
65
+ });
66
+ });
@@ -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
+ }