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,883 @@
1
+ // 划词翻译面板:按住 Ctrl 拖选(可配置为“选中后敲一下 Ctrl”或 Alt+拖选)→
2
+ // 选区旁浮窗翻译。通道分两类:LLM(跟随会话 / 供应商×模型,带思考档位与
3
+ // 提示词预设)与机翻(helper 内置九家,凭据在设置页“翻译”标签填)。单词走
4
+ // LLM 出词典卡片,句子/段落经 SSE 流式出译文;有道机翻查单词带轻量词条。
5
+ // 后端是 helper 的 /translate* 端点(src/host/translate-lib.mjs)。
6
+ import { h, t, rpc, liveBoot, getConfig, errText } from '../core.js';
7
+ import { ensureStyle, showToast, openDialog, btnSmall } from '../ui.js';
8
+ import { copyToClipboard } from './copy-path.js';
9
+ import { openSettingsDialog } from './settings-dialog.js';
10
+ import { thinkingLabel, thinkingVariantsOf, resolveThinkingOptions, adaptThinking } from '../thinking-levels.js';
11
+
12
+ let installed = false;
13
+ let featureOn = true;
14
+ let cfg = null; // /translate 配置(channel/promptId/prompts/panel/history/targetLang)
15
+ let providers = []; // LLM 供应商表 [{id,name,models}]
16
+ let services = []; // 机翻服务状态 [{id,configured}]
17
+ let panel = null; // 面板根元素(关闭即移除)
18
+ let pinned = false;
19
+ let ctrlDown = false;
20
+ let altDown = false;
21
+ let ctrlTapUsed = false; // Ctrl 按住期间按过别的键/鼠标就不算“敲一下”
22
+ let currentAbort = null; // 在途翻译请求(新翻译开始时取消旧的)
23
+ let speakAudio = null;
24
+ let sessionInfo = null; // 当前会话的模型与档位(/translate/session-model)
25
+ let lastAnchor = null; // 面板对应的选区矩形(尺寸变化后按它重新落位)
26
+ let selfDragging = false; // 用户正在拖动面板:期间不自动改位置
27
+
28
+ const MT_IDS = ['youdao', 'baidu', 'caiyun', 'deepl', 'deeplx', 'niu', 'tencent', 'aliyun', 'volc'];
29
+
30
+ function mtName(id) {
31
+ const L = t();
32
+ return L['translateMt' + id.charAt(0).toUpperCase() + id.slice(1)] || id;
33
+ }
34
+
35
+ async function loadState() {
36
+ const c = await getConfig();
37
+ featureOn = !(c && c.features && c.features.translate === false);
38
+ const res = await rpc('/translate');
39
+ if (res.ok && res.config) cfg = res.config;
40
+ const sm = await rpc('/translate/session-model');
41
+ if (sm.ok) sessionInfo = sm.session || null;
42
+ const prov = await rpc('/translate/providers');
43
+ if (prov.ok) {
44
+ providers = Array.isArray(prov.providers) ? prov.providers : [];
45
+ services = Array.isArray(prov.services) ? prov.services : [];
46
+ }
47
+ }
48
+
49
+ export function startTranslatePanel() {
50
+ if (installed) return;
51
+ installed = true;
52
+ void loadState();
53
+ // 任何设置保存都会发这个事件:功能开关与翻译配置都借此刷新
54
+ window.addEventListener('zcodepro:config-changed', () => { void loadState(); });
55
+ document.addEventListener('keydown', onKeyDown, true);
56
+ document.addEventListener('keyup', onKeyUp, true);
57
+ document.addEventListener('mousedown', onMouseDown, true);
58
+ document.addEventListener('mouseup', onMouseUp, true);
59
+ window.addEventListener('blur', () => { ctrlDown = altDown = false; });
60
+ }
61
+
62
+ function onKeyDown(e) {
63
+ // 输入法组合中一律放行(仓库统一约定),别抢组合过程中的按键
64
+ if (e.isComposing) return;
65
+ if (e.key === 'Control') { ctrlDown = true; ctrlTapUsed = false; return; }
66
+ if (e.key === 'Alt') altDown = true;
67
+ if (ctrlDown) ctrlTapUsed = true; // Ctrl 组合键(Ctrl+C 等)不算“敲一下”
68
+ if (e.key === 'Escape' && panel) {
69
+ // 设置等弹窗开着时让弹窗自己的 Esc 栈处理,别抢
70
+ if (document.querySelector('.zcodepro-overlay')) return;
71
+ e.preventDefault();
72
+ hidePanel();
73
+ }
74
+ }
75
+
76
+ function onKeyUp(e) {
77
+ if (e.key === 'Control') {
78
+ ctrlDown = false;
79
+ // “选中后敲一下 Ctrl”触发:按下到松开之间没碰过别的键/鼠标才算敲一下
80
+ if (ctrlTapUsed || !cfg || cfg.trigger?.mode !== 'ctrl-tap' || !featureOn) return;
81
+ const sel = window.getSelection();
82
+ const text = sel ? String(sel.toString()).trim() : '';
83
+ // 面板内(如输入框)的选区不触发
84
+ const inPanel = sel && sel.anchorNode && panel && panel.contains(sel.anchorNode);
85
+ if (text && !inPanel) triggerFromSelection(sel);
86
+ return;
87
+ }
88
+ if (e.key === 'Alt') altDown = false;
89
+ }
90
+
91
+ function onMouseDown(e) {
92
+ if (e.button !== 0) return;
93
+ if (ctrlDown) ctrlTapUsed = true; // Ctrl+点击/拖选都不算“敲一下”
94
+ }
95
+
96
+ function onMouseUp(e) {
97
+ if (e.button !== 0) return;
98
+ if (!featureOn || !cfg) return;
99
+ if (panel && panel.contains(e.target)) return; // 面板内部的松开(含选中译文)不触发
100
+ // 设置等 zcode-pro 弹窗开着时不动面板:用户是在设置里操作(改翻译配置),
101
+ // 这时点任何地方都不该把面板关掉(面板此刻被降到设置遮罩之下,仍应保留)
102
+ if (document.querySelector('.zcodepro-overlay')) return;
103
+ const mode = cfg.trigger?.mode || 'ctrl-drag';
104
+ // ctrl-tap 模式只认“敲一下 Ctrl”,选中过程的松开不触发
105
+ if (mode === 'ctrl-tap') { hideIfNotPinned(); return; }
106
+ const sel = window.getSelection();
107
+ const text = sel ? String(sel.toString()).trim() : '';
108
+ if (!text) { hideIfNotPinned(); return; }
109
+ if (mode === 'ctrl-drag' && !ctrlDown) return;
110
+ if (mode === 'alt-drag' && !altDown) return;
111
+ triggerFromSelection(sel);
112
+ }
113
+
114
+ // 收起 ZCode 自带的选中菜单。菜单由 React 管理,不能删节点(会让 React 摘
115
+ // 节点时抛 removeChild 错误、整块会话区域崩掉);清选区 + 派发 selectionchange
116
+ // 让官方自己卸载。必须在 React 提交本次渲染之后再执行:mouseup 时菜单还没
117
+ // 渲染出来,同步清选区后 React 照样把它挂上,所以分几拍补发
118
+ function dismissSelectionToolbar() {
119
+ const once = () => {
120
+ try {
121
+ const sel = window.getSelection();
122
+ if (sel && sel.rangeCount) sel.removeAllRanges();
123
+ document.dispatchEvent(new Event('selectionchange', { bubbles: true }));
124
+ } catch { /* ignore */ }
125
+ };
126
+ once();
127
+ // React 的提交可能落在随后的几帧里:再补两次,确保菜单不会在之后冒出来
128
+ requestAnimationFrame(() => {
129
+ once();
130
+ requestAnimationFrame(once);
131
+ });
132
+ setTimeout(once, 120);
133
+ }
134
+
135
+ function triggerFromSelection(sel) {
136
+ const text = String(sel.toString()).trim();
137
+ if (!text || [...text].length > 8000) return;
138
+ if (!sel.rangeCount) return;
139
+ const rect = sel.getRangeAt(0).getBoundingClientRect();
140
+ if (!rect || (!rect.width && !rect.height)) return;
141
+ // 选区完全滚出视口(切会话、页面滚动后残留选区)时不弹面板,
142
+ // 否则会贴着一个看不见的位置乱放
143
+ if (rect.bottom < 0 || rect.top > window.innerHeight) return;
144
+ ensurePanel(rect, text);
145
+ // 面板已拿到文本和位置,再收起官方菜单(ctrl+双击/拖选都会弹出它)
146
+ dismissSelectionToolbar();
147
+ }
148
+
149
+ // ———— 面板 ————
150
+
151
+ function hideIfNotPinned() { if (!pinned) hidePanel(); }
152
+ function hidePanel() {
153
+ pinned = false;
154
+ lastAnchor = null;
155
+ selfDragging = false;
156
+ if (currentAbort) currentAbort.abort();
157
+ if (panel) {
158
+ try { panel.__ro?.disconnect(); } catch { /* ignore */ }
159
+ panel.remove();
160
+ panel = null;
161
+ }
162
+ }
163
+
164
+ // 供外部入口(会话选中工具栏的「翻译」按钮)打开面板并翻译指定文本。
165
+ // anchor 是选区矩形:面板贴在选区上方、尖角对准选区水平中心(照官方“添加注释”弹窗)
166
+ export function openTranslatePanelAt(anchor, text) {
167
+ if (!text) return;
168
+ ensurePanel(anchor, text);
169
+ }
170
+ export function closeTranslatePanel() { hidePanel(); }
171
+
172
+ function ensurePanel(anchor, text) {
173
+ ensureStyle();
174
+ // 每次划词前刷新配置:设置页里改过的通道/档位/提示词要立即生效,
175
+ // 不能沿用上次打开面板时的旧缓存
176
+ void loadState().then(() => {
177
+ if (!panel) return;
178
+ const old = panel.querySelector('.zcodepro-tr-toolbar');
179
+ if (old) old.replaceWith(buildToolbar());
180
+ });
181
+ if (!panel) {
182
+ panel = buildPanel();
183
+ document.body.append(panel);
184
+ // 面板内容是异步变化的(翻译中 → 词典卡片/流式译文 → 报错),高度会变。
185
+ // 只在 append 那一刻量一次高度不够:量到的是空面板,内容撑高后就会压到
186
+ // 文字上。跟随尺寸变化重新落位(拖动过的不再干预)
187
+ lastAnchor = anchor || null;
188
+ const ro = new ResizeObserver(() => {
189
+ if (selfDragging || !lastAnchor || !panel) return;
190
+ positionPanel(lastAnchor);
191
+ });
192
+ ro.observe(panel);
193
+ panel.__ro = ro;
194
+ }
195
+ if (anchor) lastAnchor = anchor;
196
+ positionPanel(lastAnchor);
197
+ setInput(text);
198
+ void runTranslation(text);
199
+ }
200
+
201
+ // 面板落位:贴在选区上方,尖角(.zcodepro-tr-arrow)水平对准选区中心。
202
+ // 上方放不下(或会盖住选区分太多)时翻到下方,尖角同步翻到面板顶部。
203
+ // 左右夹取到视口内,尖角位置按面板实际左边距反算,仍指着选区。
204
+ //
205
+ // 与选区的空隙按选区行高动态算(ARROW_H 尖角高 + 呼吸空间):字号/行高在
206
+ // 设置里调过之后,这里的空隙自动跟着变,不会出现尖角压住文字。行高取选区
207
+ // 高度的近似值并封顶——多行选区的矩形高度是整块,不是行高,不能直接拿来做
208
+ // 空隙,否则空出大半屏。
209
+ //
210
+ // 注意:尖角是 absolute + 负偏移探出面板边界的,getBoundingClientRect 量不到
211
+ // 它。所以落位时要把 ARROW_H 单独算进间隙:面板边到选区边 = ARROW_H + 净空,
212
+ // 尖角正好占掉 ARROW_H,净空就是尖端到文字的实际距离。
213
+ const ARROW_H = 8; // 与 ui.js 里 .zcodepro-tr-arrow 的 border 宽度一致
214
+ const MIN_CLEARANCE = 10; // 尖端到文字的最小距离
215
+ const MAX_LINE_H = 32; // 行高估算上限(多行选区防空隙过大)
216
+
217
+ function selectionGap(anchor) {
218
+ const lineH = Math.min(anchor.height || 16, MAX_LINE_H);
219
+ const clearance = Math.max(MIN_CLEARANCE, Math.round(lineH * 0.7));
220
+ return { gap: ARROW_H + clearance, clearance };
221
+ }
222
+
223
+ function positionPanel(anchor) {
224
+ if (!panel || !anchor) return;
225
+ // 坐标必须是有限数:传进坏值(NaN/undefined)时 CSS 收到 NaNpx 会失效,
226
+ // 面板落到默认位置(左上角)。宁可不定位也不跑偏
227
+ const ok = (v) => Number.isFinite(v);
228
+ if (!ok(anchor.left) || !ok(anchor.top) || !ok(anchor.width)) return;
229
+ panel.style.visibility = 'hidden';
230
+ requestAnimationFrame(() => {
231
+ if (!panel) return;
232
+ const r = panel.getBoundingClientRect();
233
+ const margin = 8; // 视口最小边距
234
+ const { gap } = selectionGap(anchor);
235
+ const centerX = anchor.left + anchor.width / 2;
236
+ // 竖直:优先上方;上方空间不够且下方更宽裕时翻到下方
237
+ const spaceAbove = anchor.top - margin;
238
+ const spaceBelow = window.innerHeight - anchor.bottom - margin;
239
+ const placeAbove = spaceAbove >= r.height + gap || spaceAbove >= spaceBelow;
240
+ const top = placeAbove ? Math.max(margin, anchor.top - gap - r.height) : Math.min(window.innerHeight - r.height - margin, anchor.bottom + gap);
241
+ // 水平:面板中心对准选区中心,再夹取到视口内
242
+ let left = centerX - r.width / 2;
243
+ left = Math.max(margin, Math.min(left, window.innerWidth - r.width - margin));
244
+ panel.style.left = left + 'px';
245
+ panel.style.top = top + 'px';
246
+ panel.dataset.placement = placeAbove ? 'top' : 'bottom';
247
+ delete panel.dataset.dragged; // 重新定位后恢复显示尖角
248
+ // 尖角水平位置:相对面板左边,钳在圆角范围内(16px 内边距)
249
+ const arrowX = Math.max(16, Math.min(centerX - left, r.width - 16));
250
+ panel.style.setProperty('--tr-arrow-x', arrowX + 'px');
251
+ panel.style.visibility = '';
252
+ });
253
+ }
254
+
255
+ // 面板图标:与状态栏同一套 lucide 描边图标(16px、stroke-width 2、currentColor),
256
+ // 统一为纯色描边风格,不再混用彩色 emoji。路径取自 lucide 图标集
257
+ const TR_ICONS = {
258
+ pin: '<path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/>',
259
+ history: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
260
+ settings: '<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
261
+ close: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
262
+ edit: '<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>',
263
+ enter: '<path d="M20 4v7a4 4 0 0 1-4 4H4"/><path d="m9 10-5 5 5 5"/>',
264
+ volume: '<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/>',
265
+ book: '<path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/>',
266
+ text: '<path d="M15 18H3"/><path d="M17 6H3"/><path d="M21 12H3"/>',
267
+ };
268
+ // 生成 lucide 描边图标;尺寸默认 14px(面板内按钮),颜色跟随 currentColor
269
+ function trIcon(name, size = 14) {
270
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
271
+ svg.setAttribute('viewBox', '0 0 24 24');
272
+ svg.setAttribute('fill', 'none');
273
+ svg.setAttribute('stroke', 'currentColor');
274
+ svg.setAttribute('stroke-width', '2');
275
+ svg.setAttribute('stroke-linecap', 'round');
276
+ svg.setAttribute('stroke-linejoin', 'round');
277
+ svg.setAttribute('width', String(size));
278
+ svg.setAttribute('height', String(size));
279
+ svg.setAttribute('aria-hidden', 'true');
280
+ svg.style.flexShrink = '0';
281
+ svg.innerHTML = TR_ICONS[name] || '';
282
+ return svg;
283
+ }
284
+
285
+ function iconBtn(icon, title, onClick) {
286
+ return h('button', { type: 'button', class: 'zcodepro-tr-ibtn', title, 'aria-label': title, onClick }, trIcon(icon));
287
+ }
288
+
289
+ function buildPanel() {
290
+ const L = t();
291
+ pinned = false;
292
+ const root = h('div', {
293
+ class: 'zcodepro-translate-panel',
294
+ role: 'dialog',
295
+ 'data-theme': (cfg?.panel?.theme) || 'follow', // follow=跟随宿主主题,light/dark 强制
296
+ // 尺寸:宽度用设置值;高度优先用用户拖拽记住的像素值,没设过才按 maxHeightPct 自适应
297
+ style: (() => {
298
+ const pw = (cfg?.panel?.width) || 450;
299
+ const ph = Number(cfg?.panel?.height) || 0;
300
+ const mh = (cfg?.panel?.maxHeightPct) || 80;
301
+ return ph > 0
302
+ ? `width:${pw}px;height:${ph}px;max-height:${mh}vh`
303
+ : `width:${pw}px;max-height:${mh}vh`;
304
+ })(),
305
+ });
306
+ const head = h('div', { class: 'zcodepro-tr-head' },
307
+ h('span', { class: 'zcodepro-tr-title' }, L.translateTitle),
308
+ h('div', { class: 'zcodepro-tr-headbtns' },
309
+ iconBtn('pin', L.translatePin, () => { pinned = !pinned; showToast(pinned ? L.translatePinned : L.translateUnpinned, 'info'); }),
310
+ iconBtn('history', L.translateHistory, () => { void showHistory(); }),
311
+ iconBtn('settings', L.translateSettings, () => {
312
+ // 设置弹窗遮罩是 z-50,翻译面板在最高层(2147483000)会压住它。
313
+ // 按用户要求保留面板、把设置抬到上方:打开期间把面板降到遮罩之下,
314
+ // 设置关闭后恢复;面板本身不隐藏
315
+ if (panel) {
316
+ panel.style.zIndex = '40';
317
+ const restore = () => {
318
+ if (panel) panel.style.zIndex = '';
319
+ window.removeEventListener('zcodepro:settings-closed', restore);
320
+ };
321
+ window.addEventListener('zcodepro:settings-closed', restore);
322
+ }
323
+ openSettingsDialog('translate');
324
+ }),
325
+ iconBtn('close', L.close, () => { hidePanel(); })));
326
+ // 拖动:head 上按下(按钮除外)移动整面板
327
+ head.addEventListener('pointerdown', (e) => {
328
+ if (e.target.closest('button')) return;
329
+ const r = root.getBoundingClientRect();
330
+ const ox = e.clientX - r.left;
331
+ const oy = e.clientY - r.top;
332
+ selfDragging = true;
333
+ const move = (ev) => {
334
+ root.style.left = Math.max(0, Math.min(ev.clientX - ox, window.innerWidth - 60)) + 'px';
335
+ root.style.top = Math.max(0, Math.min(ev.clientY - oy, window.innerHeight - 40)) + 'px';
336
+ // 手动拖动后尖角不再对准选区,隐藏它(避免指向错误位置)
337
+ root.dataset.dragged = '1';
338
+ };
339
+ const up = () => {
340
+ window.removeEventListener('pointermove', move);
341
+ window.removeEventListener('pointerup', up);
342
+ // 拖动结束后仍保持用户放的位置(直到下次划词),所以 lastAnchor 一并清空:
343
+ // 后续尺寸变化不再把面板拉回选区旁
344
+ selfDragging = false;
345
+ lastAnchor = null;
346
+ };
347
+ window.addEventListener('pointermove', move);
348
+ window.addEventListener('pointerup', up);
349
+ e.preventDefault();
350
+ });
351
+ // 尖角:CSS 画的小三角,指向选中的文字(--tr-arrow-x 由 positionPanel 反算)
352
+ const arrow = h('div', { class: 'zcodepro-tr-arrow', 'aria-hidden': 'true' });
353
+ // 缩放入口:面板四边与四角都能拖(透明覆盖层,没有可见图标)。
354
+ // dir 是允许缩放的方向组合,如 'n'(只改上边)、'se'(右下角)、'e'(右边)。
355
+ // 改左边/上边时同步移动面板位置,视觉上就是那一条边在跟着鼠标走。
356
+ const edges = [
357
+ ['n', 'top:0;left:8px;right:8px;height:5px;cursor:ns-resize'],
358
+ ['s', 'bottom:0;left:8px;right:8px;height:5px;cursor:ns-resize'],
359
+ ['w', 'left:0;top:8px;bottom:8px;width:5px;cursor:ew-resize'],
360
+ ['e', 'right:0;top:8px;bottom:8px;width:5px;cursor:ew-resize'],
361
+ ['nw', 'left:0;top:0;width:12px;height:12px;cursor:nwse-resize'],
362
+ ['ne', 'right:0;top:0;width:12px;height:12px;cursor:nesw-resize'],
363
+ ['sw', 'left:0;bottom:0;width:12px;height:12px;cursor:nesw-resize'],
364
+ ['se', 'right:0;bottom:0;width:12px;height:12px;cursor:nwse-resize'],
365
+ ];
366
+ const MIN_W = 240;
367
+ const MIN_H = 140;
368
+ const edgeEls = edges.map(([dir, css]) => {
369
+ const el = h('div', { class: 'zcodepro-tr-edge', 'data-dir': dir, 'aria-hidden': 'true', style: css + ';z-index:3' });
370
+ el.addEventListener('pointerdown', (e) => {
371
+ e.preventDefault();
372
+ e.stopPropagation();
373
+ const r = root.getBoundingClientRect();
374
+ const startX = e.clientX;
375
+ const startY = e.clientY;
376
+ const startW = r.width;
377
+ const startH = r.height;
378
+ const startLeft = r.left;
379
+ const startTop = r.top;
380
+ const hasN = dir.includes('n');
381
+ const hasS = dir.includes('s');
382
+ const hasW = dir.includes('w');
383
+ const hasE = dir.includes('e');
384
+ selfDragging = true; // 缩放期间不让 ResizeObserver 把面板拉回选区
385
+ let w = startW;
386
+ let h = startH;
387
+ let left = startLeft;
388
+ let top = startTop;
389
+ const move = (ev) => {
390
+ const dx = ev.clientX - startX;
391
+ const dy = ev.clientY - startY;
392
+ if (hasE) w = Math.max(MIN_W, Math.min(startW + dx, window.innerWidth - startLeft - 8));
393
+ if (hasS) h = Math.max(MIN_H, Math.min(startH + dy, window.innerHeight - startTop - 8));
394
+ if (hasW) {
395
+ // 拖左边:左边界跟鼠标走,宽度反向变化,右边界保持不动
396
+ const maxDx = startW - MIN_W;
397
+ const clampedDx = Math.min(dx, maxDx); // 不让宽度小于下限
398
+ left = Math.max(8, startLeft + clampedDx);
399
+ w = startW - (left - startLeft); // 实际宽度按夹取后的左边界算
400
+ }
401
+ if (hasN) {
402
+ const maxDy = startH - MIN_H;
403
+ const clampedDy = Math.min(dy, maxDy);
404
+ top = Math.max(8, startTop + clampedDy);
405
+ h = startH - (top - startTop);
406
+ }
407
+ root.style.left = left + 'px';
408
+ root.style.top = top + 'px';
409
+ root.style.width = w + 'px';
410
+ root.style.height = h + 'px';
411
+ root.dataset.dragged = '1'; // 手动改过尺寸后尖角不再对准选区
412
+ };
413
+ const up = () => {
414
+ window.removeEventListener('pointermove', move);
415
+ window.removeEventListener('pointerup', up);
416
+ selfDragging = false;
417
+ lastAnchor = null;
418
+ void rpc('/translate', { method: 'POST', body: { config: { panel: { ...(cfg?.panel || {}), width: Math.round(w), height: Math.round(h) } } } })
419
+ .then((res) => { if (res.ok && res.config) cfg = res.config; });
420
+ };
421
+ window.addEventListener('pointermove', move);
422
+ window.addEventListener('pointerup', up);
423
+ });
424
+ return el;
425
+ });
426
+ root.append(arrow, head, buildToolbar(), buildInputRow(), h('div', { class: 'zcodepro-tr-body' }), ...edgeEls);
427
+ return root;
428
+ }
429
+
430
+ // 通道下拉值:“session” | 供应商 id | “mt:<服务id>”
431
+ function channelValue() {
432
+ const ch = cfg?.channel || {};
433
+ return ch.type === 'mt' ? ('mt:' + (ch.service || 'deepl')) : (ch.provider || 'session');
434
+ }
435
+
436
+ function buildToolbar() {
437
+ const L = t();
438
+ const ch = cfg?.channel || {};
439
+ const box = h('div', { class: 'zcodepro-tr-toolbar' });
440
+
441
+ const channelSel = h('select', { class: 'zcodepro-tr-select' },
442
+ h('optgroup', { label: L.translateChannelLlm },
443
+ h('option', { value: 'session', selected: ch.type === 'llm' && (!ch.provider || ch.provider === 'session') }, L.translateChannelSession),
444
+ ...providers.map((p) => h('option', { value: p.id, selected: ch.type === 'llm' && ch.provider === p.id }, p.name || p.id))),
445
+ h('optgroup', { label: L.translateChannelMt },
446
+ ...MT_IDS.map((id) => {
447
+ const st = services.find((s) => s.id === id);
448
+ return h('option', { value: 'mt:' + id, selected: ch.type === 'mt' && ch.service === id },
449
+ mtName(id) + (st && !st.configured ? '(' + L.translateUnconfigured + ')' : ''));
450
+ })));
451
+ channelSel.addEventListener('change', () => {
452
+ const v = channelSel.value;
453
+ const next = v.startsWith('mt:')
454
+ ? { type: 'mt', provider: 'session', model: '', thinking: 'off', service: v.slice(3) }
455
+ : { type: 'llm', provider: v, model: '', thinking: ch.thinking || 'off', service: ch.service || 'deepl' };
456
+ void persistChannel(next, true);
457
+ });
458
+
459
+ const items = [channelSel];
460
+
461
+ // 模型:LLM 且非跟随会话时显示(模型表为空给手输框)
462
+ if (ch.type === 'llm' && ch.provider && ch.provider !== 'session') {
463
+ const entry = providers.find((p) => p.id === ch.provider);
464
+ const models = (entry && Array.isArray(entry.models)) ? entry.models : [];
465
+ if (models.length) {
466
+ const modelSel = h('select', { class: 'zcodepro-tr-select' },
467
+ ...models.map((m) => h('option', { value: m, selected: ch.model === m }, m)));
468
+ // 换模型必须重建工具栏:思考档位跟着所选模型变
469
+ modelSel.addEventListener('change', () => { void persistChannel({ ...ch, model: modelSel.value }, true); });
470
+ items.push(modelSel);
471
+ } else {
472
+ const modelIn = h('input', { type: 'text', class: 'zcodepro-tr-input', value: ch.model || '', placeholder: L.translateModelEmpty, style: 'max-width:150px' });
473
+ modelIn.addEventListener('change', () => { void persistChannel({ ...ch, model: modelIn.value.trim() }, true); });
474
+ items.push(modelIn);
475
+ }
476
+ }
477
+
478
+ // 思考档位与提示词:仅 LLM 通道
479
+ if (ch.type !== 'mt') {
480
+ // 思考档位随所选模型变化;跟随会话当前模型时用会话那个模型的档位,
481
+ // 且把配置里的档位自适应映射到该模型支持的档位(如 max → enabled)
482
+ const opts = resolveThinkingOptions(providers, ch, sessionInfo);
483
+ const thinkSel = h('select', {
484
+ class: 'zcodepro-tr-select',
485
+ title: opts.unsupported ? L.translateThinkingUnsupported
486
+ : (opts.sessionModelId ? L.translateThinkingFollowSession.replaceAll('{model}', opts.sessionModelId) : L.translateThinking),
487
+ disabled: opts.unsupported ? true : undefined,
488
+ },
489
+ ...opts.variants.map((k) => h('option', { value: k, selected: opts.display === k }, thinkingLabel(k, L))));
490
+ thinkSel.addEventListener('change', () => { void persistChannel({ ...ch, thinking: thinkSel.value }); });
491
+ items.push(thinkSel);
492
+
493
+ const promptSel = h('select', { class: 'zcodepro-tr-select', title: L.translatePrompt },
494
+ ...(cfg?.prompts || []).map((p) => h('option', { value: p.id, selected: (cfg?.promptId) === p.id }, p.name || p.id)));
495
+ promptSel.addEventListener('change', async () => {
496
+ const res = await rpc('/translate', { method: 'POST', body: { config: { promptId: promptSel.value } } });
497
+ if (res.ok && res.config) cfg = res.config;
498
+ retryCurrent();
499
+ });
500
+ items.push(promptSel);
501
+ items.push(h('button', { type: 'button', class: 'zcodepro-tr-ibtn', title: L.translatePromptEdit, onClick: () => { void editPrompt(); } }, trIcon('edit')));
502
+ }
503
+
504
+ box.replaceChildren(...items);
505
+ return box;
506
+ }
507
+
508
+ function buildInputRow() {
509
+ const L = t();
510
+ const input = h('input', { type: 'text', class: 'zcodepro-tr-input', placeholder: L.translateInputPh });
511
+ input.addEventListener('keydown', (e) => {
512
+ e.stopPropagation(); // 别让面板输入的按键被全局监听拿去
513
+ if (e.key === 'Enter' && input.value.trim()) {
514
+ ensurePanelOpenNearInput(input);
515
+ void runTranslation(input.value.trim());
516
+ }
517
+ });
518
+ const row = h('div', { class: 'zcodepro-tr-inputrow' }, input,
519
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', title: L.translateGo, onClick: () => {
520
+ if (input.value.trim()) { ensurePanelOpenNearInput(input); void runTranslation(input.value.trim()); }
521
+ } }, trIcon('enter')));
522
+ return row;
523
+ }
524
+
525
+ function ensurePanelOpenNearInput(input) {
526
+ // 面板已关(钉住被关后输入行不存在)时不会走到这;这里只需保证可见
527
+ if (!panel) return;
528
+ const r = input.getBoundingClientRect();
529
+ if (r.top < 0 || r.bottom > window.innerHeight) panel.scrollIntoView({ block: 'nearest' });
530
+ }
531
+
532
+ function setInput(text) {
533
+ const input = panel?.querySelector('.zcodepro-tr-inputrow input');
534
+ if (input) input.value = text;
535
+ }
536
+
537
+ function currentText() {
538
+ const input = panel?.querySelector('.zcodepro-tr-inputrow input');
539
+ return input ? String(input.value || '').trim() : '';
540
+ }
541
+
542
+ function retryCurrent() {
543
+ const text = currentText();
544
+ if (text) void runTranslation(text);
545
+ }
546
+
547
+ async function persistChannel(next, rerender) {
548
+ // 保存前把思考档位规整到该模型支持的范围内:换模型时原档位可能不存在
549
+ // (如从 GLM 的 max 换到只有开关的 MiMo),留着无效值会让后端每次降级
550
+ let toSave = next;
551
+ if (next && next.type !== 'mt') {
552
+ const opts = resolveThinkingOptions(providers, next, sessionInfo);
553
+ if (opts.current !== next.thinking) toSave = { ...next, thinking: opts.current };
554
+ }
555
+ const res = await rpc('/translate', { method: 'POST', body: { config: { channel: toSave } } });
556
+ if (res.ok && res.config) cfg = res.config;
557
+ else showToast(t().failed + ': ' + errText(res), 'error');
558
+ if (rerender && panel) {
559
+ const old = panel.querySelector('.zcodepro-tr-toolbar');
560
+ const fresh = buildToolbar();
561
+ if (old) old.replaceWith(fresh);
562
+ retryCurrent();
563
+ }
564
+ }
565
+
566
+ // 提示词编辑(可改可新增):名称 + 内容,保存写回 prompts 与 promptId
567
+ async function editPrompt() {
568
+ const L = t();
569
+ const current = (cfg?.prompts || []).find((p) => p.id === cfg?.promptId) || { id: '', name: '', prompt: '' };
570
+ openDialog({
571
+ title: L.translatePromptEditTitle,
572
+ width: 'sm:max-w-lg',
573
+ onMount: async ({ body, close }) => {
574
+ const nameIn = h('input', { type: 'text', value: current.name || '', placeholder: L.translatePromptName, class: 'zcodepro-tr-input' });
575
+ const textIn = h('textarea', { class: 'zcodepro-tr-textarea', rows: '8' });
576
+ textIn.value = current.prompt || '';
577
+ const hint = h('div', { class: 'zcodepro-tr-hint' }, L.translatePromptHint);
578
+ body.append(
579
+ h('div', { class: 'mb-2' }, nameIn),
580
+ textIn,
581
+ hint,
582
+ h('div', { class: 'mt-3 flex justify-end gap-2' },
583
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', onClick: () => close() }, L.cancel),
584
+ h('button', {
585
+ type: 'button',
586
+ class: 'zcodepro-tr-ibtn zcodepro-tr-ibtn-primary',
587
+ onClick: async () => {
588
+ const name = nameIn.value.trim();
589
+ const prompt = textIn.value.trim();
590
+ if (!name || !prompt) { showToast(L.translatePromptRequired, 'warning'); return; }
591
+ const prompts = (cfg?.prompts || []).slice();
592
+ // 改了名称 = 另存为新预设(与提示一致,原预设不动);名称没改 = 就地更新
593
+ const renamed = !!current.id && name !== current.name;
594
+ const id = renamed || !current.id ? ('c' + Date.now().toString(36)) : current.id;
595
+ const idx = prompts.findIndex((p) => p.id === id);
596
+ if (idx >= 0) prompts[idx] = { ...prompts[idx], name, prompt };
597
+ else prompts.push({ id, name, prompt });
598
+ const res = await rpc('/translate', { method: 'POST', body: { config: { prompts, promptId: id } } });
599
+ if (res.ok && res.config) {
600
+ cfg = res.config;
601
+ if (panel) {
602
+ const old = panel.querySelector('.zcodepro-tr-toolbar');
603
+ if (old) old.replaceWith(buildToolbar());
604
+ }
605
+ close();
606
+ retryCurrent();
607
+ } else {
608
+ showToast(L.failed + ': ' + errText(res), 'error');
609
+ }
610
+ },
611
+ }, L.translateSave)));
612
+ },
613
+ });
614
+ }
615
+
616
+ // ———— 翻译执行与渲染 ————
617
+
618
+ function bodyEl() { return panel?.querySelector('.zcodepro-tr-body'); }
619
+
620
+ function renderLoading() {
621
+ const L = t();
622
+ const el = bodyEl();
623
+ if (el) el.replaceChildren(h('div', { class: 'zcodepro-tr-loading' }, L.translateLoading));
624
+ }
625
+
626
+ function renderError(msg) {
627
+ const L = t();
628
+ const el = bodyEl();
629
+ if (el) el.replaceChildren(
630
+ h('div', { class: 'zcodepro-tr-err' }, msg || L.translateFailed),
631
+ h('div', { class: 'zcodepro-tr-actions' },
632
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', onClick: () => { retryCurrent(); } }, L.translateRetry)));
633
+ }
634
+
635
+ function copyBtn(text) {
636
+ const L = t();
637
+ return h('button', {
638
+ type: 'button', class: 'zcodepro-tr-ibtn',
639
+ onClick: async () => { if (await copyToClipboard(text)) showToast(L.translateCopied, 'success'); },
640
+ }, L.translateCopy);
641
+ }
642
+
643
+ function speakBtn(text, ttsUrl) {
644
+ const L = t();
645
+ return h('button', { type: 'button', class: 'zcodepro-tr-ibtn', title: L.translateSpeak, onClick: () => speak(text, ttsUrl) }, trIcon('volume'));
646
+ }
647
+
648
+ function speak(text, ttsUrl) {
649
+ try {
650
+ if (ttsUrl) {
651
+ if (speakAudio) speakAudio.pause();
652
+ speakAudio = new Audio(ttsUrl);
653
+ void speakAudio.play();
654
+ return;
655
+ }
656
+ if (!text || !('speechSynthesis' in window)) return;
657
+ const u = new SpeechSynthesisUtterance(text);
658
+ u.lang = /[\u4e00-\u9fff]/.test(text) ? 'zh-CN' : 'en-US';
659
+ window.speechSynthesis.cancel();
660
+ window.speechSynthesis.speak(u);
661
+ } catch { /* ignore */ }
662
+ }
663
+
664
+ // 词典卡片(LLM 单词 / 有道 basic 词条共用)
665
+ function renderDict(dict) {
666
+ const L = t();
667
+ const el = bodyEl();
668
+ if (!el || !dict) return;
669
+ // 模型没按 JSON 给词条时落到空卡片:明确提示,不显示一张只有单词的空壳
670
+ const hasContent = (dict.senses || []).length || (dict.examples || []).length || (dict.forms || []).length;
671
+ if (!hasContent) {
672
+ el.replaceChildren(
673
+ h('div', { class: 'zcodepro-tr-empty' }, L.translateEmpty),
674
+ h('div', { class: 'zcodepro-tr-actions' },
675
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', onClick: () => { retryCurrent(); } }, L.translateRetry)));
676
+ return;
677
+ }
678
+ const head = h('div', { class: 'zcodepro-tr-wordrow' },
679
+ h('span', { class: 'zcodepro-tr-word' }, dict.word || ''),
680
+ dict.phonetic?.uk ? h('span', { class: 'zcodepro-tr-phon' }, 'uk /' + dict.phonetic.uk + '/') : null,
681
+ dict.phonetic?.us ? h('span', { class: 'zcodepro-tr-phon' }, 'us /' + dict.phonetic.us + '/') : null,
682
+ speakBtn(dict.word || '', dict.tts || ''));
683
+ const parts = [head];
684
+ for (const s of (dict.senses || [])) {
685
+ parts.push(h('div', { class: 'zcodepro-tr-defs' },
686
+ s.pos ? h('span', { class: 'zcodepro-tr-pos' }, s.pos) : null,
687
+ h('span', {}, (s.defs || []).join(';'))));
688
+ }
689
+ for (const ex of (dict.examples || [])) {
690
+ parts.push(h('div', { class: 'zcodepro-tr-example' },
691
+ h('div', {}, ex.src || ''),
692
+ ex.dst ? h('div', { class: 'zcodepro-tr-example-dst' }, ex.dst) : null));
693
+ }
694
+ if ((dict.forms || []).length) {
695
+ parts.push(h('div', { class: 'zcodepro-tr-forms' }, (dict.forms || []).join(' · ')));
696
+ }
697
+ const dictText = [
698
+ dict.word,
699
+ dict.phonetic?.uk ? '/' + dict.phonetic.uk + '/' : '',
700
+ ...(dict.senses || []).map((s) => (s.pos ? s.pos + ' ' : '') + (s.defs || []).join(';')),
701
+ ...(dict.examples || []).map((e) => e.src + (e.dst ? '\n' + e.dst : '')),
702
+ ].filter(Boolean).join('\n');
703
+ parts.push(h('div', { class: 'zcodepro-tr-actions' }, copyBtn(dictText)));
704
+ el.replaceChildren(...parts);
705
+ }
706
+
707
+ // 译文区(句子/段落);流式时增量更新同一节点。朗读/复制的按钮在创建时
708
+ // 就闭包引用 out 元素,点击时读实时文本,不再事后接线(避免双处理器)
709
+ function renderTransShell() {
710
+ const L = t();
711
+ const el = bodyEl();
712
+ if (!el) return null;
713
+ const src = h('div', { class: 'zcodepro-tr-src' });
714
+ const out = h('div', { class: 'zcodepro-tr-out' });
715
+ const meta = h('span', { class: 'zcodepro-tr-meta' });
716
+ el.replaceChildren(src, out,
717
+ h('div', { class: 'zcodepro-tr-actions' }, meta,
718
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', onClick: () => { retryCurrent(); } }, L.translateRetry),
719
+ h('button', { type: 'button', class: 'zcodepro-tr-ibtn', title: L.translateSpeak, onClick: () => speak(out.textContent, '') }, trIcon('volume')),
720
+ h('button', {
721
+ type: 'button', class: 'zcodepro-tr-ibtn',
722
+ onClick: async () => {
723
+ const text = String(out.textContent || '').trim();
724
+ if (text && await copyToClipboard(text)) showToast(L.translateCopied, 'success');
725
+ },
726
+ }, L.translateCopy)));
727
+ return { src, out, meta };
728
+ }
729
+
730
+ async function runTranslation(text) {
731
+ const L = t();
732
+ if (!cfg) await loadState();
733
+ if (!cfg) { renderError('config unavailable'); return; }
734
+ if (currentAbort) currentAbort.abort();
735
+ const abort = new AbortController();
736
+ currentAbort = abort;
737
+ const ch = cfg.channel || {};
738
+ const label = ch.type === 'mt' ? mtName(ch.service) : ((!ch.provider || ch.provider === 'session') ? (L.translateChannelSession + ' · ' + (ch.model || '')) : (ch.provider + ' · ' + (ch.model || '')));
739
+ const reqBody = {
740
+ text,
741
+ channel: { type: ch.type, provider: ch.provider, model: ch.model, thinking: ch.thinking, service: ch.service },
742
+ promptId: cfg.promptId,
743
+ stream: ch.type !== 'mt',
744
+ };
745
+ renderLoading();
746
+ const finish = async (kind) => {
747
+ if (abort.signal.aborted) return;
748
+ if (cfg.history?.enabled !== false) {
749
+ void rpc('/translate/history', { method: 'POST', body: { text, kind, label } });
750
+ }
751
+ };
752
+ try {
753
+ if (reqBody.stream) {
754
+ const ui = renderTransShell();
755
+ let full = '';
756
+ let handled = false; // 词典卡片等整段结果已渲染,外层不再做非空检查
757
+ await rpcStream('/translate/do', reqBody, abort.signal, (evt) => {
758
+ if (!ui || abort.signal.aborted) return;
759
+ if (evt.type === 'meta') {
760
+ ui.out.textContent = '';
761
+ if (evt.sourceLang) ui.meta.textContent = evt.sourceLang;
762
+ } else if (evt.type === 'delta') {
763
+ full += evt.text || '';
764
+ ui.out.textContent = full;
765
+ } else if (evt.type === 'done') {
766
+ full = evt.text || full;
767
+ ui.out.textContent = full;
768
+ wireTransActions(ui, { srcText: text, sourceLang: evt.sourceLang || '' });
769
+ } else if (evt.type === 'result') {
770
+ // 服务端回的是整段结果(单词词典卡片等):直接按 kind 渲染
771
+ const p = evt.payload || {};
772
+ if (p.kind === 'dict') {
773
+ handled = true;
774
+ renderDict(p.dict);
775
+ void finish('dict');
776
+ return;
777
+ }
778
+ full = (p.trans && p.trans.text) || '';
779
+ ui.out.textContent = full;
780
+ wireTransActions(ui, { srcText: text, sourceLang: (p.trans && p.trans.sourceLang) || '' });
781
+ } else if (evt.type === 'error') {
782
+ throw new Error(evt.error || 'translate failed');
783
+ }
784
+ });
785
+ if (!handled && !full.trim() && !abort.signal.aborted) throw new Error(L.translateEmpty);
786
+ if (!handled) void finish('trans');
787
+ } else {
788
+ const res = await rpc('/translate/do', { method: 'POST', body: { ...reqBody, stream: false } });
789
+ if (!res.ok) throw new Error(errText(res));
790
+ if (res.kind === 'dict') {
791
+ renderDict(res.dict);
792
+ void finish('dict');
793
+ } else {
794
+ const ui = renderTransShell();
795
+ if (ui) {
796
+ ui.out.textContent = (res.trans && res.trans.text) || '';
797
+ wireTransActions(ui, { srcText: text, sourceLang: (res.trans && res.trans.sourceLang) || '' });
798
+ }
799
+ void finish('trans');
800
+ }
801
+ }
802
+ } catch (err) {
803
+ if (abort.signal.aborted) return;
804
+ if (err && err.name === 'AbortError') return;
805
+ renderError(String((err && err.message) || err));
806
+ }
807
+ }
808
+
809
+ // 译文区收尾:填原文折叠行与源语言标注(朗读/复制按钮无需再接线)
810
+ function wireTransActions(ui, { srcText, sourceLang }) {
811
+ const L = t();
812
+ if (!ui) return;
813
+ ui.src.replaceChildren(
814
+ h('details', { class: 'zcodepro-tr-details' },
815
+ h('summary', {}, L.translateShowSource),
816
+ h('div', { class: 'zcodepro-tr-src-text' }, srcText)));
817
+ if (sourceLang) ui.meta.textContent = sourceLang;
818
+ }
819
+
820
+ async function rpcStream(path, body, signal, onEvent) {
821
+ const boot = liveBoot();
822
+ const resp = await fetch((boot.helperUrl || 'http://127.0.0.1:47889') + path, {
823
+ method: 'POST',
824
+ signal,
825
+ headers: { 'Content-Type': 'application/json', 'X-ZCodePro-Token': boot.token || '' },
826
+ body: JSON.stringify(body),
827
+ });
828
+ if (!resp.ok) {
829
+ const j = await resp.json().catch(() => ({}));
830
+ throw new Error((j && j.error) || ('HTTP ' + resp.status));
831
+ }
832
+ if (!(resp.headers.get('content-type') || '').includes('text/event-stream')) {
833
+ // 服务端回了整段 JSON(单词词典卡片,或通道不支持流式):包成 result
834
+ // 事件交给上层,按 kind 分别渲染。不能丢弃——单词请求本来就不走 SSE
835
+ const j = await resp.json().catch(() => ({}));
836
+ if (j && j.ok === false) throw new Error(j.error || 'translate failed');
837
+ onEvent({ type: 'result', payload: j });
838
+ return;
839
+ }
840
+ const reader = resp.body.getReader();
841
+ const decoder = new TextDecoder();
842
+ let buf = '';
843
+ for (;;) {
844
+ const { done, value } = await reader.read();
845
+ if (done) break;
846
+ buf += decoder.decode(value, { stream: true });
847
+ let idx;
848
+ while ((idx = buf.indexOf('\n\n')) >= 0) {
849
+ const chunk = buf.slice(0, idx);
850
+ buf = buf.slice(idx + 2);
851
+ for (const line of chunk.split('\n')) {
852
+ if (!line.startsWith('data:')) continue;
853
+ const payload = line.slice(5).trim();
854
+ if (!payload) continue;
855
+ try { onEvent(JSON.parse(payload)); } catch { /* 半截行忽略 */ }
856
+ }
857
+ }
858
+ }
859
+ }
860
+
861
+ // ———— 历史 ————
862
+
863
+ async function showHistory() {
864
+ const L = t();
865
+ const el = bodyEl();
866
+ if (!el) return;
867
+ const res = await rpc('/translate/history');
868
+ const items = res.ok && Array.isArray(res.items) ? res.items : [];
869
+ if (!items.length) {
870
+ el.replaceChildren(h('div', { class: 'zcodepro-tr-empty' }, L.translateNoHistory));
871
+ return;
872
+ }
873
+ el.replaceChildren(...items.slice(0, 50).map((it) => h('div', {
874
+ class: 'zcodepro-tr-histitem',
875
+ title: it.text || '',
876
+ onClick: () => {
877
+ setInput(it.text || '');
878
+ void runTranslation(String(it.text || ''));
879
+ },
880
+ },
881
+ h('span', { class: 'zcodepro-tr-histtime' }, new Date(it.t || Date.now()).toLocaleTimeString()),
882
+ h('span', { class: 'zcodepro-tr-histtext' }, trIcon(it.kind === 'dict' ? 'book' : 'text', 12), ' ', it.text || ''))));
883
+ }