dsh-quick-translate 0.0.0-stage → 0.2.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.
package/client.js ADDED
@@ -0,0 +1,1939 @@
1
+ // 快速翻译 · 浏览器半边(界面风格:E 纸本)
2
+ // - 侧栏加一个「快速翻译」入口,主区域是一张桌面:原文写在方格本上,译文印在叠在上面的硫酸纸上
3
+ // - 模型选择在硫酸纸底部(点开是一张索引卡),列的是 DSH「设置 › 模型」里配好的 provider + 模型,默认跟随 DSH 默认模型
4
+ // - 翻译走 Host 的 SSE 接口,边生成边显示;⌘/Ctrl+Enter 翻译,Esc 取消
5
+ // - 接缝上的牛皮纸「互换」签是真正的互换:原文和译文对调、方向翻转,再点一次就换回来
6
+ // - 每次完成的翻译自动进历史(热敏小票),点击任意一条即可回看;历史和偏好都存在 localStorage
7
+ // - 桌面跟随 DSH 明暗主题;纸张、墨色、印章是"作品",颜色固定(见 AGENTS.md §3.4);文案走 DSH 的 locale 服务
8
+ window.__ModuleLoader__.load({
9
+ id: 'dsh-quick-translate',
10
+ factory(require) {
11
+ const React = require('react')
12
+ const h = React.createElement
13
+ const { useState, useEffect, useRef, useCallback, useMemo } = React
14
+
15
+ const PANEL = 'quick-translate'
16
+ const API = '/quick-translate/api'
17
+ const PREFS_KEY = 'dsh-quick-translate:prefs'
18
+ const DRAFT_KEY = 'dsh-quick-translate:draft'
19
+ const HISTORY_KEY = 'dsh-quick-translate:history'
20
+ const SEP = '\u001f'
21
+ const HISTORY_MAX = 100
22
+ const HISTORY_MAX_CHARS = 600_000
23
+ const EMPTY_LIST = []
24
+ const AUTHOR = 'Erek'
25
+ const COMP_W = 1200 // 画板 E 的桌面尺寸(去掉标题行)
26
+ const COMP_H = 690
27
+
28
+ /* ============================== 文案 ================================ */
29
+
30
+ const STR = {
31
+ zh: {
32
+ title: '快速翻译',
33
+ subtitle: '英译中 / 中译英,用 DSH 里已配置的模型',
34
+ en2zh: '英 → 中',
35
+ zh2en: '中 → 英',
36
+ auto: '自动',
37
+ model: '模型',
38
+ direction: '方向',
39
+ followDefault: '跟随 DSH 默认',
40
+ refresh: '刷新模型',
41
+ refreshing: '刷新中…',
42
+ source: '原文',
43
+ result: '译文',
44
+ langZh: '中文',
45
+ langEn: '英文',
46
+ sourcePlaceholder: '粘贴或输入要翻译的内容…',
47
+ resultPlaceholder: '译文会显示在这里',
48
+ translate: '翻译',
49
+ translating: '翻译中…',
50
+ cancel: '取消',
51
+ clear: '清空',
52
+ clearTitle: '清空原文和译文',
53
+ copy: '复制',
54
+ copied: '已复制',
55
+ copyFailed: '复制失败',
56
+ copyFailedHint: '剪贴板被拒绝,已选中译文,请按 {key}+C 手动复制',
57
+ swap: '交换原文和译文(再点一次换回来)',
58
+ chars: '字符',
59
+ seconds: '秒',
60
+ noModels: 'DSH 里还没有可用的文字模型。到「设置 › 模型」里添加一个,再点下面的按钮重新加载。',
61
+ noModelsRefresh: '重新加载模型',
62
+ loadingModels: '正在读取模型列表…',
63
+ loadModelsFailed: '模型列表读取失败',
64
+ retry: '重试',
65
+ someSkipped: (n) => `${n} 个模型服务商暂时没有响应,请稍后重试`,
66
+ selectModel: '选择模型',
67
+ autoHint: (t) => `译成${t === 'zh' ? '中文' : '英文'}`,
68
+ emptySource: (key) => `输入内容后按 ${key} + Enter`,
69
+ done: '完成',
70
+ truncated: '输出达到模型上限,已截断',
71
+ cancelledPartial: '已取消 · 仅为已收到的部分',
72
+ streamBroken: '连接中断,没有收到完整结果',
73
+ history: '历史',
74
+ historyEmpty: '还没有翻译记录\n完成一次翻译后会自动出现在这里',
75
+ historyEmptyFiltered: '没有匹配的记录',
76
+ historySearch: '搜索原文、译文或模型',
77
+ historyClear: '清空历史',
78
+ historyConfirm: '再点一次确认清空',
79
+ historyDelete: '删除这条',
80
+ justNow: '刚刚',
81
+ minutesAgo: (n) => `${n} 分钟前`,
82
+ hoursAgo: (n) => `${n} 小时前`,
83
+ yesterday: '昨天',
84
+ defaultShort: '默认',
85
+ share: '分享图片',
86
+ shareTitle: '分享卡片',
87
+ shareMaking: '正在生成图片…',
88
+ shareCopy: '复制图片',
89
+ shareCopied: '图片已复制,可以直接粘贴到聊天里',
90
+ shareCopyFailed: '剪贴板不接受图片,请用「保存图片」',
91
+ shareSave: '保存图片',
92
+ shareSaved: '已保存到下载文件夹',
93
+ shareClose: '关闭',
94
+ today: '今天',
95
+ deskTitle: 'Quick Translate',
96
+ receiving: '接收中',
97
+ standby: '待命',
98
+ locked: '锁定 · 翻译中',
99
+ swapShort: '互换',
100
+ stamp: '已译',
101
+ statSrc: '源文字符',
102
+ statDst: '译文字符',
103
+ statTime: '用时',
104
+ waiting: '等待翻译',
105
+ waitingHint: (key) => `在左边写好原文,按 ${key} ↵ 开始`,
106
+ modelCount: (n) => `DSH 已配置 ${n} 个`,
107
+ historyTotal: (n) => `共 ${n} 条`,
108
+ noModelsTitle: '还没有可用的模型',
109
+ },
110
+ en: {
111
+ title: 'Quick translate',
112
+ subtitle: 'English ↔ Chinese with the models you already added to DSH',
113
+ en2zh: 'EN → ZH',
114
+ zh2en: 'ZH → EN',
115
+ auto: 'Auto',
116
+ model: 'Model',
117
+ direction: 'Direction',
118
+ followDefault: 'Use DSH default',
119
+ refresh: 'Refresh models',
120
+ refreshing: 'Refreshing…',
121
+ source: 'Source',
122
+ result: 'Translation',
123
+ langZh: 'Chinese',
124
+ langEn: 'English',
125
+ sourcePlaceholder: 'Paste or type the text to translate…',
126
+ resultPlaceholder: 'The translation appears here',
127
+ translate: 'Translate',
128
+ translating: 'Translating…',
129
+ cancel: 'Cancel',
130
+ clear: 'Clear',
131
+ clearTitle: 'Clear source and translation',
132
+ copy: 'Copy',
133
+ copied: 'Copied',
134
+ copyFailed: 'Copy failed',
135
+ copyFailedHint: 'Clipboard blocked; text selected, press {key}+C to copy manually',
136
+ swap: 'Swap source and translation (click again to swap back)',
137
+ chars: 'chars',
138
+ seconds: 's',
139
+ noModels: 'No text model is available yet. Add one under Settings › Models, then reload below.',
140
+ noModelsRefresh: 'Reload models',
141
+ loadingModels: 'Loading models…',
142
+ loadModelsFailed: 'Failed to load models',
143
+ retry: 'Retry',
144
+ someSkipped: (n) => `${n} provider(s) did not respond; try again shortly`,
145
+ selectModel: 'Select a model',
146
+ autoHint: (t) => `to ${t === 'zh' ? 'Chinese' : 'English'}`,
147
+ emptySource: (key) => `Type, then press ${key} + Enter`,
148
+ done: 'Done',
149
+ truncated: 'Hit the model output limit; result may be cut off',
150
+ cancelledPartial: 'Cancelled · partial result only',
151
+ streamBroken: 'The connection closed before the translation finished',
152
+ history: 'History',
153
+ historyEmpty: 'No translations yet\nFinished translations appear here automatically',
154
+ historyEmptyFiltered: 'No matching entries',
155
+ historySearch: 'Search source, translation or model',
156
+ historyClear: 'Clear history',
157
+ historyConfirm: 'Click again to confirm',
158
+ historyDelete: 'Delete this entry',
159
+ justNow: 'just now',
160
+ minutesAgo: (n) => `${n} min ago`,
161
+ hoursAgo: (n) => `${n} h ago`,
162
+ yesterday: 'yesterday',
163
+ defaultShort: 'default',
164
+ share: 'Share image',
165
+ shareTitle: 'Share card',
166
+ shareMaking: 'Rendering image…',
167
+ shareCopy: 'Copy image',
168
+ shareCopied: 'Image copied — paste it into any chat',
169
+ shareCopyFailed: 'Clipboard refused the image; use Save image',
170
+ shareSave: 'Save image',
171
+ shareSaved: 'Saved to your Downloads folder',
172
+ shareClose: 'Close',
173
+ today: 'Today',
174
+ deskTitle: 'Quick Translate',
175
+ receiving: 'Receiving',
176
+ standby: 'Standby',
177
+ locked: 'Locked while translating',
178
+ swapShort: 'Swap',
179
+ stamp: 'DONE',
180
+ statSrc: 'Source chars',
181
+ statDst: 'Output chars',
182
+ statTime: 'Time',
183
+ waiting: 'Waiting',
184
+ waitingHint: (key) => `Write on the left, then press ${key} ↵`,
185
+ modelCount: (n) => `${n} in DSH`,
186
+ historyTotal: (n) => `${n} total`,
187
+ noModelsTitle: 'No model yet',
188
+ },
189
+ }
190
+
191
+ const isMac = /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent || '')
192
+ const modKey = isMac ? '⌘' : 'Ctrl'
193
+
194
+ const langStore = {
195
+ lang: detectLang(),
196
+ listeners: new Set(),
197
+ get() {
198
+ return this.lang
199
+ },
200
+ set(next) {
201
+ if (!next || next === this.lang) return
202
+ this.lang = next
203
+ this.listeners.forEach((fn) => fn())
204
+ },
205
+ subscribe(fn) {
206
+ this.listeners.add(fn)
207
+ return () => this.listeners.delete(fn)
208
+ },
209
+ }
210
+
211
+ function detectLang() {
212
+ const id = String(navigator.language || 'en').toLowerCase()
213
+ return id.startsWith('zh') ? 'zh' : 'en'
214
+ }
215
+
216
+ function useLang() {
217
+ const [lang, setLang] = useState(langStore.get())
218
+ useEffect(() => langStore.subscribe(() => setLang(langStore.get())), [])
219
+ return lang
220
+ }
221
+
222
+ /* ============================== 样式 ================================ */
223
+
224
+ // 全部走 --dsw-alias-* token;字号从 --dsh-content-font-size 派生,用户在 DSH 里调大正文时整页跟着变。
225
+ const CSS = `
226
+ /* ============ 纸本(E):按 Design 画板 E 的尺寸和坐标原样搭一张 1200×690 的桌面,再整体缩放到面板大小 ============ */
227
+ .qt-root{
228
+ --qt-fs:var(--dsh-content-font-size,14px);
229
+ --qt-mono:"IBM Plex Mono",var(--dsh-font-family-code,ui-monospace),"SF Mono",Menlo,monospace;
230
+ --qt-grot:"Inter Tight","Helvetica Neue",Helvetica,Arial,sans-serif;
231
+ --qt-zh-serif:"Songti SC","Noto Serif SC","Source Han Serif SC","STSong",serif;
232
+ --qt-zh-sans:"PingFang SC","Noto Sans SC","Microsoft YaHei",sans-serif;
233
+ --qt-en-serif:"Iowan Old Style","Newsreader","Palatino",Georgia,serif;
234
+ --qt-desk:#1d1d1d;--qt-desk-ink:#e6e3dc;--qt-desk-faint:#3d3d3d;
235
+ --qt-paper:#eeede7;--qt-grid:#c6d0d8;--qt-ink:#1b1b1b;--qt-ink-2:#34363d;--qt-ink-3:#77787e;
236
+ --qt-indigo:#41468a;--qt-stamp:#3a3fa6;--qt-red:#ef4a23;--qt-redpen:#c8361a;--qt-kraft:#b88f62;--qt-receipt:#f5f5f2;--qt-masking:rgba(232,220,186,.92);
237
+ --qt-grain:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='240' height='240'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .28 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>");
238
+ --qt-grain-light:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='240' height='240'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 .09 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>");
239
+ --qt-tape-clip:polygon(0 8%,3% 0,7% 10%,11% 2%,100% 0,97% 92%,100% 100%,0 100%,2% 50%);
240
+ --qt-ease:cubic-bezier(.2,.7,.1,1);
241
+ position:relative;display:flex;flex-direction:column;height:100%;min-height:0;overflow:hidden;
242
+ background:var(--qt-grain-light),radial-gradient(120% 90% at 45% 40%,transparent 50%,rgba(0,0,0,.55) 100%),var(--qt-desk);
243
+ color:var(--qt-desk-ink);font-family:var(--qt-zh-sans);font-size:14px;line-height:1.5;
244
+ }
245
+ .qt-root *,.qt-root *::before,.qt-root *::after{box-sizing:border-box}
246
+ :where(.qt-root) :where(button,input,textarea){font:inherit;color:inherit}
247
+ :where(.qt-root) button{appearance:none;border:0;background:none;padding:0;cursor:pointer}
248
+ :where(.qt-root) button:disabled{cursor:default}
249
+ .qt-root :focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
250
+ .qt-mono{font-family:var(--qt-mono);letter-spacing:.02em;text-transform:uppercase}
251
+ .qt-br::before{content:"[ "}.qt-br::after{content:" ]"}
252
+ .qt-dots{height:2px;flex:none;background-image:radial-gradient(circle,currentColor 1px,transparent 1.3px);background-size:7px 2px;opacity:.55}
253
+ .qt-spacer{flex:1}
254
+
255
+ /* 头部(窗口拖拽区):画板左上角的标题和右上角的 History */
256
+ .qt-header{display:flex;align-items:baseline;gap:14px;flex:none;padding:22px 40px 0;padding-top:calc(22px + var(--dsh-frame-top-clearance,0px));padding-left:calc(40px + var(--dsh-frame-leading-clearance,0px))}
257
+ .qt-title{font-family:var(--qt-grot);font-weight:900;font-size:23px;letter-spacing:-.035em;white-space:nowrap}
258
+ .qt-subtitle{font-size:11px;opacity:.55;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
259
+ .qt-hbtn{font-family:var(--qt-mono);font-size:12px;text-transform:uppercase;letter-spacing:.02em;display:inline-flex;align-items:center;gap:8px;white-space:nowrap;color:var(--qt-desk-ink);opacity:.85;padding:4px 0}
260
+ .qt-hbtn:hover,.qt-hbtn[aria-pressed="true"]{opacity:1}
261
+ .qt-hbtn:disabled{opacity:.4}
262
+ .qt-badge{padding:1px 6px;border:1px solid currentColor;line-height:1.4;font-variant-numeric:tabular-nums}
263
+ .qt-hbtn[aria-pressed="true"] .qt-badge{background:var(--qt-desk-ink);color:var(--qt-desk)}
264
+
265
+ /* 桌面 */
266
+ .qt-board{flex:1;min-height:0;position:relative;display:flex;align-items:center;justify-content:center;overflow:hidden}
267
+ .qt-comp{position:relative;width:1200px;height:690px;flex:none}
268
+ .qt-deco-date{position:absolute;left:6px;bottom:72px;transform:rotate(-90deg);transform-origin:left bottom;font-family:var(--qt-grot);font-weight:800;font-size:30px;letter-spacing:-.02em;color:var(--qt-desk-faint);white-space:nowrap;pointer-events:none}
269
+ .qt-deco-side{position:absolute;right:14px;top:50px;writing-mode:vertical-rl;font-family:var(--qt-mono);font-size:11px;line-height:1.7;color:var(--qt-desk-faint);pointer-events:none}
270
+ .qt-col{position:absolute;isolation:isolate}
271
+ .qt-paper{position:absolute;inset:0;z-index:-1;pointer-events:none}
272
+ .qt-colhead{display:flex;justify-content:space-between;gap:12px;font-family:var(--qt-mono);font-size:11.5px;letter-spacing:.02em;text-transform:uppercase;white-space:nowrap;flex:none}
273
+ .qt-colhead > *{overflow:hidden;text-overflow:ellipsis}
274
+ .qt-locked{color:var(--qt-red)}
275
+ .qt-textarea{flex:1;min-height:0;width:100%;resize:none;border:0;outline:0;background:transparent;padding:0;margin:0;color:inherit;scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.22) transparent}
276
+ .qt-textarea:focus-visible{outline:0}
277
+ .qt-textarea{scrollbar-width:none}
278
+ .qt-textarea::-webkit-scrollbar{display:none}
279
+ .qt-tawrap{position:relative;flex:1;min-height:0;display:flex}
280
+ .qt-tarul{position:absolute;right:-24px;top:4px;bottom:4px;width:7px;pointer-events:none;background:repeating-linear-gradient(to bottom,currentColor 0 1px,transparent 1px 6px);opacity:0;transition:opacity .5s ease}
281
+ .qt-tarul.is-on{opacity:.55;transition-duration:.12s}
282
+ .qt-tarul i{position:absolute;left:0;right:0;background:currentColor}
283
+ .qt-note .qt-tarul{right:auto;left:-13px;color:var(--qt-ink-2)}
284
+
285
+ /* 原文:方格本(画板坐标 62,12 · 540×606 · -1.1°) */
286
+ .qt-note{left:62px;top:12px;width:540px;height:606px;transform:rotate(-1.1deg);color:var(--qt-ink)}
287
+ .qt-note .qt-paper{filter:drop-shadow(0 24px 30px rgba(0,0,0,.45))}
288
+ .qt-note .qt-paper::before{content:"";position:absolute;inset:0;
289
+ background:var(--qt-grain),
290
+ linear-gradient(90deg,transparent 62px,rgba(214,80,60,.45) 62px,rgba(214,80,60,.45) 63px,transparent 63px),
291
+ linear-gradient(var(--qt-grid) 1px,transparent 1px) 0 10px/22px 22px,
292
+ linear-gradient(90deg,var(--qt-grid) 1px,transparent 1px) 0 0/22px 22px,
293
+ var(--qt-paper);
294
+ clip-path:polygon(0 0,100% 0,100% 97.4%,96% 98.6%,91% 97.2%,86% 99.1%,80% 97.6%,74% 98.9%,69% 97%,63% 98.4%,57% 97.3%,51% 99.2%,45% 97.5%,39% 98.8%,33% 97.1%,27% 98.6%,21% 97.4%,15% 99%,9% 97.6%,4% 98.7%,0 97.5%)}
295
+ .qt-rings{position:absolute;left:0;top:0;bottom:18px;width:16px;background:repeating-linear-gradient(to bottom,#141414 0 11px,transparent 11px 25px);pointer-events:none}
296
+ .qt-holes{position:absolute;left:28px;top:6px;bottom:24px;width:18px;background:radial-gradient(circle,var(--qt-desk) 6.5px,transparent 7px) 0 0/18px 25px repeat-y;pointer-events:none}
297
+ .qt-note-in{position:absolute;left:82px;right:70px;top:34px;bottom:34px;display:flex;flex-direction:column}
298
+ .qt-note .qt-colhead{color:var(--qt-ink-2)}
299
+ .qt-note .qt-dots{margin:14px 0 22px;color:var(--qt-ink-2)}
300
+ .qt-src{font-family:var(--qt-mono);font-size:15.5px;line-height:1.85;color:var(--qt-ink)}
301
+ .qt-comp:not(.is-narrow) .qt-note .qt-tawrap{margin-right:30px}
302
+ .qt-src::placeholder{color:#8b8d93}
303
+ .qt-src[readonly]{cursor:default}
304
+ .qt-note-foot{display:flex;align-items:center;gap:16px;flex:none;min-height:56px;padding-right:150px}
305
+ .qt-meta{font-family:var(--qt-mono);font-size:11px;text-transform:uppercase;letter-spacing:.02em;color:var(--qt-ink-2);white-space:nowrap}
306
+
307
+ /* 文具胶带:翻译(红布胶带)· 清空 / 互换(美纹纸) */
308
+ .qt-tapebtn{position:relative;display:inline-flex;align-items:center;justify-content:center;clip-path:var(--qt-tape-clip);transition:transform .2s var(--qt-ease),opacity .15s,filter .15s}
309
+ .qt-tapebtn:disabled{opacity:.45}
310
+ .qt-tapebtn:focus-visible{outline:2px dashed currentColor;outline-offset:-7px}
311
+ .qt-actions{position:absolute;right:62px;bottom:30px;display:flex;align-items:center;gap:6px}
312
+ .qt-go{gap:16px;padding:14px 22px 14px 28px;transform:rotate(-2deg);font-family:var(--qt-zh-sans);font-weight:900;font-size:25px;letter-spacing:.06em;line-height:1.1;white-space:nowrap}
313
+ .qt-go:hover:not(:disabled){transform:rotate(-2deg) translateY(-2px)}
314
+ .qt-go kbd{font-family:var(--qt-mono);font-weight:600;font-size:11px;letter-spacing:.04em;padding:2px 5px;border:1.5px solid currentColor;line-height:1.2}
315
+ .qt-btn-primary{background:var(--qt-grain),linear-gradient(180deg,rgba(255,255,255,.14),rgba(255,255,255,0) 55%),var(--qt-red);color:#141414}
316
+ .qt-btn-stop{background:var(--qt-grain),#1b1b1b;color:var(--qt-paper)}
317
+ .qt-clear{padding:8px 20px 8px 22px;transform:rotate(-2.5deg);background:var(--qt-grain),linear-gradient(180deg,rgba(255,255,255,.22),rgba(255,255,255,0) 60%),var(--qt-masking);color:#26241f;font-family:var(--qt-zh-sans);font-weight:800;font-size:15px;letter-spacing:.24em}
318
+ .qt-clear:hover:not(:disabled){transform:rotate(-2.5deg) translateY(-2px)}
319
+
320
+ /* 互换:画板里那张牛皮纸竖签,一半压在硫酸纸下面(层级:方格本 1 → 互换 2 → 硫酸纸 3),透过磨砂纸面能看到被盖住的那半 */
321
+ .qt-note{z-index:1}
322
+ .qt-vellum{z-index:3;pointer-events:none}
323
+ .qt-vel-in,.qt-vellum .qt-picker{pointer-events:auto}
324
+ .qt-swap{position:absolute;left:512px;top:316px;z-index:2;width:78px;height:128px;display:flex;flex-direction:column;align-items:flex-start;justify-content:center;gap:10px;padding-left:8px;transform:rotate(-3deg);color:#171717;
325
+ background:var(--qt-grain),var(--qt-grain),linear-gradient(180deg,rgba(0,0,0,.10),rgba(0,0,0,0) 14%,rgba(0,0,0,0) 86%,rgba(0,0,0,.12)),repeating-linear-gradient(90deg,rgba(0,0,0,.05) 0 1px,transparent 1px 4px),var(--qt-kraft);
326
+ box-shadow:-5px 9px 16px -6px rgba(0,0,0,.5),inset 0 0 0 1px rgba(60,35,10,.18);transition:transform .25s var(--qt-ease),opacity .15s}
327
+ .qt-swap:hover:not(:disabled){transform:rotate(-3deg) translateX(-8px)}
328
+ .qt-swap:disabled{opacity:.5}
329
+ .qt-swap small,.qt-swap b{width:26px;display:flex;justify-content:center}
330
+ .qt-swap small{font-family:var(--qt-mono);font-size:11px;font-weight:600;line-height:1}
331
+ .qt-swap b{writing-mode:vertical-rl;font-family:var(--qt-zh-sans);font-weight:900;font-size:19px;letter-spacing:.12em;line-height:1}
332
+
333
+ /* 译文:硫酸纸(画板坐标 556,48 · 600×540 · 0.7°) */
334
+ .qt-vellum{left:556px;top:48px;width:600px;height:540px;transform:rotate(.7deg);color:var(--qt-indigo)}
335
+ .qt-vellum .qt-paper{background:var(--qt-grain),rgba(226,227,223,.76);-webkit-backdrop-filter:blur(2.5px) brightness(1.06);backdrop-filter:blur(2.5px) brightness(1.06);box-shadow:0 34px 60px -28px rgba(0,0,0,.65),inset 0 0 0 1px rgba(255,255,255,.35)}
336
+ .qt-vel-in{position:absolute;inset:40px 44px 36px;display:flex;flex-direction:column}
337
+ .qt-vellum .qt-colhead{font-size:12px}
338
+ .qt-vellum .qt-dots{margin:16px 0 26px}
339
+ .qt-vellum .qt-dots.qt-dots-end{margin:0 0 16px}
340
+ .qt-tape{position:absolute;height:30px;z-index:7;pointer-events:none;background:var(--qt-grain),rgba(236,231,214,.6);clip-path:var(--qt-tape-clip)}
341
+ .qt-tape-a{left:528px;top:34px;width:118px;transform:rotate(-9deg)}
342
+ .qt-tape-b{left:1070px;top:40px;width:104px;transform:rotate(7deg)}
343
+ .qt-body{flex:1;min-height:0;position:relative;display:flex;flex-direction:column}
344
+ .qt-res{font-weight:600;font-size:23px;line-height:1.8;letter-spacing:.02em;color:var(--qt-indigo)}
345
+ .qt-res[data-lang="zh"]{font-family:var(--qt-zh-serif)}
346
+ .qt-res[data-lang="en"]{font-family:var(--qt-en-serif);font-weight:500;line-height:1.6;letter-spacing:0}
347
+ .qt-res::placeholder{color:transparent}
348
+ .qt-waiting{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;text-align:center;pointer-events:none;opacity:.55}
349
+ .qt-waiting b{font-family:var(--qt-zh-sans);font-weight:900;font-size:52px;letter-spacing:.08em;line-height:1.1}
350
+ .qt-waiting span{font-family:var(--qt-mono);font-size:12px}
351
+ .qt-chip-ok{font-weight:600}
352
+ .qt-chip-warn{color:var(--qt-redpen);font-weight:600}
353
+ .qt-live::after{content:" ···";animation:qt-blink 1s steps(2) infinite}
354
+ @keyframes qt-blink{50%{opacity:.2}}
355
+ .qt-error{margin:0 0 14px;padding:10px 12px;border:2px solid var(--qt-redpen);border-radius:3px 9px 4px 11px;transform:rotate(-.6deg);color:var(--qt-redpen);display:flex;gap:12px;align-items:flex-start;font-size:13px;line-height:1.5;flex:none}
356
+ .qt-error-text{flex:1;min-width:0;word-break:break-word}
357
+ .qt-stats{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));font-family:var(--qt-mono);font-size:11.5px;line-height:1.5;flex:none}
358
+ .qt-stats b{display:block;font-weight:600;font-size:15px;font-variant-numeric:tabular-nums}
359
+ .qt-stats > :nth-child(2){text-align:center}.qt-stats > :nth-child(3){text-align:right}
360
+ .qt-bar{height:18px;margin:14px 0 16px;flex:none;position:relative;overflow:hidden;background:repeating-linear-gradient(90deg,currentColor 0 2px,transparent 2px 6px);opacity:.18}
361
+ .qt-bar[data-state="done"]{opacity:.8}
362
+ .qt-bar[data-state="streaming"]{opacity:1;background:none}
363
+ .qt-bar[data-state="streaming"]::before{content:"";position:absolute;inset:0;background:repeating-linear-gradient(90deg,currentColor 0 2px,transparent 2px 6px);opacity:.18}
364
+ .qt-bar[data-state="streaming"]::after{content:"";position:absolute;top:0;bottom:0;left:0;width:38%;background:repeating-linear-gradient(90deg,currentColor 0 2px,transparent 2px 6px);opacity:.85;animation:qt-feed 1.6s linear infinite}
365
+ @keyframes qt-feed{from{left:-38%}to{left:100%}}
366
+ .qt-vfoot{display:flex;align-items:center;gap:12px;flex:none}
367
+ .qt-link{font-family:var(--qt-mono);font-size:12px;letter-spacing:.02em;white-space:nowrap;padding:6px 0;opacity:.9}
368
+ .qt-link:hover:not(:disabled){opacity:1;text-decoration:underline;text-underline-offset:3px}
369
+ .qt-link:disabled{opacity:.35}
370
+ .qt-btn-warn{color:var(--qt-redpen);opacity:1}
371
+ .qt-sign{width:96px;height:32px;color:var(--qt-stamp);flex:none}
372
+ .qt-stamp{position:absolute;right:70px;bottom:62px;width:112px;height:112px;transform:rotate(-14deg);opacity:.6;mix-blend-mode:multiply;color:var(--qt-stamp);pointer-events:none;animation:qt-stamp .38s var(--qt-ease)}
373
+ @keyframes qt-stamp{from{opacity:0;transform:rotate(-14deg) scale(1.35)}}
374
+
375
+ /* 模型:索引卡(红页眉线 + 蓝横线,每行正好落在一条横线上) */
376
+ .qt-picker{position:relative;min-width:0}
377
+ .qt-picker-btn{display:inline-flex;align-items:baseline;gap:8px;max-width:100%;font-family:var(--qt-mono);font-size:12px;text-transform:uppercase;letter-spacing:.02em;white-space:nowrap}
378
+ .qt-picker-btn:disabled{opacity:.5}
379
+ .qt-picker-label{font-family:var(--qt-grot);font-weight:800;font-size:17px;letter-spacing:-.01em;text-transform:none;overflow:hidden;text-overflow:ellipsis;min-width:0}
380
+ .qt-picker-tag{flex:none;opacity:.7}
381
+ .qt-chev{display:inline-block;transition:transform .2s var(--qt-ease)}
382
+ .qt-picker-btn[aria-expanded="true"] .qt-chev{transform:rotate(180deg)}
383
+ .qt-picker-menu{position:absolute;left:-6px;bottom:calc(100% + 14px);z-index:30;width:352px;max-height:352px;overflow:auto;padding:22px 22px 16px;transform:rotate(-1.6deg);transform-origin:bottom left;color:var(--qt-ink);
384
+ background:var(--qt-grain),#fbfbf8;box-shadow:0 24px 40px -12px rgba(0,0,0,.55);animation:qt-card .2s var(--qt-ease)}
385
+ @keyframes qt-card{from{opacity:0;transform:rotate(-1.6deg) translateY(8px)}}
386
+ .qt-picker-head{display:flex;justify-content:space-between;align-items:baseline;height:34px;border-bottom:1.5px solid rgba(214,80,60,.55);margin-bottom:6px}
387
+ .qt-picker-head b{font-family:var(--qt-grot);font-weight:900;font-size:20px;letter-spacing:-.03em}
388
+ .qt-picker-head span{font-family:var(--qt-mono);font-size:10.5px;color:#55575e}
389
+ .qt-picker-group-title,.qt-picker-item,.qt-picker-empty{height:28px;border-bottom:1px solid rgba(90,130,190,.28)}
390
+ .qt-picker-group-title{display:flex;align-items:flex-end;padding-bottom:4px;font-family:var(--qt-mono);font-size:10px;letter-spacing:.06em;color:#9a2d16;text-transform:uppercase}
391
+ .qt-picker-item{display:flex;align-items:center;gap:10px;width:100%;text-align:left;font-size:13px;white-space:nowrap;color:var(--qt-ink)}
392
+ .qt-picker-item:hover .qt-name{text-decoration:underline;text-underline-offset:3px}
393
+ .qt-picker-item .qt-check{width:18px;flex:none;color:var(--qt-stamp);visibility:hidden;display:inline-flex}
394
+ .qt-picker-item[aria-selected="true"] .qt-check{visibility:visible}
395
+ .qt-picker-item[aria-selected="true"] .qt-name{font-weight:700}
396
+ .qt-picker-item .qt-name{overflow:hidden;text-overflow:ellipsis;min-width:0}
397
+ .qt-picker-item .qt-id{margin-left:auto;font-family:var(--qt-mono);font-size:10px;color:var(--qt-ink-3);overflow:hidden;text-overflow:ellipsis;max-width:48%}
398
+ .qt-picker-empty{display:flex;align-items:center;font-size:12px;color:var(--qt-ink-3)}
399
+
400
+ /* 方向:牛皮纸标签(380×140 · -2°),和画板一样贴着面板右下角、露出一截被裁掉 */
401
+ .qt-tagwrap{position:absolute;right:0;bottom:0;z-index:6;pointer-events:none}
402
+ .qt-tagwrap .qt-tag{pointer-events:auto}
403
+ .qt-tag{position:relative;margin:0 -52px -22px 0;width:380px;height:140px;transform:rotate(-2deg);transform-origin:right bottom;padding:14px 22px;display:flex;flex-direction:column;gap:4px;color:#171717;
404
+ background:var(--qt-grain),repeating-linear-gradient(90deg,rgba(0,0,0,.05) 0 1px,transparent 1px 4px),var(--qt-kraft);box-shadow:0 -10px 30px -12px rgba(0,0,0,.5)}
405
+ .qt-seg{display:flex;gap:14px;font-family:var(--qt-mono);font-size:11px}
406
+ .qt-seg button{opacity:.6;white-space:nowrap}
407
+ .qt-seg button:hover:not(:disabled){opacity:.85}
408
+ .qt-seg button[aria-pressed="true"]{opacity:1;font-weight:600}
409
+ .qt-seg button[aria-pressed="true"]::before{content:"[ "}.qt-seg button[aria-pressed="true"]::after{content:" ]"}
410
+ .qt-tag-big{font-family:var(--qt-zh-sans);font-weight:900;font-size:44px;letter-spacing:-.01em;line-height:1.15;white-space:nowrap}
411
+
412
+ /* 历史:热敏小票(画板坐标 右 34,-10 · 304×600 · 1.4°,整张连字一起倾斜) */
413
+ .qt-backdrop{position:absolute;inset:0;z-index:8}
414
+ .qt-history{right:34px;top:-10px;width:304px;height:600px;transform:rotate(1.4deg);z-index:9;display:flex;flex-direction:column;padding:26px 24px 22px;color:var(--qt-ink);filter:drop-shadow(0 26px 30px rgba(0,0,0,.5))}
415
+ .qt-history .qt-paper{background:var(--qt-grain),var(--qt-receipt);
416
+ clip-path:polygon(0 1.2%,4% 0,8% 1.2%,12% 0,16% 1.2%,20% 0,24% 1.2%,28% 0,32% 1.2%,36% 0,40% 1.2%,44% 0,48% 1.2%,52% 0,56% 1.2%,60% 0,64% 1.2%,68% 0,72% 1.2%,76% 0,80% 1.2%,84% 0,88% 1.2%,92% 0,96% 1.2%,100% 0,100% 100%,96% 98.8%,92% 100%,88% 98.8%,84% 100%,80% 98.8%,76% 100%,72% 98.8%,68% 100%,64% 98.8%,60% 100%,56% 98.8%,52% 100%,48% 98.8%,44% 100%,40% 98.8%,36% 100%,32% 98.8%,28% 100%,24% 98.8%,20% 100%,16% 98.8%,12% 100%,8% 98.8%,4% 100%,0 98.8%)}
417
+ .qt-history-head{display:flex;justify-content:space-between;align-items:baseline;flex:none}
418
+ .qt-history-head b{font-family:var(--qt-grot);font-weight:900;font-size:20px;letter-spacing:-.03em}
419
+ .qt-history-head span{font-family:var(--qt-mono);font-size:11px}
420
+ .qt-history-search{display:flex;gap:8px;align-items:center;margin-top:12px;padding-bottom:6px;font-family:var(--qt-mono);font-size:11px;text-transform:uppercase;flex:none}
421
+ .qt-history-search input{flex:1;min-width:0;border:0;outline:0;background:none;font-family:var(--qt-zh-sans);font-size:12px;text-transform:none;color:var(--qt-ink)}
422
+ .qt-history-search input::placeholder{color:var(--qt-ink-3)}
423
+ .qt-perf{height:6px;margin:0 -24px;flex:none;background:radial-gradient(circle at 3px 3px,var(--qt-desk) 2.2px,transparent 2.6px) 0 0/9px 6px repeat-x}
424
+ .qt-history-scroll{flex:1;min-height:0;position:relative;margin-right:-10px}
425
+ .qt-history-list{position:absolute;inset:0;overflow-y:auto;padding:0 22px 8px 0;scrollbar-width:none}
426
+ .qt-history-list::-webkit-scrollbar{display:none}
427
+ .qt-ruler{position:absolute;right:0;top:34px;bottom:6px;width:8px;pointer-events:none;background:repeating-linear-gradient(to bottom,rgba(28,28,28,.35) 0 1px,transparent 1px 6px)}
428
+ .qt-ruler i{position:absolute;left:0;right:0;background:#1c1c1c}
429
+ .qt-hday{position:sticky;top:0;z-index:2;background:var(--qt-receipt);padding:10px 0 6px;font-family:var(--qt-mono);font-size:10.5px;color:#9a2d16;box-shadow:0 6px 6px -6px rgba(0,0,0,.22)}
430
+ .qt-hitem-wrap{position:relative}
431
+ .qt-hitem-wrap + .qt-hitem-wrap{border-top:1px dotted rgba(28,28,28,.3)}
432
+ .qt-hitem{display:block;text-align:left;padding:9px 8px 10px;margin:0 -8px;width:calc(100% + 16px);color:var(--qt-ink)}
433
+ .qt-hitem[aria-current="true"]{background:linear-gradient(transparent 8%,rgba(239,74,35,.2) 8%,rgba(239,74,35,.2) 92%,transparent 92%)}
434
+ .qt-hitem-meta{display:flex;gap:10px;font-family:var(--qt-mono);font-size:10.5px;text-transform:uppercase;letter-spacing:.02em;color:#55575e;white-space:nowrap;overflow:hidden;padding-right:20px}
435
+ .qt-hitem-meta .qt-model{overflow:hidden;text-overflow:ellipsis;min-width:0}
436
+ .qt-hitem-dst{margin-top:4px;font-size:13.5px;line-height:1.55;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word;white-space:pre-line}
437
+ .qt-hitem-dst[data-lang="zh"]{font-family:var(--qt-zh-serif)}
438
+ .qt-hitem-dst[data-lang="en"]{font-family:var(--qt-en-serif)}
439
+ .qt-hitem-src{margin-top:2px;font-size:11px;color:var(--qt-ink-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
440
+ .qt-hitem-del{position:absolute;top:8px;right:0;width:20px;height:20px;font-family:var(--qt-mono);font-size:13px;color:var(--qt-ink-3);opacity:0;pointer-events:none}
441
+ .qt-hitem-wrap:hover .qt-hitem-del,.qt-hitem-del:focus-visible{opacity:1;pointer-events:auto}
442
+ .qt-hitem-del:hover{color:var(--qt-redpen)}
443
+ .qt-empty-sm{padding:28px 4px;font-family:var(--qt-mono);font-size:11px;color:var(--qt-ink-3);white-space:pre-line;line-height:1.7;text-align:center}
444
+ .qt-history-foot{display:flex;justify-content:space-between;align-items:center;padding-top:10px;flex:none;font-family:var(--qt-mono);font-size:11px}
445
+ .qt-history-foot .qt-link{font-size:11px;padding:0}
446
+ .qt-history-foot .qt-danger{color:var(--qt-redpen);opacity:1}
447
+ .qt-barcode{height:30px;margin-top:12px;flex:none;background:repeating-linear-gradient(90deg,#1c1c1c 0 1px,transparent 1px 3px,#1c1c1c 3px 6px,transparent 6px 8px,#1c1c1c 8px 9px,transparent 9px 13px)}
448
+
449
+ /* 没有模型 */
450
+ .qt-empty-card{position:relative;isolation:isolate;max-width:460px;margin:24px;padding:30px 34px 26px;color:var(--qt-ink);display:flex;flex-direction:column;align-items:flex-start;gap:16px;transform:rotate(-1deg)}
451
+ .qt-empty-card .qt-paper{background:var(--qt-grain),var(--qt-receipt);box-shadow:0 24px 40px -16px rgba(0,0,0,.5)}
452
+ .qt-empty-card b{font-family:var(--qt-grot);font-weight:900;font-size:22px;letter-spacing:-.03em}
453
+ .qt-empty-card p{margin:0;font-size:13px;line-height:1.7;white-space:pre-line}
454
+ .qt-empty-card .qt-go{position:relative;right:auto;bottom:auto}
455
+
456
+ /* 分享 */
457
+ .qt-share{position:absolute;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;padding:24px;background:rgba(10,10,10,.62);-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px);animation:qt-fade .2s ease}
458
+ @keyframes qt-fade{from{opacity:0}}
459
+ .qt-share-card{flex:1 1 0;min-height:0;width:100%;display:flex;align-items:center;justify-content:center}
460
+ .qt-share-card img{display:block;max-width:min(560px,100%);max-height:100%;width:auto;height:auto;object-fit:contain;box-shadow:0 30px 60px -20px rgba(0,0,0,.7);animation:qt-card .3s var(--qt-ease)}
461
+ .qt-share-wait{font-family:var(--qt-mono);font-size:12px;color:#e6e3dc}
462
+ .qt-share-bar{display:flex;align-items:center;gap:22px;flex-wrap:wrap;justify-content:center;color:#e6e3dc}
463
+ .qt-share-bar .qt-go,.qt-share-bar .qt-clear{position:relative;right:auto;bottom:auto;transform:none;font-size:20px;letter-spacing:.08em;padding:12px 26px}
464
+ .qt-share-bar .qt-go:hover:not(:disabled),.qt-share-bar .qt-clear:hover:not(:disabled){transform:translateY(-2px)}
465
+ .qt-share-bar .qt-hbtn{font-size:14px}
466
+ .qt-share-msg{font-family:var(--qt-mono);font-size:11px;opacity:.8;width:100%;text-align:center}
467
+
468
+ /* 窄面板:两张纸上下叠放,不缩放 */
469
+ .qt-board.is-narrow{align-items:flex-start;overflow-y:auto}
470
+ .qt-comp.is-narrow{width:100%;height:auto;padding:14px 16px 40px 20px;display:flex;flex-direction:column}
471
+ .qt-comp.is-narrow .qt-deco-date,.qt-comp.is-narrow .qt-deco-side,.qt-comp.is-narrow .qt-tape{display:none}
472
+ .qt-comp.is-narrow .qt-note{position:relative;left:auto;top:auto;width:auto;height:420px;transform:rotate(-.8deg)}
473
+ .qt-comp.is-narrow .qt-note-in{left:66px;right:22px;top:28px;bottom:28px}
474
+ .qt-comp.is-narrow .qt-note-foot{padding-right:0;flex-wrap:wrap;row-gap:8px}
475
+ .qt-comp.is-narrow .qt-actions{position:relative;right:auto;bottom:auto;margin-left:auto}
476
+ .qt-comp.is-narrow .qt-vellum{position:relative;left:auto;top:auto;width:auto;height:480px;margin-top:30px;transform:rotate(.6deg)}
477
+ .qt-comp.is-narrow .qt-vel-in{inset:30px 24px 26px}
478
+ .qt-comp.is-narrow .qt-swap{position:relative;left:auto;top:auto;align-self:flex-end;margin:-46px 26px -40px 0;width:132px;height:42px;flex-direction:row;transform:rotate(3deg);
479
+ }
480
+ .qt-comp.is-narrow .qt-swap b{writing-mode:horizontal-tb}
481
+ .qt-comp.is-narrow .qt-stamp{right:22px}
482
+ .qt-comp.is-narrow .qt-tag{position:relative;left:auto;top:auto;width:auto;height:auto;margin:18px -24px 0 30px;padding-bottom:22px}
483
+ .qt-comp.is-narrow .qt-history{position:absolute;right:6px;top:4px;width:min(304px,92%)}
484
+ .qt-title{-webkit-text-stroke:.5px currentColor}
485
+ .qt-go,.qt-clear,.qt-swap b,.qt-picker-head b,.qt-history-head b,.qt-empty-card b{-webkit-text-stroke:.6px currentColor}
486
+ .qt-tag-big,.qt-waiting b{-webkit-text-stroke:1.1px currentColor}
487
+ @media (prefers-reduced-motion:reduce){.qt-root *,.qt-root *::before,.qt-root *::after{animation:none!important;transition:none!important}}
488
+ `
489
+
490
+ function ensureStyle() {
491
+ const tagId = 'dsh-quick-translate/style.css'
492
+ let tag = document.querySelector(`style[data-plugin-css="${tagId}"]`)
493
+ if (!tag) {
494
+ tag = document.createElement('style')
495
+ tag.dataset.plugin = 'dsh-quick-translate'
496
+ tag.dataset.pluginCss = tagId
497
+ tag.textContent = CSS
498
+ document.head.appendChild(tag)
499
+ }
500
+ return tag
501
+ }
502
+
503
+ /* ============================== 工具 ================================ */
504
+
505
+ function readJson(key, fallback) {
506
+ try {
507
+ const raw = localStorage.getItem(key)
508
+ const value = raw ? JSON.parse(raw) : fallback
509
+ return value === undefined || value === null ? fallback : value
510
+ } catch {
511
+ return fallback
512
+ }
513
+ }
514
+
515
+ function writeJson(key, value) {
516
+ try {
517
+ localStorage.setItem(key, JSON.stringify(value))
518
+ } catch {
519
+ /* 隐私模式或配额满:忽略,不影响使用 */
520
+ }
521
+ }
522
+
523
+ function modelKey(entry) {
524
+ return `${entry.provider}${SEP}${entry.model}`
525
+ }
526
+
527
+ function parseKey(key) {
528
+ if (typeof key !== 'string') return null
529
+ const i = key.indexOf(SEP)
530
+ return i < 0 ? null : { provider: key.slice(0, i), model: key.slice(i + 1) }
531
+ }
532
+
533
+ // 自动模式:汉字够多就译成英文,否则译成中文(英文句里夹几个中文词名仍译成中文)。只看前 2000 个字符
534
+ function resolveTarget(direction, text) {
535
+ if (direction === 'en2zh') return 'zh'
536
+ if (direction === 'zh2en') return 'en'
537
+ let han = 0
538
+ let latin = 0
539
+ let seen = 0
540
+ for (const ch of text) {
541
+ if (++seen > 2000) break
542
+ if (/\p{Script=Han}/u.test(ch)) han++
543
+ else if (/\p{Script=Latin}/u.test(ch)) latin++
544
+ }
545
+ return han >= 1 && han >= latin / 3 ? 'en' : 'zh'
546
+ }
547
+
548
+ async function fetchModels(refresh) {
549
+ const url = new URL(`${API}/models${refresh ? '?refresh=1' : ''}`, document.baseURI)
550
+ const response = await fetch(url, { credentials: 'same-origin' })
551
+ let payload = null
552
+ try {
553
+ payload = await response.json()
554
+ } catch {
555
+ payload = null
556
+ }
557
+ if (!response.ok || !payload || payload.ok === false) {
558
+ throw new Error((payload && (payload.message || payload.error)) || `HTTP ${response.status}`)
559
+ }
560
+ return payload
561
+ }
562
+
563
+ // 读 Host 的 SSE 流:meta → delta* → done | error
564
+ async function streamTranslate({ text, target, provider, model, onMeta, onDelta, signal }) {
565
+ const response = await fetch(new URL(`${API}/translate`, document.baseURI), {
566
+ method: 'POST',
567
+ credentials: 'same-origin',
568
+ headers: { 'Content-Type': 'application/json' },
569
+ body: JSON.stringify({ text, target, provider, model }),
570
+ signal,
571
+ })
572
+ if (!response.ok || !response.body) {
573
+ let payload = null
574
+ try {
575
+ payload = await response.json()
576
+ } catch {
577
+ payload = null
578
+ }
579
+ throw new Error((payload && (payload.message || payload.error)) || `HTTP ${response.status}`)
580
+ }
581
+ const reader = response.body.getReader()
582
+ const decoder = new TextDecoder()
583
+ let buffer = ''
584
+ let done = null
585
+ const handleBlock = (block) => {
586
+ for (const line of block.split('\n')) {
587
+ if (!line.startsWith('data:')) continue
588
+ let event
589
+ try {
590
+ event = JSON.parse(line.slice(5).trim())
591
+ } catch {
592
+ continue
593
+ }
594
+ if (event.type === 'meta') onMeta?.(event)
595
+ else if (event.type === 'delta') onDelta?.(String(event.text || ''))
596
+ else if (event.type === 'error') {
597
+ const error = new Error(event.message || 'unknown')
598
+ error.cancelled = Boolean(event.cancelled)
599
+ throw error
600
+ } else if (event.type === 'done') done = event
601
+ }
602
+ }
603
+ for (;;) {
604
+ const { value, done: finished } = await reader.read()
605
+ if (finished) break
606
+ buffer += decoder.decode(value, { stream: true })
607
+ let idx
608
+ while ((idx = buffer.indexOf('\n\n')) >= 0) {
609
+ const block = buffer.slice(0, idx)
610
+ buffer = buffer.slice(idx + 2)
611
+ handleBlock(block)
612
+ }
613
+ }
614
+ buffer += decoder.decode()
615
+ if (buffer.trim()) handleBlock(buffer)
616
+ if (!done) throw new Error('__stream_broken__')
617
+ return done
618
+ }
619
+
620
+ // 耗时文案;不足 1 秒显示毫秒
621
+ function fmtElapsed(ms, t) {
622
+ if (!ms || !(ms > 0)) return `0 ${t.seconds}`
623
+ return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} ${t.seconds}`
624
+ }
625
+
626
+ // 相对时间
627
+ function relTime(ts, t) {
628
+ const diff = Date.now() - Number(ts || 0)
629
+ const m = Math.floor(diff / 60000)
630
+ if (m < 1) return t.justNow
631
+ if (m < 60) return t.minutesAgo(m)
632
+ const hrs = Math.floor(m / 60)
633
+ if (hrs < 24) return t.hoursAgo(hrs)
634
+ const d = new Date(ts)
635
+ const now = new Date()
636
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
637
+ if (Math.round((day(now) - day(d)) / 86400000) === 1) return t.yesterday
638
+ return `${d.getMonth() + 1}/${d.getDate()}`
639
+ }
640
+
641
+ // 历史只保留结构完整的条目,并限制条数和总体积
642
+ function sanitizeHistory(list) {
643
+ if (!Array.isArray(list)) return []
644
+ const out = []
645
+ let total = 0
646
+ for (const e of list) {
647
+ if (!e || typeof e.source !== 'string' || typeof e.result !== 'string') continue
648
+ total += e.source.length + e.result.length
649
+ if (out.length >= HISTORY_MAX || total > HISTORY_MAX_CHARS) break
650
+ out.push({
651
+ id: typeof e.id === 'string' ? e.id : `${Number(e.at) || Date.now()}-${out.length}`,
652
+ source: e.source,
653
+ result: e.result,
654
+ target: e.target === 'en' ? 'en' : 'zh',
655
+ provider: String(e.provider || ''),
656
+ model: String(e.model || ''),
657
+ modelName: String(e.modelName || e.model || ''),
658
+ at: Number(e.at) || Date.now(),
659
+ elapsedMs: Number(e.elapsedMs) || 0,
660
+ truncated: Boolean(e.truncated),
661
+ })
662
+ }
663
+ return out
664
+ }
665
+
666
+ // 新条目放最前;最新一条若原文、目标语言、模型都相同,就替换而不是再堆一条
667
+ function pushHistory(list, entry) {
668
+ const rest = list.filter((e, i) => !(i === 0 && e.source === entry.source && e.target === entry.target && e.model === entry.model))
669
+ return sanitizeHistory([entry, ...rest])
670
+ }
671
+
672
+ function groupModels(list) {
673
+ const map = new Map()
674
+ for (const m of list) {
675
+ const key = m.provider
676
+ if (!map.has(key)) map.set(key, { provider: key, name: m.providerName || key, models: [] })
677
+ map.get(key).models.push(m)
678
+ }
679
+ return [...map.values()]
680
+ }
681
+
682
+ /* ============================== 图形 ================================ */
683
+
684
+ const svgProps = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true }
685
+ const P = (...d) => d.map((dd) => h('path', { d: dd }))
686
+
687
+ // 侧栏图标:DSH 侧栏里和其它插件并排,保持 Lucide 线条风格
688
+ function TranslateIcon({ size = 18 }) {
689
+ return h('svg', { ...svgProps, width: size, height: size, viewBox: '0 0 24 24' }, ...P('m5 8 6 6', 'm4 14 6-6 2-3', 'M2 5h12', 'M7 2h1', 'm22 22-5-10-5 10', 'M14 18h6'))
690
+ }
691
+ // 索引卡上的手写勾
692
+ function TickMark() {
693
+ return h('svg', { viewBox: '0 0 24 24', width: 18, height: 18, 'aria-hidden': true }, h('path', { d: 'M3 13c3 1 5 4 6 6 3-7 7-12 13-16', fill: 'none', stroke: 'currentColor', strokeWidth: 2.4, strokeLinecap: 'round' }))
694
+ }
695
+ // 模型名旁的手写签名(装饰)
696
+ function Signature() {
697
+ return h('svg', { className: 'qt-sign', viewBox: '0 0 120 40', 'aria-hidden': true }, h('path', { d: 'M4 30c10-2 14-22 22-20s-8 22 2 20 10-18 18-16-4 14 4 13 12-12 20-11 2 9 10 8 18-14 34-18', fill: 'none', stroke: 'currentColor', strokeWidth: 1.6, strokeLinecap: 'round' }))
698
+ }
699
+ // 完成时盖的「已译」章
700
+ function Stamp({ label, arrow }) {
701
+ return h(
702
+ 'svg',
703
+ { className: 'qt-stamp', viewBox: '0 0 140 140', 'aria-hidden': true },
704
+ h('defs', null, h('path', { id: 'qt-stamp-ring', d: 'M70 70 m-52 0 a52 52 0 1 1 104 0 a52 52 0 1 1 -104 0' })),
705
+ h('circle', { cx: 70, cy: 70, r: 66, fill: 'none', stroke: 'currentColor', strokeWidth: 3, strokeDasharray: '60 2 30 3 90 1' }),
706
+ h('circle', { cx: 70, cy: 70, r: 40, fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 }),
707
+ h('text', { fontFamily: 'IBM Plex Mono, ui-monospace, monospace', fontSize: 11, letterSpacing: 3, fill: 'currentColor' }, h('textPath', { href: '#qt-stamp-ring' }, `TRANSLATED ✦ DSH ✦ ${arrow} ✦ QUICK ✦`)),
708
+ h('text', { x: 70, y: 80, textAnchor: 'middle', fontFamily: 'PingFang SC, Noto Sans SC, sans-serif', fontWeight: 900, fontSize: label.length > 2 ? 22 : 28, fill: 'currentColor' }, label),
709
+ )
710
+ }
711
+
712
+ const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
713
+ const pad2 = (n) => String(n).padStart(2, '0')
714
+ const fmtClock = (ts) => { const d = new Date(ts); return `${pad2(d.getHours())}:${pad2(d.getMinutes())}` }
715
+ // 历史小票的日期分组:今天 / 昨天 / 11 月 21 日
716
+ function dayLabel(ts, t, lang) {
717
+ const d = new Date(ts)
718
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime()
719
+ const diff = Math.round((day(new Date()) - day(d)) / 86400000)
720
+ if (diff <= 0) return t.today
721
+ if (diff === 1) return t.yesterday
722
+ return lang === 'zh' ? `${d.getMonth() + 1} 月 ${d.getDate()} 日` : `${MONTHS[d.getMonth()]} ${d.getDate()}`
723
+ }
724
+ const arrowOf = (target) => (target === 'zh' ? 'EN >>> ZH' : target === 'en' ? 'ZH >>> EN' : '— >>> —')
725
+
726
+ /* ============================== 分享卡片 ============================== */
727
+
728
+ // 用 canvas 把这次翻译画成一张竖版拼贴卡:深色桌面、方格本(原文)、硫酸纸(译文)、美纹纸胶带、「已译」章、条码
729
+ const SHARE_FONTS = {
730
+ mono: '"IBM Plex Mono", "SF Mono", Menlo, monospace',
731
+ grot: '"Inter Tight", "Helvetica Neue", Helvetica, Arial, sans-serif',
732
+ zhSerif: '"Songti SC", "Noto Serif SC", "Source Han Serif SC", serif',
733
+ zhSans: '"PingFang SC", "Noto Sans SC", sans-serif',
734
+ enSerif: '"Iowan Old Style", "Newsreader", Palatino, Georgia, serif',
735
+ }
736
+ const CJK_RE = /[⺀-鿿豈-﫿＀-￯ -〿]/
737
+
738
+ // 按宽度断行:中文逐字断,英文按词断;超过 maxLines 截断并补省略号
739
+ function wrapLines(ctx, text, maxWidth, maxLines) {
740
+ const out = []
741
+ const paras = String(text || '').replace(/\r/g, '').split('\n')
742
+ paras.forEach((para, pi) => {
743
+ if (!para.trim()) {
744
+ if (out.length && pi < paras.length - 1 && out[out.length - 1] !== '') out.push('')
745
+ return
746
+ }
747
+ const tokens = para.match(new RegExp(`${CJK_RE.source}|[^\\s\\u2E80-\\u9FFF\\uF900-\\uFAFF\\uFF00-\\uFFEF\\u3000-\\u303F]+|\\s+`, 'g')) || []
748
+ let line = ''
749
+ for (const tok of tokens) {
750
+ if (!line && /^\s+$/.test(tok)) continue
751
+ if (ctx.measureText(line + tok).width <= maxWidth) {
752
+ line += tok
753
+ continue
754
+ }
755
+ if (line) out.push(line.trimEnd())
756
+ line = ''
757
+ if (/^\s+$/.test(tok)) continue
758
+ let rest = tok
759
+ while (ctx.measureText(rest).width > maxWidth && rest.length > 1) {
760
+ let i = rest.length
761
+ while (i > 1 && ctx.measureText(rest.slice(0, i)).width > maxWidth) i--
762
+ out.push(rest.slice(0, i))
763
+ rest = rest.slice(i)
764
+ }
765
+ line = rest
766
+ }
767
+ if (line) out.push(line.trimEnd())
768
+ })
769
+ while (out.length && out[out.length - 1] === '') out.pop()
770
+ if (out.length <= maxLines) return { lines: out, truncated: false }
771
+ const cut = out.slice(0, maxLines)
772
+ let last = cut[maxLines - 1]
773
+ while (last && ctx.measureText(`${last}…`).width > maxWidth) last = last.slice(0, -1)
774
+ cut[maxLines - 1] = `${last}…`
775
+ return { lines: cut, truncated: true }
776
+ }
777
+
778
+ function grainPattern(ctx, alpha) {
779
+ const c = document.createElement('canvas')
780
+ c.width = 180
781
+ c.height = 180
782
+ const g = c.getContext('2d')
783
+ const img = g.createImageData(180, 180)
784
+ for (let i = 0; i < img.data.length; i += 4) {
785
+ const v = Math.random() * 255
786
+ img.data[i] = v
787
+ img.data[i + 1] = v
788
+ img.data[i + 2] = v
789
+ img.data[i + 3] = Math.random() * alpha
790
+ }
791
+ g.putImageData(img, 0, 0)
792
+ return ctx.createPattern(c, 'repeat')
793
+ }
794
+
795
+ async function renderShareCard({ source, result, target, modelName, elapsedMs, t }) {
796
+ try {
797
+ await document.fonts?.ready
798
+ } catch {
799
+ /* 字体没就绪就用回退字体画 */
800
+ }
801
+ const F = SHARE_FONTS
802
+ const W = 1080
803
+ const S = 2
804
+ const toZh = target !== 'en'
805
+ const measure = document.createElement('canvas').getContext('2d')
806
+
807
+ // ---- 排版 ----
808
+ const padX = 84
809
+ const noteX = padX
810
+ const noteW = W - padX * 2
811
+ const noteY = 196
812
+ const srcFont = `400 25px ${F.mono}`
813
+ measure.font = srcFont
814
+ const src = wrapLines(measure, source, noteW - 128 - 56, 7)
815
+ const srcLH = 42
816
+ const noteH = 52 + 24 + 34 + src.lines.length * srcLH + 64
817
+
818
+ const velX = padX + 34
819
+ const velW = noteW - 34
820
+ const velY = noteY + noteH - 26
821
+ let size = 46
822
+ let dst = null
823
+ for (; size >= 30; size -= 4) {
824
+ measure.font = toZh ? `600 ${size}px ${F.zhSerif}` : `500 ${size}px ${F.enSerif}`
825
+ dst = wrapLines(measure, result, velW - 116, 12)
826
+ if (!dst.truncated && dst.lines.length <= 8) break
827
+ }
828
+ size = Math.max(size, 30)
829
+ const dstFont = toZh ? `600 ${size}px ${F.zhSerif}` : `500 ${size}px ${F.enSerif}`
830
+ const dstLH = Math.round(size * (toZh ? 1.72 : 1.5))
831
+ const velH = 58 + 24 + 40 + dst.lines.length * dstLH + 36 + 34 + 56 + 34 + 60
832
+ const H = Math.max(1180, velY + velH + 150)
833
+
834
+ const canvas = document.createElement('canvas')
835
+ canvas.width = W * S
836
+ canvas.height = H * S
837
+ const ctx = canvas.getContext('2d')
838
+ ctx.scale(S, S)
839
+ ctx.textBaseline = 'alphabetic'
840
+ const shadow = (blur, y, a) => {
841
+ ctx.shadowColor = `rgba(0,0,0,${a})`
842
+ ctx.shadowBlur = blur
843
+ ctx.shadowOffsetY = y
844
+ }
845
+ const noShadow = () => {
846
+ ctx.shadowColor = 'transparent'
847
+ ctx.shadowBlur = 0
848
+ ctx.shadowOffsetY = 0
849
+ }
850
+ const tilt = (x, y, w, h, a) => {
851
+ ctx.translate(x + w / 2, y + h / 2)
852
+ ctx.rotate(a)
853
+ ctx.translate(-(x + w / 2), -(y + h / 2))
854
+ }
855
+ const dots = (x1, x2, y, color) => {
856
+ ctx.fillStyle = color
857
+ for (let x = x1; x < x2; x += 9) {
858
+ ctx.beginPath()
859
+ ctx.arc(x, y, 1.3, 0, Math.PI * 2)
860
+ ctx.fill()
861
+ }
862
+ }
863
+ const tape = (x, y, w, a) => {
864
+ ctx.save()
865
+ tilt(x, y, w, 34, a)
866
+ ctx.beginPath()
867
+ ctx.moveTo(x, y + 3)
868
+ for (let i = 0; i <= 6; i++) ctx.lineTo(x + i * 3, y + (i % 2 ? 0 : 4))
869
+ ctx.lineTo(x + w, y)
870
+ for (let i = 0; i <= 6; i++) ctx.lineTo(x + w - (i % 2 ? 3 : 0), y + i * 5.6)
871
+ ctx.lineTo(x, y + 34)
872
+ for (let i = 6; i >= 0; i--) ctx.lineTo(x + (i % 2 ? 3 : 0), y + i * 5.6)
873
+ ctx.closePath()
874
+ shadow(4, 2, 0.18)
875
+ ctx.fillStyle = 'rgba(232,220,186,0.9)'
876
+ ctx.fill()
877
+ noShadow()
878
+ ctx.restore()
879
+ }
880
+
881
+ // ---- 桌面 ----
882
+ ctx.fillStyle = '#1c1b1a'
883
+ ctx.fillRect(0, 0, W, H)
884
+ const vg = ctx.createRadialGradient(W * 0.45, H * 0.38, W * 0.15, W * 0.5, H * 0.5, W)
885
+ vg.addColorStop(0, 'rgba(255,255,255,0.05)')
886
+ vg.addColorStop(1, 'rgba(0,0,0,0.5)')
887
+ ctx.fillStyle = vg
888
+ ctx.fillRect(0, 0, W, H)
889
+ ctx.fillStyle = '#e8e5de'
890
+ ctx.font = `900 54px ${F.grot}`
891
+ ctx.fillText('Quick Translate', padX, 116)
892
+ ctx.strokeStyle = '#e8e5de'
893
+ ctx.lineWidth = 1.2
894
+ ctx.strokeText('Quick Translate', padX, 116)
895
+ ctx.font = `500 19px ${F.mono}`
896
+ ctx.fillStyle = 'rgba(232,229,222,0.5)'
897
+ ctx.fillText(`[ ${t.title} ] DEEPSEEK HARNESS PLUGIN · BY ${AUTHOR.toUpperCase()}`, padX, 152)
898
+ ctx.textAlign = 'right'
899
+ ctx.font = `600 22px ${F.mono}`
900
+ ctx.fillStyle = 'rgba(232,229,222,0.8)'
901
+ ctx.fillText(arrowOf(target), W - padX, 116)
902
+ ctx.textAlign = 'left'
903
+
904
+ // ---- 原文:方格本 ----
905
+ ctx.save()
906
+ tilt(noteX, noteY, noteW, noteH, -0.009)
907
+ const torn = () => {
908
+ ctx.beginPath()
909
+ ctx.moveTo(noteX, noteY)
910
+ ctx.lineTo(noteX + noteW, noteY)
911
+ ctx.lineTo(noteX + noteW, noteY + noteH - 12)
912
+ const n = 24
913
+ for (let i = n; i >= 0; i--) ctx.lineTo(noteX + (noteW * i) / n, noteY + noteH - (i % 2 ? 3 : 13) - ((i * 7) % 5))
914
+ ctx.closePath()
915
+ }
916
+ shadow(40, 22, 0.45)
917
+ ctx.fillStyle = '#eeede7'
918
+ torn()
919
+ ctx.fill()
920
+ noShadow()
921
+ ctx.save()
922
+ torn()
923
+ ctx.clip()
924
+ ctx.strokeStyle = '#c6d0d8'
925
+ ctx.lineWidth = 1
926
+ for (let gx = noteX + 8; gx < noteX + noteW; gx += 28) {
927
+ ctx.beginPath()
928
+ ctx.moveTo(gx + 0.5, noteY)
929
+ ctx.lineTo(gx + 0.5, noteY + noteH)
930
+ ctx.stroke()
931
+ }
932
+ for (let gy = noteY + 14; gy < noteY + noteH; gy += 28) {
933
+ ctx.beginPath()
934
+ ctx.moveTo(noteX, gy + 0.5)
935
+ ctx.lineTo(noteX + noteW, gy + 0.5)
936
+ ctx.stroke()
937
+ }
938
+ ctx.strokeStyle = 'rgba(214,80,60,0.5)'
939
+ ctx.beginPath()
940
+ ctx.moveTo(noteX + 98.5, noteY)
941
+ ctx.lineTo(noteX + 98.5, noteY + noteH)
942
+ ctx.stroke()
943
+ ctx.fillStyle = '#1c1b1a'
944
+ for (let hy = noteY + 24; hy < noteY + noteH - 24; hy += 34) {
945
+ ctx.beginPath()
946
+ ctx.arc(noteX + 52, hy, 8.5, 0, Math.PI * 2)
947
+ ctx.fill()
948
+ }
949
+ ctx.restore()
950
+ ctx.fillStyle = '#121212'
951
+ for (let hy = noteY + 16; hy < noteY + noteH - 30; hy += 34) ctx.fillRect(noteX - 8, hy, 26, 15)
952
+ const tx = noteX + 128
953
+ ctx.fillStyle = '#34363d'
954
+ ctx.font = `500 18px ${F.mono}`
955
+ ctx.fillText(`${t.source} / SOURCE`, tx, noteY + 52)
956
+ ctx.textAlign = 'right'
957
+ ctx.fillText(toZh ? 'EN' : 'ZH', noteX + noteW - 56, noteY + 52)
958
+ ctx.textAlign = 'left'
959
+ dots(tx, noteX + noteW - 56, noteY + 76, 'rgba(52,54,61,0.5)')
960
+ ctx.fillStyle = '#1b1b1b'
961
+ ctx.font = srcFont
962
+ src.lines.forEach((ln, i) => ctx.fillText(ln, tx, noteY + 52 + 24 + 34 + 26 + i * srcLH))
963
+ ctx.restore()
964
+
965
+ // ---- 译文:硫酸纸 ----
966
+ ctx.save()
967
+ tilt(velX, velY, velW, velH, 0.007)
968
+ shadow(60, 30, 0.5)
969
+ ctx.fillStyle = 'rgba(229,230,226,0.985)'
970
+ ctx.fillRect(velX, velY, velW, velH)
971
+ noShadow()
972
+ const vx = velX + 58
973
+ const vr = velX + velW - 58
974
+ const indigo = '#41468a'
975
+ ctx.fillStyle = indigo
976
+ ctx.font = `500 18px ${F.mono}`
977
+ ctx.fillText(`${t.result} / TRANSLATION`, vx, velY + 58)
978
+ ctx.textAlign = 'right'
979
+ ctx.fillText(elapsedMs ? `${t.done} ${fmtElapsed(elapsedMs, t)}` : t.done, vr, velY + 58)
980
+ ctx.textAlign = 'left'
981
+ dots(vx, vr, velY + 82, 'rgba(65,70,138,0.5)')
982
+ ctx.font = dstFont
983
+ ctx.fillStyle = indigo
984
+ const dy0 = velY + 82 + 40 + size
985
+ dst.lines.forEach((ln, i) => ctx.fillText(ln, vx, dy0 + i * dstLH))
986
+ let y = dy0 + (dst.lines.length - 1) * dstLH + 46
987
+ dots(vx, vr, y, 'rgba(65,70,138,0.5)')
988
+ y += 50
989
+ ctx.font = `500 17px ${F.mono}`
990
+ ctx.fillText('MODEL:', vx, y)
991
+ ctx.font = `800 27px ${F.grot}`
992
+ ctx.fillText(modelName || '—', vx + 82, y + 1)
993
+ y += 30
994
+ const barY = y
995
+ let seed = 0
996
+ for (const ch of String(result)) seed = (seed * 31 + ch.charCodeAt(0)) >>> 0
997
+ ctx.fillStyle = indigo
998
+ for (let x = vx; x < vr - 196; ) {
999
+ seed = (seed * 1103515245 + 12345) >>> 0
1000
+ const w = 1 + (seed % 3)
1001
+ ctx.fillRect(x, y, w, 34)
1002
+ x += w + 2 + ((seed >> 4) % 4)
1003
+ }
1004
+ ctx.restore()
1005
+ tape(velX - 26, velY - 14, 126, -0.16)
1006
+ tape(velX + velW - 104, velY - 10, 116, 0.12)
1007
+
1008
+ // 「已译」章
1009
+ ctx.save()
1010
+ const cx = velX + velW - 58 - 92
1011
+ const cy = barY + 2
1012
+ ctx.translate(cx, cy)
1013
+ ctx.rotate(-0.26)
1014
+ ctx.globalAlpha = 0.66
1015
+ ctx.strokeStyle = '#3a3fa6'
1016
+ ctx.fillStyle = '#3a3fa6'
1017
+ ctx.lineWidth = 4
1018
+ ctx.beginPath()
1019
+ ctx.arc(0, 0, 82, 0, Math.PI * 2)
1020
+ ctx.stroke()
1021
+ ctx.lineWidth = 2
1022
+ ctx.beginPath()
1023
+ ctx.arc(0, 0, 50, 0, Math.PI * 2)
1024
+ ctx.stroke()
1025
+ ctx.font = `900 ${t.stamp.length > 2 ? 26 : 36}px ${F.zhSans}`
1026
+ ctx.textAlign = 'center'
1027
+ ctx.fillText(t.stamp, 0, 12)
1028
+ ctx.font = `600 13px ${F.mono}`
1029
+ const ring = 'TRANSLATED ✦ DSH ✦ QUICK TRANSLATE ✦ '
1030
+ const step = (Math.PI * 2) / ring.length
1031
+ ;[...ring].forEach((ch, i) => {
1032
+ ctx.save()
1033
+ ctx.rotate(-Math.PI / 2 + i * step)
1034
+ ctx.translate(0, -62)
1035
+ ctx.fillText(ch, 0, 4)
1036
+ ctx.restore()
1037
+ })
1038
+ ctx.restore()
1039
+
1040
+ // ---- 桌面底部 ----
1041
+ const now = new Date()
1042
+ ctx.fillStyle = 'rgba(232,229,222,0.2)'
1043
+ ctx.font = `800 38px ${F.grot}`
1044
+ ctx.fillText(`${now.getDate()} ${MONTHS[now.getMonth()]} ${now.getFullYear()}`, padX, H - 66)
1045
+ ctx.textAlign = 'right'
1046
+ ctx.font = `500 17px ${F.mono}`
1047
+ ctx.fillStyle = 'rgba(232,229,222,0.45)'
1048
+ ctx.fillText('MADE WITH DEEPSEEK HARNESS', W - padX, H - 70)
1049
+ ctx.textAlign = 'left'
1050
+
1051
+ // 颗粒
1052
+ ctx.fillStyle = grainPattern(ctx, 22)
1053
+ ctx.fillRect(0, 0, W, H)
1054
+
1055
+ return new Promise((resolve) => canvas.toBlob((b) => resolve(b), 'image/png'))
1056
+ }
1057
+
1058
+ /** 分享:生成卡片 → 预览 → 复制图片 / 保存图片。浮层画在面板自己里面,不往 body 挂东西。 */
1059
+ function ShareSheet({ data, t, onClose }) {
1060
+ const [url, setUrl] = useState('')
1061
+ const [blob, setBlob] = useState(null)
1062
+ const [msg, setMsg] = useState('')
1063
+ useEffect(() => {
1064
+ let alive = true
1065
+ let made = ''
1066
+ renderShareCard(data)
1067
+ .then((b) => {
1068
+ if (!alive || !b) return
1069
+ made = URL.createObjectURL(b)
1070
+ setBlob(b)
1071
+ setUrl(made)
1072
+ })
1073
+ .catch((err) => alive && setMsg(String(err?.message || err)))
1074
+ return () => {
1075
+ alive = false
1076
+ if (made) URL.revokeObjectURL(made)
1077
+ }
1078
+ }, [data])
1079
+ useEffect(() => {
1080
+ const onKey = (e) => {
1081
+ if (e.key !== 'Escape') return
1082
+ e.stopPropagation()
1083
+ onClose()
1084
+ }
1085
+ document.addEventListener('keydown', onKey, true)
1086
+ return () => document.removeEventListener('keydown', onKey, true)
1087
+ }, [onClose])
1088
+ const copy = async () => {
1089
+ try {
1090
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
1091
+ setMsg(t.shareCopied)
1092
+ } catch {
1093
+ setMsg(t.shareCopyFailed)
1094
+ }
1095
+ }
1096
+ const save = () => {
1097
+ const a = document.createElement('a')
1098
+ a.href = url
1099
+ a.download = `quick-translate-${new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-')}.png`
1100
+ a.click()
1101
+ setMsg(t.shareSaved)
1102
+ }
1103
+ return h(
1104
+ 'div',
1105
+ { className: 'qt-share', role: 'dialog', 'aria-modal': 'true', 'aria-label': t.shareTitle, onClick: (e) => e.target === e.currentTarget && onClose() },
1106
+ h('div', { className: 'qt-share-card' }, url ? h('img', { src: url, alt: t.shareTitle }) : h('span', { className: 'qt-share-wait' }, msg || t.shareMaking)),
1107
+ h(
1108
+ 'div',
1109
+ { className: 'qt-share-bar' },
1110
+ h('button', { type: 'button', className: 'qt-tapebtn qt-go qt-btn-primary', onClick: copy, disabled: !blob }, t.shareCopy),
1111
+ h('button', { type: 'button', className: 'qt-tapebtn qt-clear', onClick: save, disabled: !url }, t.shareSave),
1112
+ h('button', { type: 'button', className: 'qt-hbtn', onClick: onClose }, t.shareClose),
1113
+ url && msg ? h('span', { className: 'qt-share-msg', role: 'status' }, msg) : null,
1114
+ ),
1115
+ )
1116
+ }
1117
+
1118
+ // 文本框的刻度尺:内容超出时才出现,实心段表示当前位置
1119
+ function thumbOf(el) {
1120
+ if (!el || !el.scrollHeight) return null
1121
+ const sh = el.scrollHeight
1122
+ const ch = el.clientHeight
1123
+ if (sh <= ch + 2) return null
1124
+ const size = Math.max(8, (ch / sh) * 100)
1125
+ return { top: (el.scrollTop / (sh - ch)) * (100 - size), size }
1126
+ }
1127
+ const rulerOf = (thumb) => (thumb ? h('div', { className: `qt-tarul ${thumb.on ? 'is-on' : ''}`, 'aria-hidden': 'true' }, h('i', { style: { top: `${thumb.top}%`, height: `${thumb.size}%` } })) : null)
1128
+
1129
+ /* ============================== 组件 ================================ */
1130
+
1131
+ /** 模型选择:硫酸纸底部的一行字,点开是一张索引卡(absolute 锚在按钮上方,不受祖先 transform 影响)。 */
1132
+ function ModelPicker({ groups, defaultRoute, value, onChange, loading, disabled, t }) {
1133
+ const [open, setOpen] = useState(false)
1134
+ const btnRef = useRef(null)
1135
+ const menuRef = useRef(null)
1136
+ const parsed = parseKey(value)
1137
+ const selected = parsed ? groups.flatMap((g) => g.models).find((m) => m.provider === parsed.provider && m.model === parsed.model) || null : null
1138
+ const label = selected
1139
+ ? selected.name || selected.model
1140
+ : defaultRoute
1141
+ ? defaultRoute.model
1142
+ : loading
1143
+ ? t.loadingModels
1144
+ : t.selectModel
1145
+ const total = groups.reduce((n, g) => n + g.models.length, 0)
1146
+
1147
+ useEffect(() => {
1148
+ if (!open) return undefined
1149
+ const onDown = (e) => {
1150
+ if (btnRef.current?.contains(e.target) || menuRef.current?.contains(e.target)) return
1151
+ setOpen(false)
1152
+ }
1153
+ const onKey = (e) => {
1154
+ if (e.key !== 'Escape') return
1155
+ // 只关菜单,别让同一下 Esc 穿透到面板的「取消翻译」
1156
+ e.stopPropagation()
1157
+ setOpen(false)
1158
+ }
1159
+ document.addEventListener('mousedown', onDown)
1160
+ document.addEventListener('keydown', onKey)
1161
+ return () => {
1162
+ document.removeEventListener('mousedown', onDown)
1163
+ document.removeEventListener('keydown', onKey)
1164
+ }
1165
+ }, [open])
1166
+
1167
+ const toggle = () => {
1168
+ if (disabled) return
1169
+ setOpen((v) => !v)
1170
+ }
1171
+
1172
+ const pick = (key) => {
1173
+ onChange(key)
1174
+ setOpen(false)
1175
+ btnRef.current?.focus()
1176
+ }
1177
+
1178
+ const item = (key, name, id) =>
1179
+ h(
1180
+ 'button',
1181
+ { type: 'button', key: key || '__default', className: 'qt-picker-item', role: 'option', 'aria-selected': value === key ? 'true' : 'false', onClick: () => pick(key) },
1182
+ h('span', { className: 'qt-check' }, h(TickMark)),
1183
+ h('span', { className: 'qt-name' }, name),
1184
+ id && id !== name ? h('span', { className: 'qt-id' }, id) : null,
1185
+ )
1186
+
1187
+ return h(
1188
+ 'div',
1189
+ { className: 'qt-picker' },
1190
+ h(
1191
+ 'button',
1192
+ { ref: btnRef, type: 'button', className: 'qt-picker-btn', onClick: toggle, disabled: disabled || loading, 'aria-haspopup': 'listbox', 'aria-expanded': open ? 'true' : 'false', title: !selected && defaultRoute ? `${t.followDefault} · ${label}` : label },
1193
+ h('span', null, `${t.model}:`),
1194
+ h('span', { className: 'qt-picker-label' }, label),
1195
+ !selected && defaultRoute ? h('span', { className: 'qt-picker-tag' }, `[${t.defaultShort}]`) : null,
1196
+ h('span', { className: 'qt-chev', 'aria-hidden': true }, '▾'),
1197
+ ),
1198
+ open
1199
+ ? h(
1200
+ 'div',
1201
+ { ref: menuRef, className: 'qt-picker-menu', role: 'listbox', 'aria-label': t.selectModel },
1202
+ h('div', { className: 'qt-picker-head' }, h('b', null, t.model), h('span', null, t.modelCount(total))),
1203
+ defaultRoute ? item('', `${t.followDefault}`, defaultRoute.model) : null,
1204
+ groups.map((g) =>
1205
+ h(
1206
+ 'div',
1207
+ { key: g.provider },
1208
+ h('div', { className: 'qt-picker-group-title' }, g.name),
1209
+ g.models.map((m) => item(modelKey(m), m.name || m.model, m.model)),
1210
+ ),
1211
+ ),
1212
+ loading ? h('div', { className: 'qt-picker-empty' }, t.loadingModels) : null,
1213
+ !loading && groups.length === 0 && !defaultRoute ? h('div', { className: 'qt-picker-empty' }, t.selectModel) : null,
1214
+ )
1215
+ : null,
1216
+ )
1217
+ }
1218
+
1219
+ /** 历史:一张热敏小票。头尾固定,中间单独滚动;日期标签吸顶;右边缘的刻度尺代替滚动条。 */
1220
+ function HistoryPanel({ history, currentId, query, onQuery, onPick, onDelete, onClear, clearArmed, t, lang }) {
1221
+ const [thumb, setThumb] = useState({ top: 0, size: 100 })
1222
+ const q = query.trim().toLowerCase()
1223
+ const shown = q
1224
+ ? history.filter((e) => e.source.toLowerCase().includes(q) || e.result.toLowerCase().includes(q) || e.modelName.toLowerCase().includes(q))
1225
+ : history
1226
+ const onScroll = (event) => {
1227
+ const el = event.currentTarget
1228
+ const size = el.scrollHeight > 0 ? Math.min(100, (el.clientHeight / el.scrollHeight) * 100) : 100
1229
+ const room = el.scrollHeight - el.clientHeight
1230
+ setThumb({ top: room > 0 ? (el.scrollTop / room) * (100 - size) : 0, size })
1231
+ }
1232
+ const rows = []
1233
+ let lastDay = ''
1234
+ for (const e of shown) {
1235
+ const d = dayLabel(e.at, t, lang)
1236
+ if (d !== lastDay) {
1237
+ rows.push(h('div', { key: `d-${e.id}`, className: 'qt-hday' }, `— ${d} —`))
1238
+ lastDay = d
1239
+ }
1240
+ rows.push(
1241
+ h(
1242
+ 'div',
1243
+ { key: e.id, role: 'listitem', className: 'qt-hitem-wrap' },
1244
+ h(
1245
+ 'button',
1246
+ { type: 'button', className: 'qt-hitem', 'aria-current': e.id === currentId ? 'true' : 'false', onClick: () => onPick(e), title: e.source.slice(0, 200) },
1247
+ h(
1248
+ 'div',
1249
+ { className: 'qt-hitem-meta' },
1250
+ h('span', null, fmtClock(e.at)),
1251
+ h('span', null, e.target === 'zh' ? 'EN>ZH' : 'ZH>EN'),
1252
+ e.modelName ? h('span', { className: 'qt-model' }, e.modelName) : null,
1253
+ ),
1254
+ h('div', { className: 'qt-hitem-dst', 'data-lang': e.target }, e.result),
1255
+ h('div', { className: 'qt-hitem-src' }, e.source),
1256
+ ),
1257
+ h(
1258
+ 'button',
1259
+ { type: 'button', className: 'qt-hitem-del', title: t.historyDelete, 'aria-label': t.historyDelete, onClick: (ev) => { ev.stopPropagation(); onDelete(e.id) } },
1260
+ '×',
1261
+ ),
1262
+ ),
1263
+ )
1264
+ }
1265
+ return h(
1266
+ 'aside',
1267
+ { className: 'qt-history qt-col', 'aria-label': t.history },
1268
+ h('div', { className: 'qt-paper', 'aria-hidden': 'true' }),
1269
+ h('div', { className: 'qt-history-head' }, h('b', null, t.history), h('span', null, `No. ${pad2(history.length)}`)),
1270
+ h(
1271
+ 'label',
1272
+ { className: 'qt-history-search' },
1273
+ h('span', null, 'Find:'),
1274
+ h('input', { type: 'search', value: query, placeholder: t.historySearch, onChange: (e) => onQuery(e.target.value), 'aria-label': t.historySearch, disabled: history.length === 0 }),
1275
+ ),
1276
+ h('div', { className: 'qt-perf', 'aria-hidden': 'true' }),
1277
+ h(
1278
+ 'div',
1279
+ { className: 'qt-history-scroll' },
1280
+ h(
1281
+ 'div',
1282
+ { className: 'qt-history-list', role: 'list', onScroll },
1283
+ history.length === 0
1284
+ ? h('div', { className: 'qt-empty-sm' }, t.historyEmpty)
1285
+ : shown.length === 0
1286
+ ? h('div', { className: 'qt-empty-sm' }, t.historyEmptyFiltered)
1287
+ : rows,
1288
+ ),
1289
+ thumb.size < 100
1290
+ ? h('div', { className: 'qt-ruler', 'aria-hidden': 'true' }, h('i', { style: { top: `${thumb.top}%`, height: `${thumb.size}%` } }))
1291
+ : null,
1292
+ ),
1293
+ h('div', { className: 'qt-perf', 'aria-hidden': 'true' }),
1294
+ h(
1295
+ 'div',
1296
+ { className: 'qt-history-foot' },
1297
+ history.length
1298
+ ? h(
1299
+ 'button',
1300
+ { type: 'button', className: `qt-link qt-br ${clearArmed ? 'qt-danger' : ''}`, onClick: onClear },
1301
+ clearArmed ? t.historyConfirm : t.historyClear,
1302
+ )
1303
+ : h('span'),
1304
+ h('span', null, t.historyTotal(history.length)),
1305
+ ),
1306
+ h('div', { className: 'qt-barcode', 'aria-hidden': 'true' }),
1307
+ )
1308
+ }
1309
+
1310
+ function TranslatePanel() {
1311
+ const lang = useLang()
1312
+ const t = STR[lang] || STR.en
1313
+ const langName = (code) => (code === 'zh' ? t.langZh : t.langEn)
1314
+
1315
+ const prefs = useMemo(() => readJson(PREFS_KEY, {}), [])
1316
+ const draft = useMemo(() => readJson(DRAFT_KEY, {}), [])
1317
+ const [source, setSource] = useState(typeof draft.source === 'string' ? draft.source : '')
1318
+ const [result, setResult] = useState(typeof draft.result === 'string' ? draft.result : '')
1319
+ const [direction, setDirection] = useState(['en2zh', 'zh2en', 'auto'].includes(prefs.direction) ? prefs.direction : 'auto')
1320
+ // 窄屏下历史是盖住内容的小票,默认不展开,免得一打开面板先看到的是「还没有翻译记录」
1321
+ const [historyOpen, setHistoryOpen] = useState(prefs.historyOpen === true && window.innerWidth > 720)
1322
+ const [history, setHistory] = useState(() => sanitizeHistory(readJson(HISTORY_KEY, [])))
1323
+ const [historyQuery, setHistoryQuery] = useState('')
1324
+ const [clearArmed, setClearArmed] = useState(false)
1325
+ const [currentId, setCurrentId] = useState(null)
1326
+ const [models, setModels] = useState(null)
1327
+ const [skipped, setSkipped] = useState(0)
1328
+ const [defaultRoute, setDefaultRoute] = useState(null)
1329
+ const [modelKeyState, setModelKeyState] = useState(typeof prefs.modelKey === 'string' ? prefs.modelKey : '')
1330
+ const [modelsLoading, setModelsLoading] = useState(false)
1331
+ const [modelsError, setModelsError] = useState('')
1332
+ const [status, setStatus] = useState('idle') // idle | streaming | done | error
1333
+ const [error, setError] = useState('')
1334
+ const [elapsed, setElapsed] = useState(0)
1335
+ const [usedRoute, setUsedRoute] = useState(null)
1336
+ const [usedTarget, setUsedTarget] = useState(null)
1337
+ const [truncated, setTruncated] = useState(false)
1338
+ const [cancelled, setCancelled] = useState(false)
1339
+ const [copied, setCopied] = useState(false)
1340
+ const [copyFailed, setCopyFailed] = useState(false)
1341
+ const [shareData, setShareData] = useState(null)
1342
+ const boardRef = useRef(null)
1343
+ // 桌面按画板 E 的 1200×690 原样搭好,再整体缩放到面板大小;面板窄于 760 时改成上下叠放、不缩放
1344
+ const [fit, setFit] = useState({ scale: 1, narrow: window.innerWidth < 760 })
1345
+ useEffect(() => {
1346
+ const el = boardRef.current
1347
+ if (!el || typeof ResizeObserver === 'undefined') return undefined
1348
+ const measure = () => {
1349
+ const w = el.clientWidth
1350
+ const hh = el.clientHeight
1351
+ const narrow = w < 760
1352
+ const scale = narrow ? 1 : Math.max(0.55, Math.min(1.6, (w - 16) / COMP_W, (hh - 8) / COMP_H))
1353
+ setFit((p) => (p.narrow === narrow && Math.abs(p.scale - scale) < 0.004 ? p : { scale, narrow }))
1354
+ }
1355
+ const ro = new ResizeObserver(measure)
1356
+ ro.observe(el)
1357
+ measure()
1358
+ return () => ro.disconnect()
1359
+ }, [])
1360
+ const [srcThumb, setSrcThumb] = useState(null)
1361
+ const [resThumb, setResThumb] = useState(null)
1362
+ const rulerTimers = useRef({})
1363
+ // 滚动时亮出刻度尺,停下 900ms 后淡出
1364
+ const flashRuler = (key, setter, el) => {
1365
+ const th = thumbOf(el)
1366
+ setter(th ? { ...th, on: true } : null)
1367
+ clearTimeout(rulerTimers.current[key])
1368
+ rulerTimers.current[key] = setTimeout(() => setter((p) => (p ? { ...p, on: false } : p)), 900)
1369
+ }
1370
+ useEffect(() => setSrcThumb(thumbOf(sourceRef.current)), [source, fit])
1371
+ useEffect(() => {
1372
+ const el = resultRef.current
1373
+ // 流式输出时跟着最新一行往下走
1374
+ if (el && status === 'streaming') el.scrollTop = el.scrollHeight
1375
+ setResThumb(thumbOf(el))
1376
+ }, [result, fit, status])
1377
+ const abortRef = useRef(null)
1378
+ const resultRef = useRef(null)
1379
+ const sourceRef = useRef(null)
1380
+
1381
+ // 草稿和偏好落 localStorage:切到别的面板再回来不丢。流式输出时 delta 很密,草稿写入做 400ms 去抖
1382
+ useEffect(() => {
1383
+ const id = setTimeout(() => writeJson(DRAFT_KEY, { source, result }), 400)
1384
+ return () => clearTimeout(id)
1385
+ }, [source, result])
1386
+ useEffect(() => writeJson(PREFS_KEY, { modelKey: modelKeyState, direction, historyOpen }), [modelKeyState, direction, historyOpen])
1387
+ useEffect(() => writeJson(HISTORY_KEY, history), [history])
1388
+
1389
+ // 「确认清空」3 秒后自动撤回
1390
+ useEffect(() => {
1391
+ if (!clearArmed) return undefined
1392
+ const id = setTimeout(() => setClearArmed(false), 3000)
1393
+ return () => clearTimeout(id)
1394
+ }, [clearArmed])
1395
+
1396
+ const loadModels = useCallback(
1397
+ async (refresh) => {
1398
+ setModelsLoading(true)
1399
+ setModelsError('')
1400
+ try {
1401
+ const payload = await fetchModels(refresh)
1402
+ const list = Array.isArray(payload.models) ? payload.models : []
1403
+ setModels(list)
1404
+ setSkipped(Array.isArray(payload.skipped) ? payload.skipped.length : 0)
1405
+ setDefaultRoute(payload.default && payload.default.provider && payload.default.model ? payload.default : null)
1406
+ // 上次选的模型已经被用户从 DSH 里删掉 → 退回跟随默认
1407
+ setModelKeyState((prev) => {
1408
+ const parsed = parseKey(prev)
1409
+ if (!parsed) return prev
1410
+ return list.some((m) => m.provider === parsed.provider && m.model === parsed.model) ? prev : ''
1411
+ })
1412
+ } catch (err) {
1413
+ setModelsError(String(err?.message || err))
1414
+ } finally {
1415
+ setModelsLoading(false)
1416
+ }
1417
+ },
1418
+ [],
1419
+ )
1420
+
1421
+ useEffect(() => {
1422
+ loadModels(false)
1423
+ }, [loadModels])
1424
+
1425
+ const list = models ?? EMPTY_LIST
1426
+ const groups = useMemo(() => groupModels(list), [list])
1427
+ // 当前生效的模型:用户选了就用选的(必须在当前列表里),否则跟随 DSH 默认
1428
+ const selected = useMemo(() => {
1429
+ const parsed = parseKey(modelKeyState)
1430
+ if (!parsed) return null
1431
+ return list.find((m) => m.provider === parsed.provider && m.model === parsed.model) || null
1432
+ }, [modelKeyState, list])
1433
+ const effective = selected || defaultRoute
1434
+
1435
+ const canTranslate = source.trim().length > 0 && Boolean(effective) && status !== 'streaming'
1436
+ const hasText = Boolean(source.trim())
1437
+ // 译文栏的语言标签:有结果时显示这次实际译成的语言,没结果时才显示「如果现在翻会译成什么」
1438
+ const target = hasText ? resolveTarget(direction, source) : null
1439
+ const shownTarget = status === 'done' ? usedTarget : target
1440
+
1441
+ const cancel = useCallback(() => {
1442
+ abortRef.current?.abort()
1443
+ }, [])
1444
+
1445
+ const runTranslate = useCallback(async () => {
1446
+ const text = source.trim()
1447
+ if (!text) return
1448
+ const to = resolveTarget(direction, source)
1449
+ const route = selected || defaultRoute
1450
+ if (!route) {
1451
+ setStatus('error')
1452
+ setError(t.noModels)
1453
+ return
1454
+ }
1455
+ abortRef.current?.abort()
1456
+ const controller = new AbortController()
1457
+ abortRef.current = controller
1458
+ const started = performance.now()
1459
+ setStatus('streaming')
1460
+ setError('')
1461
+ setResult('')
1462
+ setTruncated(false)
1463
+ setCancelled(false)
1464
+ setElapsed(0)
1465
+ setUsedRoute({ provider: route.provider, model: route.model, name: route.name || route.model })
1466
+ setUsedTarget(to)
1467
+ setCurrentId(null)
1468
+ let acc = ''
1469
+ try {
1470
+ const done = await streamTranslate({
1471
+ text,
1472
+ target: to,
1473
+ provider: route.provider,
1474
+ model: route.model,
1475
+ signal: controller.signal,
1476
+ onMeta: (meta) => meta?.model && setUsedRoute({ provider: meta.provider, model: meta.model, name: route.name || meta.model }),
1477
+ onDelta: (delta) => {
1478
+ acc += delta
1479
+ setResult((prev) => prev + delta)
1480
+ },
1481
+ })
1482
+ if (typeof done.text === 'string') {
1483
+ acc = done.text
1484
+ setResult(done.text)
1485
+ }
1486
+ const ms = Number(done.elapsedMs) || performance.now() - started
1487
+ setElapsed(ms)
1488
+ setTruncated(Boolean(done.truncated))
1489
+ const used = { provider: done.provider || route.provider, model: done.model || route.model }
1490
+ setUsedRoute({ ...used, name: route.name || used.model })
1491
+ setStatus('done')
1492
+ // 完成的翻译进历史
1493
+ const entry = {
1494
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1495
+ source: text,
1496
+ result: acc,
1497
+ target: to,
1498
+ provider: used.provider,
1499
+ model: used.model,
1500
+ modelName: route.name || used.model,
1501
+ at: Date.now(),
1502
+ elapsedMs: ms,
1503
+ truncated: Boolean(done.truncated),
1504
+ }
1505
+ setHistory((prev) => pushHistory(prev, entry))
1506
+ setCurrentId(entry.id)
1507
+ } catch (err) {
1508
+ if (controller.signal.aborted || err?.cancelled) {
1509
+ if (abortRef.current !== controller) return
1510
+ // 取消后已经收到的那部分留着给用户看,但要明确标成「已取消的部分结果」
1511
+ const partial = acc.trim().length > 0
1512
+ setCancelled(partial)
1513
+ setElapsed(partial ? performance.now() - started : 0)
1514
+ setStatus(partial ? 'done' : 'idle')
1515
+ return
1516
+ }
1517
+ const message = String(err?.message || err)
1518
+ setStatus('error')
1519
+ setError(message === '__stream_broken__' ? t.streamBroken : message)
1520
+ } finally {
1521
+ if (abortRef.current === controller) abortRef.current = null
1522
+ }
1523
+ }, [source, direction, selected, defaultRoute, t])
1524
+
1525
+ const onSourceKey = (event) => {
1526
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
1527
+ event.preventDefault()
1528
+ if (canTranslate) runTranslate()
1529
+ }
1530
+ }
1531
+
1532
+ useEffect(() => {
1533
+ const onKey = (event) => {
1534
+ // 输入法组合中按 Esc 是在取消候选词,不是取消翻译;焦点在历史搜索框时也别响应
1535
+ if (event.key !== 'Escape' || event.isComposing || event.keyCode === 229) return
1536
+ if (event.target?.closest?.('.qt-history-search')) return
1537
+ if (!abortRef.current) return
1538
+ event.preventDefault()
1539
+ abortRef.current.abort()
1540
+ }
1541
+ window.addEventListener('keydown', onKey)
1542
+ return () => window.removeEventListener('keydown', onKey)
1543
+ }, [])
1544
+
1545
+ useEffect(() => () => abortRef.current?.abort(), [])
1546
+
1547
+ const copyResult = async () => {
1548
+ if (!result) return
1549
+ try {
1550
+ await navigator.clipboard.writeText(result)
1551
+ setCopied(true)
1552
+ setCopyFailed(false)
1553
+ setTimeout(() => setCopied(false), 1500)
1554
+ } catch {
1555
+ resultRef.current?.select()
1556
+ setCopyFailed(true)
1557
+ setTimeout(() => setCopyFailed(false), 3000)
1558
+ }
1559
+ }
1560
+
1561
+ const resetOutcome = () => {
1562
+ setStatus('idle')
1563
+ setError('')
1564
+ setElapsed(0)
1565
+ setTruncated(false)
1566
+ setCancelled(false)
1567
+ setUsedRoute(null)
1568
+ setUsedTarget(null)
1569
+ setCurrentId(null)
1570
+ }
1571
+
1572
+ // 真正的互换:原文 ⇄ 译文,方向翻转;再点一次就换回来
1573
+ const swap = () => {
1574
+ if (!result || status === 'streaming') return
1575
+ const s = source
1576
+ const r = result
1577
+ setSource(r)
1578
+ setResult(s)
1579
+ resetOutcome()
1580
+ if (direction === 'en2zh') setDirection('zh2en')
1581
+ else if (direction === 'zh2en') setDirection('en2zh')
1582
+ sourceRef.current?.focus()
1583
+ }
1584
+
1585
+ const clearAll = () => {
1586
+ abortRef.current?.abort()
1587
+ abortRef.current = null
1588
+ setSource('')
1589
+ setResult('')
1590
+ resetOutcome()
1591
+ sourceRef.current?.focus()
1592
+ }
1593
+
1594
+ // 回看一条历史:填回两栏,方向若与之矛盾就顺手改过来;窄屏下顺手收起抽屉,别挡着译文
1595
+ const pickHistory = (e) => {
1596
+ abortRef.current?.abort()
1597
+ abortRef.current = null
1598
+ setSource(e.source)
1599
+ setResult(e.result)
1600
+ setStatus('done')
1601
+ setError('')
1602
+ setElapsed(e.elapsedMs || 0)
1603
+ setTruncated(Boolean(e.truncated))
1604
+ setCancelled(false)
1605
+ setUsedRoute({ provider: e.provider, model: e.model, name: e.modelName })
1606
+ setUsedTarget(e.target)
1607
+ setCurrentId(e.id)
1608
+ if (direction === 'en2zh' && e.target === 'en') setDirection('zh2en')
1609
+ else if (direction === 'zh2en' && e.target === 'zh') setDirection('en2zh')
1610
+ if (window.innerWidth <= 720) setHistoryOpen(false)
1611
+ }
1612
+
1613
+ const deleteHistory = (id) => {
1614
+ setHistory((prev) => prev.filter((e) => e.id !== id))
1615
+ if (id === currentId) setCurrentId(null)
1616
+ }
1617
+
1618
+ const clearHistory = () => {
1619
+ if (!clearArmed) return setClearArmed(true)
1620
+ setHistory([])
1621
+ setHistoryQuery('')
1622
+ setCurrentId(null)
1623
+ setClearArmed(false)
1624
+ }
1625
+
1626
+ // 没有任何可用路由时整个面板换成空状态:区分「真没有模型」「服务商没响应」「列表读取失败」
1627
+ const modelsMissing = !modelsLoading && !defaultRoute && list.length === 0 && (models !== null || Boolean(modelsError))
1628
+ const emptyMessage = modelsError
1629
+ ? `${t.loadModelsFailed}:${modelsError}`
1630
+ : skipped > 0
1631
+ ? t.someSkipped(skipped)
1632
+ : t.noModels
1633
+
1634
+ const streaming = status === 'streaming'
1635
+ const shownArrow = arrowOf(shownTarget || (status === 'done' ? usedTarget : null))
1636
+ const cleanDone = status === 'done' && !cancelled && !truncated && Boolean(result)
1637
+ const today = new Date()
1638
+ const deskDate = `${today.getDate()} ${MONTHS[today.getMonth()]} ${today.getFullYear()}`
1639
+ const noDrag = { WebkitAppRegion: 'no-drag' }
1640
+ const kbdLabel = `${modKey === 'Ctrl' ? 'Ctrl' : '⌘'} ↵`
1641
+
1642
+ const segButton = (value, label) =>
1643
+ h('button', { type: 'button', 'aria-pressed': direction === value ? 'true' : 'false', onClick: () => setDirection(value), disabled: streaming }, label)
1644
+
1645
+ // 硫酸纸右上角:这次翻译的状态
1646
+ const statusChip = () => {
1647
+ if (streaming) return h('span', { className: 'qt-chip qt-live' }, t.receiving)
1648
+ if (status !== 'done') return h('span', { className: 'qt-chip' }, t.standby)
1649
+ if (cancelled) return h('span', { className: 'qt-chip qt-chip-warn', title: t.cancelledPartial }, t.cancelledPartial)
1650
+ if (truncated) return h('span', { className: 'qt-chip qt-chip-warn', title: t.truncated }, t.truncated)
1651
+ return h('span', { className: 'qt-chip qt-chip-ok' }, `${t.done} ${fmtElapsed(elapsed, t)}`)
1652
+ }
1653
+
1654
+ // 方格本右上角:这一页会译成什么(预测值);翻译中显示「锁定」
1655
+ const sourceHint = streaming
1656
+ ? h('span', { className: 'qt-locked' }, `[ ${t.locked} ]`)
1657
+ : hasText
1658
+ ? h('span', null, direction === 'auto' ? `${t.auto} → ${langName(target)}` : `→ ${langName(target)}`)
1659
+ : h('span', null, direction === 'auto' ? `[ ${t.auto} ]` : '')
1660
+
1661
+ // 牛皮纸标签上的大字:手动方向优先;只有「自动」时才看上次实际译成的方向
1662
+ const bigTarget = direction === 'en2zh' ? 'zh' : direction === 'zh2en' ? 'en' : streaming || status === 'done' ? usedTarget || target : target
1663
+ const bigLabel = bigTarget === 'en' ? t.zh2en : bigTarget === 'zh' ? t.en2zh : t.auto
1664
+
1665
+ const narrow = fit.narrow
1666
+ const compStyle = narrow ? undefined : { zoom: fit.scale }
1667
+
1668
+ const note = h(
1669
+ 'section',
1670
+ { className: 'qt-col qt-note', 'aria-label': t.source },
1671
+ h('div', { className: 'qt-paper', 'aria-hidden': 'true' }),
1672
+ h('div', { className: 'qt-rings', 'aria-hidden': 'true' }),
1673
+ h('div', { className: 'qt-holes', 'aria-hidden': 'true' }),
1674
+ h(
1675
+ 'div',
1676
+ { className: 'qt-note-in' },
1677
+ h('div', { className: 'qt-colhead' }, h('span', null, `${t.source} / Source`), sourceHint),
1678
+ h('div', { className: 'qt-dots', 'aria-hidden': 'true' }),
1679
+ h(
1680
+ 'div',
1681
+ { className: 'qt-tawrap' },
1682
+ h('textarea', {
1683
+ ref: sourceRef,
1684
+ className: 'qt-textarea qt-src',
1685
+ value: source,
1686
+ placeholder: t.sourcePlaceholder,
1687
+ spellCheck: false,
1688
+ autoFocus: true,
1689
+ // 流式输出期间锁住原文,避免译完了原文却和译文/历史条目对不上
1690
+ readOnly: streaming,
1691
+ onKeyDown: onSourceKey,
1692
+ onChange: (event) => setSource(event.target.value),
1693
+ onScroll: (event) => flashRuler('src', setSrcThumb, event.currentTarget),
1694
+ }),
1695
+ rulerOf(srcThumb),
1696
+ ),
1697
+ h(
1698
+ 'div',
1699
+ { className: 'qt-note-foot' },
1700
+ h('span', { className: 'qt-meta' }, `${source.length} ${t.chars}`),
1701
+ h('button', { type: 'button', className: 'qt-tapebtn qt-clear', onClick: clearAll, title: t.clearTitle, disabled: streaming || (!source && !result) }, t.clear),
1702
+ narrow ? actions() : null,
1703
+ ),
1704
+ ),
1705
+ narrow ? null : actions(),
1706
+ )
1707
+
1708
+ function actions() {
1709
+ return h('div', { className: 'qt-actions' }, goButton())
1710
+ }
1711
+
1712
+ function goButton() {
1713
+ return streaming
1714
+ ? h('button', { type: 'button', className: 'qt-tapebtn qt-go qt-btn-stop', onClick: cancel, title: 'Esc' }, t.cancel, h('kbd', null, 'Esc'))
1715
+ : h('button', { type: 'button', className: 'qt-tapebtn qt-go qt-btn-primary', disabled: !canTranslate, onClick: runTranslate, title: `${modKey} + Enter` }, t.translate, h('kbd', null, kbdLabel))
1716
+ }
1717
+
1718
+ const swapTape = h(
1719
+ 'button',
1720
+ { type: 'button', className: 'qt-swap', title: t.swap, 'aria-label': t.swap, disabled: !result || streaming, onClick: swap },
1721
+ h('small', { 'aria-hidden': 'true' }, '<>'),
1722
+ h('b', { 'aria-hidden': 'true' }, t.swapShort),
1723
+ )
1724
+
1725
+ const vellum = h(
1726
+ 'section',
1727
+ { className: 'qt-col qt-vellum', 'aria-label': t.result },
1728
+ h('div', { className: 'qt-paper', 'aria-hidden': 'true' }),
1729
+ h(
1730
+ 'div',
1731
+ { className: 'qt-vel-in' },
1732
+ h('div', { className: 'qt-colhead' }, h('span', null, `${t.result} / Translation`), h('span', null, shownArrow), statusChip()),
1733
+ h('div', { className: 'qt-dots', 'aria-hidden': 'true' }),
1734
+ status === 'error' && error
1735
+ ? h(
1736
+ 'div',
1737
+ { className: 'qt-error', role: 'alert' },
1738
+ h('span', { className: 'qt-error-text' }, error),
1739
+ h('button', { type: 'button', className: 'qt-link qt-br', onClick: runTranslate }, t.retry),
1740
+ )
1741
+ : null,
1742
+ h(
1743
+ 'div',
1744
+ { className: 'qt-body' },
1745
+ h('textarea', {
1746
+ ref: resultRef,
1747
+ className: 'qt-textarea qt-res',
1748
+ 'data-lang': shownTarget || 'zh',
1749
+ value: result,
1750
+ placeholder: t.resultPlaceholder,
1751
+ readOnly: true,
1752
+ spellCheck: false,
1753
+ onScroll: (event) => flashRuler('res', setResThumb, event.currentTarget),
1754
+ }),
1755
+ rulerOf(resThumb),
1756
+ !result && !streaming && status !== 'error'
1757
+ ? h('div', { className: 'qt-waiting', 'aria-hidden': 'true' }, h('b', null, t.waiting), h('span', null, t.waitingHint(modKey === 'Ctrl' ? 'Ctrl' : '⌘')))
1758
+ : null,
1759
+ ),
1760
+ h('div', { className: 'qt-dots qt-dots-end', 'aria-hidden': 'true' }),
1761
+ h(
1762
+ 'div',
1763
+ { className: 'qt-stats' },
1764
+ h('div', null, t.statSrc, h('b', null, hasText ? `${source.length}` : '—')),
1765
+ h('div', null, t.statDst, h('b', null, result ? `${result.length}` : '—')),
1766
+ h('div', null, t.statTime, h('b', null, status === 'done' && elapsed ? fmtElapsed(elapsed, t) : '—')),
1767
+ ),
1768
+ h('div', { className: 'qt-bar', 'data-state': streaming ? 'streaming' : result ? 'done' : 'idle', 'aria-hidden': 'true' }),
1769
+ h(
1770
+ 'div',
1771
+ { className: 'qt-vfoot' },
1772
+ h(ModelPicker, {
1773
+ groups,
1774
+ defaultRoute,
1775
+ value: modelKeyState,
1776
+ onChange: setModelKeyState,
1777
+ loading: modelsLoading,
1778
+ disabled: modelsMissing,
1779
+ t,
1780
+ }),
1781
+ cleanDone && !narrow ? h(Signature) : null,
1782
+ h('span', { className: 'qt-spacer' }),
1783
+ h(
1784
+ 'button',
1785
+ {
1786
+ type: 'button',
1787
+ className: `qt-link qt-br ${copyFailed ? 'qt-btn-warn' : ''}`,
1788
+ onClick: copyResult,
1789
+ disabled: !result,
1790
+ title: copyFailed ? t.copyFailedHint.replace('{key}', modKey) : '',
1791
+ },
1792
+ copyFailed ? t.copyFailed : copied ? t.copied : t.copy,
1793
+ ),
1794
+ h(
1795
+ 'button',
1796
+ {
1797
+ type: 'button',
1798
+ className: 'qt-link qt-br qt-share-btn',
1799
+ disabled: !result || streaming,
1800
+ onClick: () =>
1801
+ setShareData({
1802
+ source,
1803
+ result,
1804
+ target: usedTarget || shownTarget || resolveTarget(direction, source),
1805
+ modelName: usedRoute?.name || usedRoute?.model || selected?.name || defaultRoute?.model || '',
1806
+ elapsedMs: status === 'done' ? elapsed : 0,
1807
+ t,
1808
+ }),
1809
+ },
1810
+ t.share,
1811
+ ),
1812
+ ),
1813
+ ),
1814
+ cleanDone ? h(Stamp, { key: currentId || 'stamp', label: t.stamp, arrow: shownArrow.replace(/ >>> /, '>') }) : null,
1815
+ )
1816
+
1817
+ const tag = h(
1818
+ 'div',
1819
+ { className: 'qt-tag' },
1820
+ h('div', { className: 'qt-seg', role: 'group', 'aria-label': t.direction }, segButton('en2zh', t.en2zh), segButton('zh2en', t.zh2en), segButton('auto', t.auto)),
1821
+ h('div', { className: 'qt-tag-big', 'aria-hidden': 'true' }, bigLabel),
1822
+ )
1823
+
1824
+ return h(
1825
+ 'div',
1826
+ { className: 'qt-root', 'data-state': status },
1827
+ h(
1828
+ 'header',
1829
+ { className: 'qt-header', 'data-window-drag': '' },
1830
+ h('span', { className: 'qt-title' }, t.deskTitle),
1831
+ h('span', { className: 'qt-subtitle qt-mono' }, `[ ${t.title} ] DSH Plugin · by ${AUTHOR}`),
1832
+ h('span', { className: 'qt-spacer' }),
1833
+ h(
1834
+ 'button',
1835
+ {
1836
+ type: 'button',
1837
+ className: 'qt-hbtn',
1838
+ 'aria-pressed': historyOpen ? 'true' : 'false',
1839
+ style: noDrag,
1840
+ onClick: () => setHistoryOpen((v) => !v),
1841
+ },
1842
+ t.history,
1843
+ h('span', { className: 'qt-badge' }, `${history.length}`),
1844
+ ),
1845
+ h(
1846
+ 'button',
1847
+ {
1848
+ type: 'button',
1849
+ className: 'qt-hbtn',
1850
+ title: modelsError || t.refresh,
1851
+ 'aria-label': t.refresh,
1852
+ disabled: modelsLoading,
1853
+ style: noDrag,
1854
+ onClick: () => loadModels(true),
1855
+ },
1856
+ modelsLoading ? t.refreshing : t.refresh,
1857
+ ),
1858
+ ),
1859
+ h(
1860
+ 'div',
1861
+ { ref: boardRef, className: `qt-board ${narrow ? 'is-narrow' : ''}` },
1862
+ modelsMissing
1863
+ ? h(
1864
+ 'div',
1865
+ { className: 'qt-empty-card' },
1866
+ h('div', { className: 'qt-paper', 'aria-hidden': 'true' }),
1867
+ h('b', null, t.noModelsTitle),
1868
+ h('p', null, emptyMessage),
1869
+ h('button', { type: 'button', className: 'qt-tapebtn qt-go qt-btn-primary', onClick: () => loadModels(true), disabled: modelsLoading }, t.noModelsRefresh),
1870
+ )
1871
+ : h(
1872
+ 'div',
1873
+ { className: `qt-comp ${narrow ? 'is-narrow' : ''}`, style: compStyle },
1874
+ h('span', { className: 'qt-deco-date', 'aria-hidden': 'true' }, deskDate),
1875
+ h(
1876
+ 'span',
1877
+ { className: 'qt-deco-side', 'aria-hidden': 'true' },
1878
+ 'DSH-QT / V0.3',
1879
+ h('br'),
1880
+ shownArrow,
1881
+ modelsError ? h('br') : null,
1882
+ modelsError ? t.loadModelsFailed : skipped > 0 ? t.someSkipped(skipped) : null,
1883
+ ),
1884
+ note,
1885
+ h('span', { className: 'qt-tape qt-tape-a', 'aria-hidden': 'true' }),
1886
+ h('span', { className: 'qt-tape qt-tape-b', 'aria-hidden': 'true' }),
1887
+ vellum,
1888
+ swapTape,
1889
+ narrow ? tag : null,
1890
+ historyOpen && narrow ? h('div', { className: 'qt-backdrop', onClick: () => setHistoryOpen(false), 'aria-hidden': 'true' }) : null,
1891
+ historyOpen
1892
+ ? h(HistoryPanel, {
1893
+ history,
1894
+ currentId,
1895
+ query: historyQuery,
1896
+ onQuery: setHistoryQuery,
1897
+ onPick: pickHistory,
1898
+ onDelete: deleteHistory,
1899
+ onClear: clearHistory,
1900
+ clearArmed,
1901
+ t,
1902
+ lang,
1903
+ })
1904
+ : null,
1905
+ ),
1906
+ !narrow && !modelsMissing ? h('div', { className: 'qt-tagwrap', style: { zoom: fit.scale } }, tag) : null,
1907
+ ),
1908
+ shareData ? h(ShareSheet, { data: shareData, t, onClose: () => setShareData(null) }) : null,
1909
+ )
1910
+ }
1911
+
1912
+ function SidebarIcon({ size }) {
1913
+ return h(TranslateIcon, { size: size || 18 })
1914
+ }
1915
+
1916
+ /* ============================== 入口 ================================ */
1917
+
1918
+ function apply(ctx) {
1919
+ ensureStyle()
1920
+
1921
+ // 语言跟随 DSH:有 locale 服务就用它,没有就跟随浏览器
1922
+ ctx.inject(['locale'], (c) => {
1923
+ const push = () => langStore.set(String(c.locale.getSnapshot()?.active || '').slice(0, 2).toLowerCase())
1924
+ push()
1925
+ c.on('locale/change', push)
1926
+ })
1927
+
1928
+ ctx.slots.inject('sidebar.panellist', () =>
1929
+ ctx.slots.register(
1930
+ { name: 'sidebar.panellist', id: PANEL, order: 7, label: () => STR[langStore.get()]?.title || STR.en.title },
1931
+ SidebarIcon,
1932
+ ),
1933
+ )
1934
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL }, TranslatePanel))
1935
+ }
1936
+
1937
+ return { apply, inject: ['slots'] }
1938
+ },
1939
+ })