tavern-harness 0.1.12 → 0.1.13

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 (47) hide show
  1. package/CHANGELOG.md +345 -0
  2. package/README.md +12 -4
  3. package/README.zh.md +12 -4
  4. package/bin/cli.js +16 -2
  5. package/index.html +3 -1
  6. package/package.json +18 -5
  7. package/persistence-server.mjs +303 -0
  8. package/public/sillytavern-logo.png +0 -0
  9. package/src/App.tsx +72 -8
  10. package/src/components/CharactersView.tsx +221 -68
  11. package/src/components/ChatView.tsx +98 -69
  12. package/src/components/FileDisplayModal.tsx +28 -17
  13. package/src/components/NewSessionMenu.tsx +2 -9
  14. package/src/components/PopoverMenu.tsx +54 -0
  15. package/src/components/SettingsView.tsx +21 -1
  16. package/src/components/Sidebar.tsx +133 -53
  17. package/src/components/VersionHistoryModal.tsx +114 -0
  18. package/src/components/shared.tsx +12 -3
  19. package/src/core/browserPreferences.ts +45 -0
  20. package/src/core/changelog.ts +43 -0
  21. package/src/core/characterBook.ts +32 -0
  22. package/src/core/clipboard.ts +32 -0
  23. package/src/core/editable.ts +26 -0
  24. package/src/core/gameplay.ts +2 -0
  25. package/src/core/i18n.ts +141 -10
  26. package/src/core/longPress.ts +209 -0
  27. package/src/core/longPressGesture.ts +110 -0
  28. package/src/core/mobileViewport.ts +362 -0
  29. package/src/core/openai.ts +39 -7
  30. package/src/core/sillyTavernWorldInfo.ts +159 -0
  31. package/src/core/sortableSensors.ts +21 -0
  32. package/src/core/stickyBottom.ts +45 -0
  33. package/src/core/tools/generatedSkillExecutor.ts +4 -20
  34. package/src/core/version.ts +46 -0
  35. package/src/core/viewport.ts +81 -0
  36. package/src/core/wechatTouch.ts +145 -0
  37. package/src/db/database.ts +313 -2
  38. package/src/generated/changelog.json +510 -0
  39. package/src/main.tsx +18 -2
  40. package/src/store/store.ts +99 -33
  41. package/src/theme/chat.css +174 -49
  42. package/src/theme/global.css +391 -10
  43. package/src/theme/theme.ts +9 -2
  44. package/src/theme/views.css +341 -8
  45. package/src/types/models.ts +9 -0
  46. package/src/vite-env.d.ts +4 -1
  47. package/vite.config.ts +184 -17
@@ -0,0 +1,159 @@
1
+ // ============================================================
2
+ // SillyTavern 世界书(World Info / Lorebook)JSON 导入
3
+ // ============================================================
4
+ // 支持两种 entries 结构:
5
+ // - 对象映射:{ "0": {...}, "1": {...} }(SillyTavern 导出格式)
6
+ // - 数组:[{...}, {...}](Character Book 格式)
7
+ // 输出统一为角色卡 Character Book JSON,字段标准与角色卡知识库完全一致。
8
+
9
+ export interface ParsedSillyTavernWorldBook {
10
+ /** 世界书名(优先取 JSON 的 name,否则回退到文件名) */
11
+ name: string;
12
+ /** 世界书固定内容(SillyTavern 的 description,可为空) */
13
+ content: string;
14
+ /** 归一化后的 Character Book JSON */
15
+ characterBook: string;
16
+ entryCount: number;
17
+ /** 启用且内容非空的条目数(会参与关键词召回) */
18
+ enabledEntryCount: number;
19
+ }
20
+
21
+ function asRecord(value: unknown): Record<string, unknown> | null {
22
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
23
+ }
24
+
25
+ function stringValue(value: unknown): string {
26
+ return typeof value === 'string' ? value : '';
27
+ }
28
+
29
+ function stringArray(value: unknown): string[] {
30
+ return Array.isArray(value)
31
+ ? value.filter((item): item is string => typeof item === 'string').map((item) => item.trim()).filter(Boolean)
32
+ : [];
33
+ }
34
+
35
+ function booleanValue(value: unknown, fallback: boolean): boolean {
36
+ return typeof value === 'boolean' ? value : fallback;
37
+ }
38
+
39
+ function numberValue(value: unknown): number | undefined {
40
+ if (value === null || value === undefined || value === '') return undefined;
41
+ const number = Number(value);
42
+ return Number.isFinite(number) ? number : undefined;
43
+ }
44
+
45
+ function firstNumber(...values: unknown[]): number | undefined {
46
+ for (const value of values) {
47
+ const number = numberValue(value);
48
+ if (number != null) return number;
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ /** 把单条 SillyTavern 世界书条目归一化为 Character Book 条目字段。 */
54
+ function normalizeEntry(value: unknown, index: number): Record<string, unknown> | null {
55
+ const entry = asRecord(value);
56
+ if (!entry) return null;
57
+
58
+ const keys = stringArray(entry.keys ?? entry.key);
59
+ const secondaryKeys = stringArray(entry.secondary_keys ?? entry.keysecondary);
60
+ const comment = stringValue(entry.comment).trim();
61
+ const name = stringValue(entry.name).trim() || comment;
62
+ const content = stringValue(entry.content);
63
+ // SillyTavern 用 disable 表示停用,新版导出同时带 enabled;两者都存在时以 enabled 为准。
64
+ const enabled = entry.enabled !== undefined
65
+ ? entry.enabled !== false
66
+ : entry.disable !== true;
67
+
68
+ const normalized: Record<string, unknown> = {
69
+ id: entry.id ?? entry.uid ?? index,
70
+ keys,
71
+ secondary_keys: secondaryKeys,
72
+ content,
73
+ enabled,
74
+ constant: booleanValue(entry.constant, false),
75
+ selective: booleanValue(entry.selective, false),
76
+ selective_logic: firstNumber(entry.selective_logic, entry.selectiveLogic) ?? 0,
77
+ insertion_order: firstNumber(entry.insertion_order, entry.order, entry.priority) ?? index,
78
+ };
79
+ if (name) normalized.name = name;
80
+ if (comment) normalized.comment = comment;
81
+ if (entry.priority !== undefined) {
82
+ const priority = numberValue(entry.priority);
83
+ if (priority != null) normalized.priority = priority;
84
+ }
85
+ if (entry.case_sensitive !== undefined) normalized.case_sensitive = booleanValue(entry.case_sensitive, false);
86
+ if (entry.match_whole_words !== undefined) normalized.match_whole_words = booleanValue(entry.match_whole_words, false);
87
+ if (entry.useProbability !== undefined) normalized.useProbability = booleanValue(entry.useProbability, false);
88
+ if (entry.probability !== undefined) {
89
+ const probability = numberValue(entry.probability);
90
+ if (probability != null) normalized.probability = probability;
91
+ }
92
+ if (entry.position !== undefined) normalized.position = entry.position;
93
+ if (entry.depth !== undefined) {
94
+ const depth = numberValue(entry.depth);
95
+ if (depth != null) normalized.depth = depth;
96
+ }
97
+ if (entry.excludeRecursion !== undefined) normalized.excludeRecursion = booleanValue(entry.excludeRecursion, false);
98
+ if (entry.extensions !== undefined) normalized.extensions = entry.extensions;
99
+ if (entry.characterFilter !== undefined) normalized.characterFilter = entry.characterFilter;
100
+ return normalized;
101
+ }
102
+
103
+ /**
104
+ * 解析 SillyTavern 世界书 JSON 文本。
105
+ * 失败时抛出带可读原因的 Error;成功时返回可直接写入世界书知识库的 Character Book JSON。
106
+ */
107
+ export function parseSillyTavernWorldInfoJson(raw: string, fallbackName = 'Imported world book'): ParsedSillyTavernWorldBook {
108
+ let json: unknown;
109
+ try {
110
+ json = JSON.parse(raw);
111
+ } catch {
112
+ throw new Error('Invalid JSON');
113
+ }
114
+ const root = asRecord(json);
115
+ if (!root) throw new Error('World info JSON must be an object');
116
+
117
+ const entriesValue = root.entries;
118
+ const rawEntries = Array.isArray(entriesValue)
119
+ ? entriesValue
120
+ : (() => {
121
+ const record = asRecord(entriesValue);
122
+ return record ? Object.values(record) : [];
123
+ })();
124
+ if (rawEntries.length === 0) throw new Error('World info JSON has no entries');
125
+
126
+ const entries = rawEntries
127
+ .map((entry, index) => normalizeEntry(entry, index))
128
+ .filter((entry): entry is Record<string, unknown> => entry != null);
129
+ if (entries.length === 0) throw new Error('World info JSON has no valid entries');
130
+ if (!entries.some((entry) => typeof entry.content === 'string' && entry.content.trim())) {
131
+ throw new Error('World info JSON has no entry content');
132
+ }
133
+
134
+ const name = stringValue(root.name).trim() || fallbackName.trim() || 'Imported world book';
135
+ const description = stringValue(root.description);
136
+ const book: Record<string, unknown> = { name, entries };
137
+ if (description) book.description = description;
138
+ const scanDepth = numberValue(root.scan_depth);
139
+ if (scanDepth != null) book.scan_depth = scanDepth;
140
+ const tokenBudget = numberValue(root.token_budget);
141
+ if (tokenBudget != null) book.token_budget = tokenBudget;
142
+ if (root.recursive_scanning !== undefined) book.recursive_scanning = booleanValue(root.recursive_scanning, false);
143
+ if (root.extensions !== undefined) book.extensions = root.extensions;
144
+
145
+ return {
146
+ name,
147
+ content: description.trim(),
148
+ characterBook: JSON.stringify(book, null, 2),
149
+ entryCount: entries.length,
150
+ enabledEntryCount: entries.filter((entry) => entry.enabled !== false && typeof entry.content === 'string' && entry.content.trim()).length,
151
+ };
152
+ }
153
+
154
+ /** 读取并解析 SillyTavern 世界书 JSON 文件(不落库,由 UI 预填后确认保存)。 */
155
+ export async function parseSillyTavernWorldInfoFile(file: File, fallbackName?: string): Promise<ParsedSillyTavernWorldBook> {
156
+ const raw = await file.text();
157
+ const fileFallback = file.name.replace(/\.json$/i, '').trim();
158
+ return parseSillyTavernWorldInfoJson(raw, fileFallback || fallbackName);
159
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 可排序列表共用的 dnd-kit 传感器(技能卡、新建会话的角色顺序)。
3
+ *
4
+ * - 鼠标:移动 4px 进入拖拽,桌面端保持原行为;
5
+ * - 触屏:按住 250ms 不动才进入拖拽,轻触后直接上下滑动仍然是滚动页面;
6
+ * - 键盘:保留无指针操作。
7
+ *
8
+ * 刻意不注册 PointerSensor:它会把触控笔一并纳入拖拽,而本产品不需要手写笔排序
9
+ * (产品决定)。将来若要支持触控笔,需要单独评估 PointerSensor 与 TouchSensor
10
+ * 的组合,而不是用它顶替 MouseSensor。
11
+ */
12
+ import { KeyboardSensor, MouseSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core';
13
+ import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
14
+
15
+ export function useSortableSensors() {
16
+ return useSensors(
17
+ useSensor(MouseSensor, { activationConstraint: { distance: 4 } }),
18
+ useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 5 } }),
19
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
20
+ );
21
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * 滚动容器“贴底”跟随。
3
+ *
4
+ * 软键盘弹起 / 收起会改变滚动容器的高度(移动端布局视口随键盘收缩),
5
+ * 输入框随内容增高时也会。若只在事件回调里 `requestAnimationFrame` 之后再贴底,
6
+ * 浏览器会先用旧滚动位置绘制一帧:内容先闪在错误位置,下一帧才跳到底部。
7
+ *
8
+ * `ResizeObserver` 的回调在布局之后、绘制之前执行,在这里同步修正 `scrollTop`,
9
+ * 滚动位置与高度变化会落在同一帧里,因此不会出现残影 / 二次跳动。
10
+ */
11
+
12
+ /** 距底部多少像素以内算“贴底”。与消息区自动滚动的阈值保持一致。 */
13
+ export const STICKY_BOTTOM_THRESHOLD = 60;
14
+
15
+ /** 纯函数:滚动位置是否已经贴底。 */
16
+ export function isNearBottom(
17
+ scrollHeight: number,
18
+ scrollTop: number,
19
+ clientHeight: number,
20
+ threshold = STICKY_BOTTOM_THRESHOLD,
21
+ ): boolean {
22
+ return scrollHeight - scrollTop - clientHeight < threshold;
23
+ }
24
+
25
+ /**
26
+ * 让容器在高度变化时保持贴底。
27
+ *
28
+ * 只在变化**之前**已经贴底时才跟随;用户主动向上回看时保持阅读位置,
29
+ * 不会因为地址栏显隐或键盘弹起被强行拉回底部。
30
+ *
31
+ * @returns 解除监听的函数
32
+ */
33
+ export function keepStickyBottom(el: HTMLElement, threshold = STICKY_BOTTOM_THRESHOLD): () => void {
34
+ let lastHeight = el.clientHeight;
35
+ const observer = new ResizeObserver(() => {
36
+ const height = el.clientHeight;
37
+ if (height === lastHeight) return;
38
+ // 用变化前的高度判断,避免容器长高时浏览器已经把 scrollTop 夹到新上限而误判。
39
+ const wasNearBottom = isNearBottom(el.scrollHeight, el.scrollTop, lastHeight, threshold);
40
+ lastHeight = height;
41
+ if (wasNearBottom) el.scrollTop = el.scrollHeight;
42
+ });
43
+ observer.observe(el);
44
+ return () => observer.disconnect();
45
+ }
@@ -9,30 +9,14 @@ import { translate } from '../i18n';
9
9
  const MAX_OUTPUT_CHARS = 20_000;
10
10
  /** 单文件读写字符上限(与沙箱服务 file_read/file_write 对齐) */
11
11
  const MAX_READ_CHARS = 100_000;
12
- const WORKSPACE_SCOPE_KEY = 'th-workspace-scope';
13
- let cachedWorkspaceScope: string | undefined;
14
-
15
- function workspaceScope(): string {
16
- if (cachedWorkspaceScope) return cachedWorkspaceScope;
17
- try {
18
- const existing = localStorage.getItem(WORKSPACE_SCOPE_KEY);
19
- if (existing && /^[a-z0-9-]+$/i.test(existing)) return (cachedWorkspaceScope = existing);
20
- const scope = crypto.randomUUID();
21
- localStorage.setItem(WORKSPACE_SCOPE_KEY, scope);
22
- return (cachedWorkspaceScope = scope);
23
- } catch {
24
- return (cachedWorkspaceScope = crypto.randomUUID());
25
- }
26
- }
27
-
28
- /** 为当前浏览器酒馆实例生成独立的会话工作目录名。 */
12
+ /** 会话工作目录由服务端共享数据中的会话 id 确定,因此所有浏览器访问同一目录。 */
29
13
  export function createSessionWorkspaceDir(sessionId: number): string {
30
- return `instance-${workspaceScope()}-session-${sessionId}`;
14
+ return `session-${sessionId}`;
31
15
  }
32
16
 
33
- /** 工作目录是否属于当前浏览器酒馆实例。 */
17
+ /** 工作目录是否由 Tavern Harness 服务端会话管理。 */
34
18
  export function isCurrentInstanceWorkspaceDir(dir: string | null | undefined): boolean {
35
- return typeof dir === 'string' && dir.startsWith(`instance-${workspaceScope()}-session-`);
19
+ return typeof dir === 'string' && /^session-\d+$/.test(dir);
36
20
  }
37
21
 
38
22
  /** 会话工作目录名是否合规(仅允许相对目录、不允许 .. / 绝对路径 / 危险字符) */
@@ -0,0 +1,46 @@
1
+ import { useSyncExternalStore } from 'react';
2
+
3
+ // ============================================================
4
+ // 版本号与「版本记录已读」状态
5
+ // - APP_VERSION 由 vite.config.ts 的 define 从 package.json 注入,
6
+ // 运行期不读文件、不请求 npm registry。
7
+ // ============================================================
8
+
9
+ export const APP_VERSION = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.0.0';
10
+
11
+ const STORAGE_KEY = 'tavern-harness:last-seen-version';
12
+ const listeners = new Set<() => void>();
13
+
14
+ function readLastSeen(): string | null {
15
+ try {
16
+ return localStorage.getItem(STORAGE_KEY);
17
+ } catch {
18
+ // 隐私模式 / 禁用存储时当作未读处理,只是多一个提示点
19
+ return null;
20
+ }
21
+ }
22
+
23
+ export function hasUnseenVersion(): boolean {
24
+ return readLastSeen() !== APP_VERSION;
25
+ }
26
+
27
+ export function markVersionSeen(): void {
28
+ try {
29
+ localStorage.setItem(STORAGE_KEY, APP_VERSION);
30
+ } catch {
31
+ /* 写入失败不影响使用 */
32
+ }
33
+ listeners.forEach((listener) => listener());
34
+ }
35
+
36
+ function subscribe(listener: () => void): () => void {
37
+ listeners.add(listener);
38
+ return () => {
39
+ listeners.delete(listener);
40
+ };
41
+ }
42
+
43
+ /** 当前版本是否有尚未查看的版本记录(设置入口的小圆点) */
44
+ export function useHasUnseenVersion(): boolean {
45
+ return useSyncExternalStore(subscribe, hasUnseenVersion, () => false);
46
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 视口 / 弹层定位的纯计算 + 浏览器包装。
3
+ * 纯函数部分不触碰 `window`,可以被 Node 单测直接导入。
4
+ */
5
+
6
+ export type ViewportPoint = { x: number; y: number };
7
+ export type Viewport = {
8
+ offsetLeft: number;
9
+ offsetTop: number;
10
+ width: number;
11
+ height: number;
12
+ };
13
+ /** `position: fixed` 弹层使用的布局视口边界。 */
14
+ export type ViewportBounds = { left: number; top: number; right: number; bottom: number };
15
+ export type PopoverSize = { width: number; height: number };
16
+
17
+ /** 弹层与视口边缘的最小间距。 */
18
+ export const POPOVER_EDGE_GAP = 8;
19
+ /** 与 CSS `@media (max-width: 680px)` 保持一致。 */
20
+ export const MOBILE_BREAKPOINT_PX = 680;
21
+ export const MOBILE_MEDIA_QUERY = `(max-width: ${MOBILE_BREAKPOINT_PX}px)`;
22
+
23
+ export function isMobileViewport(): boolean {
24
+ return window.matchMedia(MOBILE_MEDIA_QUERY).matches;
25
+ }
26
+
27
+ /**
28
+ * 把 client 坐标换算成 `position: fixed` 弹层使用的布局视口坐标。
29
+ * 页面缩放时 client 坐标相对 visual viewport,而 fixed 定位相对 layout viewport。
30
+ */
31
+ export function toLayoutViewportPoint(
32
+ point: ViewportPoint,
33
+ viewport?: Viewport | null,
34
+ ): ViewportPoint {
35
+ return {
36
+ x: point.x + (viewport?.offsetLeft ?? 0),
37
+ y: point.y + (viewport?.offsetTop ?? 0),
38
+ };
39
+ }
40
+
41
+ /** fixed 弹层可用的布局视口边界;没有 visualViewport 时退回窗口尺寸。 */
42
+ export function layoutViewportBounds(
43
+ viewport: Viewport | null | undefined,
44
+ fallbackWidth: number,
45
+ fallbackHeight: number,
46
+ ): ViewportBounds {
47
+ const left = viewport?.offsetLeft ?? 0;
48
+ const top = viewport?.offsetTop ?? 0;
49
+ return {
50
+ left,
51
+ top,
52
+ right: left + (viewport?.width ?? fallbackWidth),
53
+ bottom: top + (viewport?.height ?? fallbackHeight),
54
+ };
55
+ }
56
+
57
+ /** client 坐标 → 布局视口坐标(缩放时两者不一致)。 */
58
+ export function fixedViewportPoint(point: ViewportPoint): ViewportPoint {
59
+ return toLayoutViewportPoint(point, window.visualViewport);
60
+ }
61
+
62
+ /** fixed 弹层可用的布局视口边界。 */
63
+ export function fixedViewportBounds(): ViewportBounds {
64
+ return layoutViewportBounds(window.visualViewport, window.innerWidth, window.innerHeight);
65
+ }
66
+
67
+ /**
68
+ * 把弹层左上角钳制在可视区域内。`point` 必须已经是布局视口坐标
69
+ * (通过 `fixedViewportPoint` 转换),`bounds` 来自 `fixedViewportBounds`。
70
+ */
71
+ export function clampPopoverPosition(
72
+ point: ViewportPoint,
73
+ size: PopoverSize,
74
+ bounds: ViewportBounds,
75
+ gap = POPOVER_EDGE_GAP,
76
+ ): { left: number; top: number } {
77
+ return {
78
+ left: Math.max(bounds.left + gap, Math.min(point.x, bounds.right - size.width - gap)),
79
+ top: Math.max(bounds.top + gap, Math.min(point.y, bounds.bottom - size.height - gap)),
80
+ };
81
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * 微信 Android 内置浏览器(X5 / XWeb)的长按兜底。
3
+ *
4
+ * `-webkit-touch-callout` 是 iOS 的扩展,Blink 内核不认;微信 Android 还会
5
+ * 在原生层接管长按。即使气泡正文设置了 `user-select: none`,原生选词也会
6
+ * “吸附”到附近唯一的可选文字(输入区模型名称、页面其它文本),弹出系统
7
+ * 「复制 / 全选 / 搜一搜」菜单。这里做三层兜底:
8
+ *
9
+ * 1. 安装时给 `<html>` 加 `wechat-android` 类:`global.css` 用它将气泡正文
10
+ * 等纯文本区域移出命中测试,并让聊天区内不再产生文本选区;
11
+ * 2. 从消息 / 会话项开始触摸时,给 `<body>` 临时加内联 `user-select: none`
12
+ * (抬手后恢复),这样系统在 500ms 长按判定时找不到任何可选文字;
13
+ * 只有非交互目标才加锁,输入框、消息内按钮、链接不受影响;
14
+ * 3. 触摸期间阻止 `selectstart`,并清掉落到非输入控件上的选区。
15
+ *
16
+ * 只在 Android + MicroMessenger 下安装。输入框 / 搜索框 / 代码编辑器的
17
+ * 聚焦与选词完全不受影响——不能把整个 `.app-shell` 长期设为不可选,否则
18
+ * 微信软键盘可能无法弹出。
19
+ */
20
+ import { isEditableNode, isEditableTarget } from './editable.ts';
21
+ import { INTERACTIVE_SELECTOR } from './longPressGesture.ts';
22
+
23
+ export function isWeChatAndroidUa(userAgent: string): boolean {
24
+ return /Android/i.test(userAgent) && /MicroMessenger/i.test(userAgent);
25
+ }
26
+
27
+ /** 与 `useTouchLongPress` 绑定的表面保持一致。 */
28
+ const LONG_PRESS_SURFACE_SELECTOR = '.msg-row, .session-item';
29
+
30
+ /**
31
+ * 与 `shouldTrackLongPress` 相同的判定:目标在长按表面上,且不是嵌套的
32
+ * 交互控件(消息内按钮、链接等)。会话项本身是 `<button>`,所以要允许
33
+ * “交互目标就是长按表面”的情况。
34
+ */
35
+ function isLongPressSurfaceTarget(target: EventTarget | null): boolean {
36
+ if (!(target instanceof Element)) return false;
37
+ const surface = target.closest(LONG_PRESS_SURFACE_SELECTOR);
38
+ if (!surface) return false;
39
+ const interactive = target.closest(INTERACTIVE_SELECTOR);
40
+ return interactive == null || interactive === surface;
41
+ }
42
+
43
+ /** 微信原生选词/菜单可能在抬手后一小段时间才落地,保留一个短窗口。 */
44
+ const RELEASE_GRACE_MS = 300;
45
+
46
+ export function installWeChatTouchSelectionGuard(userAgent = navigator.userAgent): () => void {
47
+ if (!isWeChatAndroidUa(userAgent)) return () => {};
48
+
49
+ document.documentElement.classList.add('wechat-android');
50
+
51
+ let touching = false;
52
+ /** 本次触摸是否从消息 / 会话项(非交互区域)开始。 */
53
+ let touchOnLongPressSurface = false;
54
+ let releaseTimer = 0;
55
+
56
+ let bodyLocked = false;
57
+ let savedUserSelect = '';
58
+ let savedWebkitUserSelect = '';
59
+
60
+ const lockBodySelection = () => {
61
+ if (bodyLocked || !document.body) return;
62
+ const style = document.body.style;
63
+ savedUserSelect = style.getPropertyValue('user-select');
64
+ savedWebkitUserSelect = style.getPropertyValue('-webkit-user-select');
65
+ style.setProperty('user-select', 'none');
66
+ style.setProperty('-webkit-user-select', 'none');
67
+ bodyLocked = true;
68
+ };
69
+
70
+ const unlockBodySelection = () => {
71
+ if (!bodyLocked || !document.body) return;
72
+ const style = document.body.style;
73
+ style.removeProperty('user-select');
74
+ style.removeProperty('-webkit-user-select');
75
+ if (savedUserSelect) style.setProperty('user-select', savedUserSelect);
76
+ if (savedWebkitUserSelect) style.setProperty('-webkit-user-select', savedWebkitUserSelect);
77
+ savedUserSelect = '';
78
+ savedWebkitUserSelect = '';
79
+ bodyLocked = false;
80
+ };
81
+
82
+ const endTouch = () => {
83
+ if (releaseTimer) window.clearTimeout(releaseTimer);
84
+ releaseTimer = window.setTimeout(() => {
85
+ releaseTimer = 0;
86
+ touching = false;
87
+ touchOnLongPressSurface = false;
88
+ unlockBodySelection();
89
+ }, RELEASE_GRACE_MS);
90
+ };
91
+
92
+ const onTouchStart = (event: TouchEvent) => {
93
+ if (releaseTimer) {
94
+ window.clearTimeout(releaseTimer);
95
+ releaseTimer = 0;
96
+ }
97
+ // 新手势开始:先解除上一次长按留下的临时锁,避免影响正常输入。
98
+ unlockBodySelection();
99
+ touching = true;
100
+ touchOnLongPressSurface = isLongPressSurfaceTarget(event.target);
101
+ // 系统长按判定发生在触摸持续期间;临时锁住整个页面,避免选区吸附。
102
+ if (touchOnLongPressSurface) lockBodySelection();
103
+ };
104
+
105
+ const onSelectStart = (event: Event) => {
106
+ if (!touching || !touchOnLongPressSurface) return;
107
+ if (isEditableTarget(event.target)) return;
108
+ event.preventDefault();
109
+ };
110
+
111
+ const onSelectionChange = () => {
112
+ if (!touching || !touchOnLongPressSurface) return;
113
+ const selection = document.getSelection();
114
+ if (!selection || selection.rangeCount === 0) return;
115
+ // 只清普通文本的选区;输入框 / 代码编辑器里的选区保持原样。
116
+ if (isEditableNode(selection.anchorNode) || isEditableNode(selection.focusNode)) return;
117
+ selection.removeAllRanges();
118
+ };
119
+
120
+ // 只对从消息 / 会话项开始的触摸拦截系统 contextmenu;不影响输入框。
121
+ const onContextMenu = (event: Event) => {
122
+ if (!touching || !touchOnLongPressSurface) return;
123
+ if (isEditableTarget(event.target)) return;
124
+ event.preventDefault();
125
+ };
126
+
127
+ document.addEventListener('touchstart', onTouchStart, { capture: true, passive: true });
128
+ document.addEventListener('touchend', endTouch, { capture: true, passive: true });
129
+ document.addEventListener('touchcancel', endTouch, { capture: true, passive: true });
130
+ document.addEventListener('selectstart', onSelectStart, { capture: true });
131
+ document.addEventListener('selectionchange', onSelectionChange);
132
+ document.addEventListener('contextmenu', onContextMenu, { capture: true });
133
+
134
+ return () => {
135
+ if (releaseTimer) window.clearTimeout(releaseTimer);
136
+ unlockBodySelection();
137
+ document.documentElement.classList.remove('wechat-android');
138
+ document.removeEventListener('touchstart', onTouchStart, { capture: true });
139
+ document.removeEventListener('touchend', endTouch, { capture: true });
140
+ document.removeEventListener('touchcancel', endTouch, { capture: true });
141
+ document.removeEventListener('selectstart', onSelectStart, { capture: true });
142
+ document.removeEventListener('selectionchange', onSelectionChange);
143
+ document.removeEventListener('contextmenu', onContextMenu, { capture: true });
144
+ };
145
+ }