zcode-pro 1.10.0 → 1.12.0

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.
@@ -0,0 +1,174 @@
1
+ // 会话选中文本的浮动工具栏增强:在官方「注释」按钮右侧插入「翻译」按钮。
2
+ // 官方工具栏结构(3.16.x 实测):
3
+ // div[data-conversation-selection-tooltip](fixed z-50,官方内联 left/top)
4
+ // ├ button[data-conversation-selection-action="comment"] 「注释」
5
+ // ├ div.w-px.bg-border 分隔线
6
+ // └ button[data-conversation-selection-action="ask-in-side-chat"]「在辅助对话中提问」
7
+ // 工具栏是官方 React 渲染的,生命周期由它自己管:这里只在它出现时补一个按钮,
8
+ // 它重建/移除时跟着消失(按钮挂在同一容器里,不持有跨渲染状态)。
9
+ // 点击后走和划词面板相同的翻译流程(helper 的 /translate/do),面板浮在按钮附近。
10
+ import { h, t, rpc, getConfig } from '../core.js';
11
+ import { showToast } from '../ui.js';
12
+ import { openTranslatePanelAt, closeTranslatePanel } from './translate-panel.js';
13
+
14
+ let installed = false;
15
+ let enabled = true;
16
+ const MARK = 'data-zcodepro-translate-btn';
17
+
18
+ async function refreshEnabled() {
19
+ try {
20
+ const cfg = await getConfig();
21
+ enabled = !(cfg && cfg.features && cfg.features.translate === false);
22
+ } catch { /* 配置读不到时按开启处理(与默认值一致) */ }
23
+ }
24
+
25
+ // 选区文本与矩形:官方工具栏是基于当前选区出现的。点击时现取即可——实测
26
+ // click 触发时选区仍完整(pointerdown 被官方拦掉,收不到,所以不依赖它)
27
+ function currentSelection() {
28
+ const sel = window.getSelection();
29
+ if (!sel || !sel.rangeCount) return { text: '', rect: null };
30
+ const text = String(sel.toString()).trim();
31
+ const rect = text ? sel.getRangeAt(0).getBoundingClientRect() : null;
32
+ return { text, rect };
33
+ }
34
+
35
+ // h() 用 createElement,建出的 <svg> 在 HTML 命名空间里不渲染:SVG 必须用
36
+ // createElementNS 建(settings-dialog 的标题图标同款做法)
37
+ function svgIcon(paths, cls) {
38
+ const ns = 'http://www.w3.org/2000/svg';
39
+ const svg = document.createElementNS(ns, 'svg');
40
+ svg.setAttribute('xmlns', ns);
41
+ svg.setAttribute('width', '24');
42
+ svg.setAttribute('height', '24');
43
+ svg.setAttribute('viewBox', '0 0 24 24');
44
+ svg.setAttribute('fill', 'none');
45
+ svg.setAttribute('stroke', 'currentColor');
46
+ svg.setAttribute('stroke-width', '1.5');
47
+ svg.setAttribute('stroke-linecap', 'round');
48
+ svg.setAttribute('stroke-linejoin', 'round');
49
+ svg.setAttribute('class', cls);
50
+ svg.setAttribute('aria-hidden', 'true');
51
+ for (const d of paths) {
52
+ const p = document.createElementNS(ns, 'path');
53
+ p.setAttribute('d', d);
54
+ svg.append(p);
55
+ }
56
+ return svg;
57
+ }
58
+
59
+ // 关闭官方选中菜单:菜单是 React 管理的节点,直接 remove() 会让 React 之后
60
+ // 摘节点时抛 “removeChild ... is not a child of this node”,整个会话区域崩掉
61
+ // (实测过)。正确做法是让官方自己收:清掉选区并派发 selectionchange,React
62
+ // 收到后自行卸载菜单,DOM 树保持由 React 独占。分几拍补发,覆盖 React 在
63
+ // 本次事件之后才提交渲染的情况(否则菜单会在我们关完后又冒出来)
64
+ function dismissToolbar() {
65
+ const once = () => {
66
+ try {
67
+ const sel = window.getSelection();
68
+ if (sel && sel.rangeCount) sel.removeAllRanges();
69
+ document.dispatchEvent(new Event('selectionchange', { bubbles: true }));
70
+ } catch { /* ignore */ }
71
+ };
72
+ once();
73
+ requestAnimationFrame(() => {
74
+ once();
75
+ requestAnimationFrame(once);
76
+ });
77
+ setTimeout(once, 120);
78
+ }
79
+
80
+ function injectButton(tooltip) {
81
+ if (!enabled) return;
82
+ if (tooltip.querySelector('[' + MARK + ']')) return;
83
+ const anchor = tooltip.querySelector('[data-conversation-selection-action="comment"]');
84
+ // 找不到「注释」就不动:官方结构变了时宁可不加,也不插到奇怪的位置
85
+ if (!anchor) return;
86
+
87
+ const btn = h('button', {
88
+ type: 'button',
89
+ [MARK]: '1',
90
+ // 复刻官方「注释」按钮的排版(padding/gap/hover 用官方同款工具类)
91
+ class: 'flex min-w-0 items-center gap-1 px-2.5 py-1.5 hover:bg-menu-hover',
92
+ title: t().translateToolbarTitle,
93
+ },
94
+ // 图标与文字间不留空档:图标存在时用官方同款 gap-1;无图标只剩文字
95
+ svgIcon(['m5 8 6 6', 'm4 14 6-6 2-3', 'M2 5h12', 'M7 2h1', 'm22 22-5-10-5 10', 'M14 18h6'], 'size-3.5 shrink-0 text-foreground-subtle'),
96
+ h('span', {}, t().translateToolbarLabel));
97
+
98
+ // 事件注册:官方在捕获阶段就对 click 调 stopPropagation(实测我们的冒泡
99
+ // 监听器一次都没触发,事件根本到不了目标),所以必须用捕获阶段监听器。
100
+ // h() 只能挂冒泡,这里手动加
101
+ btn.addEventListener('click', (e) => {
102
+ e.preventDefault();
103
+ e.stopPropagation();
104
+ const cur = currentSelection();
105
+ const text = cur.text;
106
+ const raw = cur.rect;
107
+ if (!text) return;
108
+ // DOMRect 的 left/top/width 等都是原型上的 getter,展开运算符拷不到
109
+ // ({ ...domRect } 得到空对象),必须逐字段读出来
110
+ let rect = raw
111
+ ? { left: raw.left, right: raw.right, top: raw.top, bottom: raw.bottom, width: raw.width, height: raw.height }
112
+ : null;
113
+ // 选区矩形可能超出视口(选中跨屏长段、页面滚动过):官方工具栏能显示就
114
+ // 说明选区可见,把矩形夹回视口内再落位,不因越界直接放弃
115
+ if (rect) {
116
+ const top = Math.max(0, Math.min(rect.top, window.innerHeight - 1));
117
+ const bottom = Math.max(top, Math.min(rect.bottom, window.innerHeight));
118
+ if (bottom <= 0 || top >= window.innerHeight) {
119
+ // 完全不可见时才退回工具栏自身位置
120
+ const tr = tooltip.getBoundingClientRect();
121
+ rect = { left: tr.left, right: tr.right, top: tr.top, bottom: tr.bottom, width: tr.width, height: tr.height };
122
+ } else {
123
+ rect = { ...rect, top, bottom, height: Math.max(1, bottom - top) };
124
+ }
125
+ }
126
+ closeTranslatePanel();
127
+ openTranslatePanelAt(rect, text);
128
+ // 弹出翻译面板后收起官方选中菜单(先取选区矩形再关,顺序不能反)
129
+ dismissToolbar();
130
+ }, true); // 捕获阶段
131
+ // pointerdown 也拦一下,避免官方把它当成“点工具栏外部”而收起
132
+ btn.addEventListener('pointerdown', (e) => e.stopPropagation(), true);
133
+
134
+ // 结构:「注释」‖ 翻译 ‖「在辅助对话中提问」。
135
+ // 官方原结构是 [注释][分隔线][辅助对话]。要拿到两条竖线,把翻译插在
136
+ // 官方分隔线“之前”:先在锚点后插分隔线,再把翻译插到那条新分隔线前面,
137
+ // 得到 [注释][新分隔线][翻译][官方分隔线][辅助对话]
138
+ const sep = h('div', { class: 'w-px shrink-0 bg-border' });
139
+ anchor.after(sep);
140
+ sep.after(btn);
141
+ }
142
+
143
+ const TIP_SEL = '[data-conversation-selection-tooltip]';
144
+ let lastTip = null;
145
+
146
+ // 工具栏是官方弹层,出现/消失频繁:监听容器增删,命中就补按钮。
147
+ // 只用 MutationObserver 的变化记录做廉价判断(新增节点里是否带工具栏),
148
+ // 命中才查一次 DOM——界面流式输出时 body 变动极频繁,不能每次都全文档查询
149
+ function scan(records) {
150
+ let maybe = false;
151
+ for (const rec of records || []) {
152
+ for (const node of rec.addedNodes) {
153
+ if (node.nodeType !== 1) continue;
154
+ if (node.matches?.(TIP_SEL) || node.querySelector?.(TIP_SEL)) { maybe = true; break; }
155
+ }
156
+ if (maybe) break;
157
+ }
158
+ // 当前工具栏若已被官方移除,清掉引用(下次插入时重新注入)
159
+ const cur = document.querySelector(TIP_SEL);
160
+ if (cur !== lastTip) lastTip = cur;
161
+ if (!maybe && !cur) return;
162
+ if (!cur) return;
163
+ injectButton(cur);
164
+ }
165
+
166
+ export function startSelectionToolbarTranslate() {
167
+ if (installed) return;
168
+ installed = true;
169
+ void refreshEnabled();
170
+ window.addEventListener('zcodepro:config-changed', () => { void refreshEnabled(); });
171
+ const mo = new MutationObserver((records) => scan(records));
172
+ mo.observe(document.body, { childList: true, subtree: true });
173
+ scan([]);
174
+ }