transproof-dsh-plugin 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,410 @@
1
+ /* ═══════════ 设置页 ═══════════ */
2
+ function fillCfg(){
3
+ // 比对时双向去掉尾部 /(Gemini 等以 / 结尾的端点保存时会被 btn-save 剥掉,不归一化会误判成自定义)
4
+ const nb = String(CFG.baseUrl || '').replace(/\/+$/, '');
5
+ const p = PROVIDERS.find(x => x.url.replace(/\/+$/, '') === nb && x.model === CFG.model);
6
+ if(p) $('#provider').value = p.url + '|' + p.model + '|' + p.label; else $('#provider').value = 'custom';
7
+ $('#baseUrl').value = CFG.baseUrl || '';
8
+ $('#model').value = CFG.model || '';
9
+ $('#apiKey').value = CFG.apiKey || '';
10
+ $('#maxTok').value = CFG.maxTok;
11
+ $('#maxInChars').value = CFG.maxInChars || 80000;
12
+ $('#temp').value = CFG.temp;
13
+ $('#timeout').value = CFG.timeout;
14
+ $('#webhook').value = CFG.webhook || '';
15
+ $('#keyWarn').style.display = CFG.apiKey ? 'none' : 'block';
16
+ updateDot();
17
+ }
18
+ const PROVIDERS = [
19
+ /* 国内主流(可直连)——base URL 均为官方 OpenAI 兼容端点,模型名可手改 */
20
+ {g:'国内主流', url:'https://api.deepseek.com', model:'deepseek-chat', label:'DeepSeek 官方 · deepseek-chat(推荐)'},
21
+ {g:'国内主流', url:'https://api.deepseek.com', model:'deepseek-reasoner', label:'DeepSeek-R1 推理(慢但更细)'},
22
+ {g:'国内主流', url:'https://api.xiaomimimo.com/v1', model:'mimo-v2.6-flash', label:'小米 MiMo · mimo-v2.6-flash'},
23
+ {g:'国内主流', url:'https://api.xiaomimimo.com/v1', model:'mimo-v2.6-pro', label:'小米 MiMo Pro · mimo-v2.6-pro'},
24
+ {g:'国内主流', url:'https://dashscope.aliyuncs.com/compatible-mode/v1', model:'qwen-plus', label:'通义千问 Qwen-Plus(阿里云)'},
25
+ {g:'国内主流', url:'https://dashscope.aliyuncs.com/compatible-mode/v1', model:'qwen-max', label:'通义千问 Qwen-Max(阿里云)'},
26
+ {g:'国内主流', url:'https://open.bigmodel.cn/api/paas/v4', model:'glm-4-plus', label:'智谱 GLM-4-Plus'},
27
+ {g:'国内主流', url:'https://api.moonshot.cn/v1', model:'moonshot-v1-32k', label:'Kimi 月之暗面 32K'},
28
+ {g:'国内主流', url:'https://ark.cn-beijing.volces.com/api/v3', model:'doubao-pro-32k', label:'火山方舟 豆包'},
29
+ {g:'国内主流', url:'https://qianfan.baidubce.com/v2', model:'ernie-4.0-turbo-8k', label:'百度千帆 ERNIE 4.0'},
30
+ {g:'国内主流', url:'https://api.hunyuan.cloud.tencent.com/v1', model:'hunyuan-turbos-latest', label:'腾讯混元 Turbos'},
31
+ {g:'国内主流', url:'https://api.siliconflow.cn/v1', model:'deepseek-ai/DeepSeek-V3', label:'硅基流动 · DeepSeek-V3'},
32
+ {g:'国内主流', url:'https://api.minimax.chat/v1', model:'MiniMax-Text-01', label:'MiniMax · Text-01'},
33
+ {g:'国内主流', url:'https://api.stepfun.com/v1', model:'step-2-16k', label:'阶跃星辰 Step-2'},
34
+ /* 海外主流(需可访问外网) */
35
+ {g:'海外主流(需外网)', url:'https://api.openai.com/v1', model:'gpt-4o', label:'OpenAI · gpt-4o'},
36
+ {g:'海外主流(需外网)', url:'https://api.openai.com/v1', model:'gpt-4.1', label:'OpenAI · gpt-4.1'},
37
+ {g:'海外主流(需外网)', url:'https://api.anthropic.com/v1', model:'claude-sonnet-4-5', label:'Anthropic · Claude Sonnet 4.5'},
38
+ {g:'海外主流(需外网)', url:'https://generativelanguage.googleapis.com/v1beta/openai/', model:'gemini-2.5-flash', label:'Google · Gemini 2.5 Flash'},
39
+ {g:'海外主流(需外网)', url:'https://generativelanguage.googleapis.com/v1beta/openai/', model:'gemini-2.5-pro', label:'Google · Gemini 2.5 Pro'},
40
+ {g:'海外主流(需外网)', url:'https://api.x.ai/v1', model:'grok-4', label:'xAI · Grok-4'},
41
+ {g:'海外主流(需外网)', url:'https://api.mistral.ai/v1', model:'mistral-large-latest', label:'Mistral Large'},
42
+ {g:'海外主流(需外网)', url:'https://api.groq.com/openai/v1', model:'llama-3.3-70b-versatile', label:'Groq · Llama-3.3-70B(快)'},
43
+ /* 聚合与本地 */
44
+ {g:'聚合 / 本地', url:'https://openrouter.ai/api/v1', model:'deepseek/deepseek-chat', label:'OpenRouter(一个 Key 用各家)'},
45
+ {g:'聚合 / 本地', url:'http://localhost:11434/v1', model:'qwen3:8b', label:'Ollama 本地(Key 随意填)'}
46
+ ];
47
+ /* v4.23.0:下拉按 PROVIDERS 分组动态生成,末尾固定「自定义」项。
48
+ custom 的 value 必须是字面 'custom'——4.22.0 前是 'custom|custom|…',导致
49
+ onchange 的 v==='custom' 永假(选自定义会把接口地址/模型名覆盖成字面 custom)、
50
+ fillCfg 的回显匹配也落空,本次一并修掉。 */
51
+ function renderProviderOptions(){
52
+ const sel = $('#provider'); if(!sel) return;
53
+ sel.innerHTML = '';
54
+ let og = null, lastG = '';
55
+ for(const p of PROVIDERS){
56
+ if(p.g !== lastG){ og = document.createElement('optgroup'); og.label = p.g; sel.appendChild(og); lastG = p.g; }
57
+ const o = document.createElement('option');
58
+ o.value = p.url + '|' + p.model + '|' + p.label;
59
+ o.textContent = p.label;
60
+ og.appendChild(o);
61
+ }
62
+ const oc = document.createElement('option');
63
+ oc.value = 'custom'; oc.textContent = '自定义 · OpenAI 兼容接口';
64
+ sel.appendChild(oc);
65
+ }
66
+ renderProviderOptions();
67
+ function updateDot(){
68
+ const ok = CFG.apiKey && CFG.baseUrl && CFG.model;
69
+ const dot = $('#apiDot'), txt = $('#apiTxt');
70
+ dot.className = 'dot' + (ok ? ' on' : '');
71
+ txt.textContent = ok ? (CFG.model || '已配置') : '未配置';
72
+ }
73
+ $('#provider').onchange = e => {
74
+ const v = e.target.value;
75
+ if(v === 'custom') return;
76
+ const [url, model] = v.split('|');
77
+ $('#baseUrl').value = url; $('#model').value = model;
78
+ };
79
+ $('#btn-save').onclick = () => {
80
+ CFG = {
81
+ baseUrl: $('#baseUrl').value.trim().replace(/\/+$/, ''),
82
+ model: $('#model').value.trim(),
83
+ apiKey: $('#apiKey').value.trim(),
84
+ maxTok: +$('#maxTok').value || 16000,
85
+ maxInChars: +$('#maxInChars').value || 80000,
86
+ temp: +$('#temp').value || 0.3,
87
+ timeout: +$('#timeout').value || 180,
88
+ webhook: $('#webhook').value.trim()
89
+ };
90
+ save(LS.cfg, CFG);
91
+ toast('已保存', 'ok');
92
+ };
93
+ // tokens 快速预设
94
+ document.querySelectorAll('[data-preset-tok]').forEach(b => b.onclick = () => { $('#maxTok').value = b.dataset.presetTok; CFG.maxTok = +b.dataset.presetTok; save(LS.cfg, CFG); toast('已设 ' + b.dataset.presetTok + ' tokens(已自动保存)', 'ok'); });
95
+ // 原文最大字数预设
96
+ document.querySelectorAll('[data-preset-chars]').forEach(b => b.onclick = () => { $('#maxInChars').value = b.dataset.presetChars; CFG.maxInChars = +b.dataset.presetChars; save(LS.cfg, CFG); toast('原文上限已设 ' + b.dataset.presetChars + ' 字(已自动保存)', 'ok'); });
97
+ $('#btn-test').onclick = async () => {
98
+ const url = $('#baseUrl').value.trim(), key = $('#apiKey').value.trim(), model = $('#model').value.trim();
99
+ const m = $('#testMsg');
100
+ if(!url || !key || !model){ m.textContent = '请先填写完整'; m.style.color = 'var(--warn)'; return; }
101
+ m.innerHTML = '<span class="spin"></span> 测试中……'; m.style.color = 'var(--tx2)';
102
+ try{
103
+ const r = await fetch(url.replace(/\/+$/,'') + '/chat/completions', {
104
+ method:'POST',
105
+ headers:{'Content-Type':'application/json','Authorization':'Bearer ' + key},
106
+ body: JSON.stringify({ model, messages:[{role:'user',content:'回复两个字:正常'}], max_tokens:16, stream:false })
107
+ });
108
+ if(!r.ok){ const t = await r.text(); throw new Error('HTTP ' + r.status + ' — ' + t.slice(0,180)); }
109
+ const j = await r.json();
110
+ const txt = j?.choices?.[0]?.message?.content || '(空)';
111
+ m.textContent = '✓ 连接成功 · 模型回复:' + txt.trim().slice(0,30);
112
+ m.style.color = 'var(--ok)';
113
+ CFG = { baseUrl:url.replace(/\/+$/,''), model, apiKey:key, maxTok:+$('#maxTok').value||8000, maxInChars:+$('#maxInChars').value||80000, temp:+$('#temp').value||0.3, timeout:+$('#timeout').value||180, webhook:$('#webhook').value.trim() };
114
+ save(LS.cfg, CFG); updateDot(); $('#keyWarn').style.display='none';
115
+ }catch(err){
116
+ m.textContent = '✗ 失败:' + err.message;
117
+ m.style.color = 'var(--err)';
118
+ }
119
+ };
120
+
121
+ /* ═══════════ 术语库 ═══════════ */
122
+ const CATS = ['哲学','社会学','人类学','文化研究','电影学','历史学','政治经济学','文学理论','心理学','法学','传播学','自然科学','人名','地名','机构','其他'];
123
+ function renderTerms(){
124
+ const q = ($('#termSearch')?.value || '').toLowerCase().trim();
125
+ const cat = $('#termCat')?.value || '';
126
+ const tb = $('#termTable tbody');
127
+ const list = TERMS.filter(t =>
128
+ (!q || (t.src+' '+t.dst+' '+(t.note||'')).toLowerCase().includes(q)) &&
129
+ (!cat || t.cat === cat)
130
+ );
131
+ $('#termCount').textContent = TERMS.length + ' 条' + (list.length !== TERMS.length ? '(筛选出 ' + list.length + ')' : '');
132
+ const w = $('#termWarn'); if(w) w.style.display = TERMS.length ? 'none' : 'inline';
133
+ if(!list.length){
134
+ tb.innerHTML = '<tr><td colspan="5"><div class="empty">' + (TERMS.length ? '没有匹配的术语' : '术语库还是空的 — 在上方批量粘贴,或点「+ 新增一行」') + '</div></td></tr>';
135
+ return;
136
+ }
137
+ tb.innerHTML = list.map(t => {
138
+ const i = TERMS.indexOf(t);
139
+ return '<tr data-i="' + i + '">' +
140
+ '<td><input value="' + esc(t.src) + '" data-k="src"></td>' +
141
+ '<td><input value="' + esc(t.dst) + '" data-k="dst"></td>' +
142
+ '<td><select data-k="cat">' + CATS.map(c => '<option' + (c===t.cat?' selected':'') + '>' + c + '</option>').join('') + '</select></td>' +
143
+ '<td><input value="' + esc(t.note||'') + '" data-k="note"></td>' +
144
+ '<td style="white-space:nowrap"><button class="btn gray sm" data-verify title="AI 核查这条收录是否正确(v4.26.0)">🤖 核查</button> <button class="btn gray sm" data-del>删除</button></td></tr>';
145
+ }).join('');
146
+ tb.querySelectorAll('tr').forEach(tr => {
147
+ const i = +tr.dataset.i;
148
+ tr.querySelectorAll('[data-k]').forEach(el => {
149
+ el.onchange = () => { TERMS[i][el.dataset.k] = el.value.trim(); save(LS.terms, TERMS); };
150
+ });
151
+ tr.querySelector('[data-del]').onclick = () => {
152
+ TERMS.splice(i, 1); save(LS.terms, TERMS); renderTerms();
153
+ };
154
+ tr.querySelector('[data-verify]').onclick = async () => {
155
+ const t = TERMS[+tr.dataset.i]; if(!t) return;
156
+ const items = [{ src: t.src, dst: t.dst, extra: t.cat || '' }];
157
+ const vs = await verifyEntries(items, tr.querySelector('[data-verify]'));
158
+ if(!vs) return;
159
+ showVerifyResults(items, vs, { onAdopt: (k, v) => {
160
+ if(!v.suggest) return false;
161
+ t.dst = v.suggest; save(LS.terms, TERMS); renderTerms();
162
+ toast('已把「' + t.src + '」的译法改为建议值');
163
+ return true;
164
+ }});
165
+ };
166
+ });
167
+ }
168
+ function initTermCat(){
169
+ $('#termCat').innerHTML = '<option value="">全部类别</option>' + CATS.map(c => '<option>' + c + '</option>').join('');
170
+ }
171
+ $('#termSearch').oninput = renderTerms;
172
+ $('#termCat').onchange = renderTerms;
173
+ $('#btn-term-new').onclick = () => {
174
+ TERMS.unshift({ src:'', dst:'', cat:'其他', note:'' });
175
+ save(LS.terms, TERMS);
176
+ $('#termSearch').value = ''; $('#termCat').value = '';
177
+ renderTerms();
178
+ const f = $('#termTable tbody tr:first-child input'); if(f) f.focus();
179
+ };
180
+ $('#btn-term-add').onclick = () => {
181
+ const lines = $('#termPaste').value.split('\n').map(s => s.trim()).filter(Boolean);
182
+ if(!lines.length){ toast('请先粘贴内容'); return; }
183
+ let n = 0;
184
+ lines.forEach(line => {
185
+ const p = line.split(/[|\t]/).map(s => s.trim());
186
+ if(!p[0] || !p[1]) return;
187
+ const ex = TERMS.find(t => t.src.toLowerCase() === p[0].toLowerCase());
188
+ if(ex){ ex.dst = p[1]; if(p[2]) ex.note = p[2]; }
189
+ else TERMS.push({ src:p[0], dst:p[1], cat:p[3] || guessCat(p[0], p[2] || ''), note:p[2] || '' });
190
+ n++;
191
+ });
192
+ save(LS.terms, TERMS); $('#termPaste').value = ''; renderTerms();
193
+ toast('已导入 ' + n + ' 条术语');
194
+ };
195
+ function guessCat(src, note){
196
+ const s = (src + ' ' + note).toLowerCase();
197
+ if(/hegemony|capital|class|marx|labour|labor|state|ideolog|neoliber/.test(s)) return '政治经济学';
198
+ if(/ritual|kinship|ethnograph|tribe|totem/.test(s)) return '人类学';
199
+ if(/cinema|film|mise|montage|shot|auteur/.test(s)) return '电影学';
200
+ if(/discourse|narrative|semiot|deconstruct|textual/.test(s)) return '文化研究';
201
+ if(/unconscious|cognit|psycho|freud|lacan/.test(s)) return '心理学';
202
+ if(/dynasty|empire|colonial|histori|archiv/.test(s)) return '历史学';
203
+ return '其他';
204
+ }
205
+ $('#btn-term-exp').onclick = () => dl('术语库_' + today() + '.json', JSON.stringify(TERMS, null, 2), 'application/json');
206
+ $('#btn-term-csv').onclick = () => {
207
+ const rows = [['原文','中文译名','类别','备注']].concat(TERMS.map(t => [t.src, t.dst, t.cat||'', t.note||'']));
208
+ const csv = '\ufeff' + rows.map(r => r.map(c => '"' + String(c).replace(/"/g,'""') + '"').join(',')).join('\n');
209
+ dl('术语库_' + today() + '.csv', csv, 'text/csv');
210
+ };
211
+ $('#btn-term-imp').onclick = () => $('#termFile').click();
212
+ $('#termFile').onchange = e => {
213
+ const f = e.target.files[0]; if(!f) return;
214
+ const rd = new FileReader();
215
+ rd.onload = () => {
216
+ try{
217
+ const txt = rd.result;
218
+ let add = [];
219
+ if(f.name.endsWith('.json')){
220
+ const j = JSON.parse(txt);
221
+ add = (Array.isArray(j) ? j : j.terms || []).map(t => ({ src:t.src||t.source||'', dst:t.dst||t.target||'', cat:t.cat||'其他', note:t.note||'' }));
222
+ }else{
223
+ add = csvParse(txt).slice(txt.trim().split('\n')[0].includes('原文') ? 1 : 0).map(c => ({ src:c[0]||'', dst:c[1]||'', cat:c[2]||'其他', note:c[3]||'' }));
224
+ }
225
+ add = add.filter(t => t.src && t.dst);
226
+ add.forEach(t => {
227
+ const ex = TERMS.find(x => x.src.toLowerCase() === t.src.toLowerCase());
228
+ if(ex){ ex.dst = t.dst; ex.note = t.note || ex.note; } else TERMS.push(t);
229
+ });
230
+ save(LS.terms, TERMS); renderTerms();
231
+ toast('已导入 ' + add.length + ' 条');
232
+ }catch(err){ toast('导入失败:' + err.message, 'e'); }
233
+ };
234
+ rd.readAsText(f, 'UTF-8');
235
+ e.target.value = '';
236
+ };
237
+ $('#btn-term-scan').onclick = () => $('#termScanFile').click();
238
+ $('#termScanFile').onchange = async e => {
239
+ const f = e.target.files[0]; e.target.value = '';
240
+ if(!f) return;
241
+ const btn = $('#btn-term-scan');
242
+ btn.disabled = true; btn.textContent = '🤖 扫描中…';
243
+ try{
244
+ const r = await smartScanFile(f, (msg) => { btn.textContent = '🤖 ' + msg; });
245
+ btn.disabled = false; btn.textContent = '🤖 智能扫描';
246
+ if(r && r.total){
247
+ toast('智能扫描完成:抽取 ' + r.total + ' 条术语 → 集合。已放入「专有译词库」,可到那里审核后点「⚡ 同步到术语库」一键锁定。');
248
+ }
249
+ }catch(err){
250
+ btn.disabled = false; btn.textContent = '🤖 智能扫描';
251
+ toast('智能扫描失败:' + err.message, 'e');
252
+ }
253
+ };
254
+ $('#btn-term-clr').onclick = () => {
255
+ if(!TERMS.length){ toast('术语库已是空的'); return; }
256
+ if(confirm('确定清空全部 ' + TERMS.length + ' 条术语?建议先导出备份。')){
257
+ TERMS = []; save(LS.terms, TERMS); renderTerms(); toast('已清空');
258
+ }
259
+ };
260
+ $('#btn-pref-save').onclick = () => {
261
+ PREFS = $('#prefs').value.trim(); save(LS.prefs, PREFS);
262
+ $('#prefSaved').textContent = '✓ 已保存 · ' + new Date().toLocaleTimeString('zh-CN');
263
+ };
264
+
265
+ /* ═══════════ 团队云端同步(3.2) ═══════════ */
266
+ $('#cloudUrl').value = CFG.cloudUrl || '';
267
+ $('#btn-cloud-pull').onclick = async () => {
268
+ const url = $('#cloudUrl').value.trim();
269
+ const msg = $('#cloudMsg');
270
+ if(!url){ msg.innerHTML = '<span style="color:var(--err)">请先粘贴共享词库网址(见下方发布教程)</span>'; return; }
271
+ if(!/^https?:\/\//i.test(url)){ msg.innerHTML = '<span style="color:var(--err)">网址需要以 http:// 或 https:// 开头</span>'; return; }
272
+ CFG.cloudUrl = url; save(LS.cfg, CFG);
273
+ msg.innerHTML = '<span style="color:var(--tx3)">⏳ 正在拉取云端词库……</span>';
274
+ try{
275
+ const res = await fetch(url, { cache: 'no-store' });
276
+ if(!res.ok) throw new Error('网址返回了错误状态 HTTP ' + res.status + (res.status === 404 ? '(链接失效?重新复制一次 Raw 网址)' : ''));
277
+ const txt = await res.text();
278
+ let j;
279
+ try{ j = JSON.parse(txt); }
280
+ catch(_){ throw new Error('返回内容不是 JSON——请确认粘贴的是「Raw」网址:浏览器打开它应该显示一串纯文本词条,而不是网页界面'); }
281
+ const arr = Array.isArray(j) ? j : (Array.isArray(j.terms) ? j.terms : null);
282
+ if(!arr) throw new Error('格式不认识:需要「导出 JSON」得到的词库数组');
283
+ const add = arr.map(t => {
284
+ if(t && (t.src || t.source)) return { src: t.src || t.source || '', dst: t.dst || t.target || '', cat: t.cat || '其他', note: t.note || '' };
285
+ if(t && (t.zh || t.foreign)) return { src: t.foreign || t.zh || '', dst: t.zh || '', cat: t.type || '其他', note: [t.note, (t.tags||[]).join('、')].filter(Boolean).join(';') };
286
+ return null;
287
+ }).filter(t => t && t.src && t.dst);
288
+ if(!add.length) throw new Error('云端词库是空的,或不是本工具导出的格式');
289
+ let added = 0, updated = 0;
290
+ add.forEach(t => {
291
+ const ex = TERMS.find(x => x.src.toLowerCase() === t.src.toLowerCase());
292
+ if(ex){ if(ex.dst !== t.dst){ ex.dst = t.dst; updated++; } ex.note = t.note || ex.note; }
293
+ else { TERMS.push(t); added++; }
294
+ });
295
+ save(LS.terms, TERMS); renderTerms();
296
+ msg.innerHTML = '<span style="color:var(--ok)">✓ 同步完成(' + new Date().toLocaleTimeString('zh-CN') + '):云端 ' + add.length + ' 条 → 新增 ' + added + '、更新 ' + updated + '、与本地一致 ' + (add.length - added - updated) + '</span>';
297
+ toast('云端词库已同步');
298
+ }catch(err){
299
+ const net = /Failed to fetch|NetworkError|Load failed/i.test(err.message);
300
+ msg.innerHTML = '<span style="color:var(--err)">✗ 拉取失败:' + esc(net ? '网络不通,或该网址不允许浏览器跨域读取。建议:① 检查网络后重试;② 确认复制的是 GitHub Gist 的 Raw 网址;③ 仍不行就把 JSON 放进 GitHub 仓库,改用 jsDelivr 网址(cdn.jsdelivr.net/gh/用户名/仓库名@main/文件名.json)' : err.message) + '</span>';
301
+ }
302
+ };
303
+
304
+ /* ═══════════ 数据管理 ═══════════ */
305
+ function today(){ return new Date().toISOString().slice(0,10); }
306
+ function dl(name, content, type){
307
+ const b = new Blob([content], { type: type + ';charset=utf-8' });
308
+ const a = document.createElement('a');
309
+ a.href = URL.createObjectURL(b); a.download = name; a.click();
310
+ setTimeout(() => URL.revokeObjectURL(a.href), 3000);
311
+ }
312
+ // 全部持久化 key(v2 备份/恢复/清除/统计的单一来源)
313
+ const ALL_KEYS = ['tp.cfg','tp.terms','tp.prefs','tp.history','tp.memory','tp.project','tp.prompts','tp.gloss','tp.task','tp.stage','tp.theme','tp.accent','tp.splash','tp.fb.log'];
314
+ $('#btn-backup').onclick = () => {
315
+ // v2:完整备份所有本地数据(12 个 key),用于原封不动迁移到其他设备/平台
316
+ const data = {};
317
+ ALL_KEYS.forEach(k => { try{ const v = localStorage.getItem(k); if(v != null) data[k] = v; }catch(e){} });
318
+ dl('译校助手完整备份_' + today() + '.json', JSON.stringify({ v:2, date:new Date().toISOString(), data }, null, 2), 'application/json');
319
+ };
320
+ $('#btn-restore').onclick = () => $('#bakFile').click();
321
+ $('#bakFile').onchange = e => {
322
+ const f = e.target.files[0]; if(!f) return;
323
+ const rd = new FileReader();
324
+ rd.onload = () => {
325
+ try{
326
+ const j = JSON.parse(rd.result);
327
+ if(j.data && typeof j.data === 'object'){
328
+ // v2:完整恢复所有本地数据,然后刷新让全部模块重新加载
329
+ Object.entries(j.data).forEach(([k, v]) => { if(v != null && ALL_KEYS.includes(k)){ try{ localStorage.setItem(k, v); }catch(_){} } });
330
+ toast('完整备份已恢复,即将刷新…');
331
+ setTimeout(() => location.reload(), 600);
332
+ } else {
333
+ // v1 兼容:旧的 cfg/terms/prefs
334
+ if(j.cfg) { CFG = Object.assign({}, DEF_CFG, j.cfg); save(LS.cfg, CFG); }
335
+ if(Array.isArray(j.terms)) { TERMS = j.terms; save(LS.terms, TERMS); }
336
+ if(typeof j.prefs === 'string') { PREFS = j.prefs; save(LS.prefs, PREFS); $('#prefs').value = PREFS; }
337
+ fillCfg(); renderTerms(); renderDataStat();
338
+ toast('备份已恢复');
339
+ }
340
+ }catch(err){ toast('恢复失败:' + err.message, 'e'); }
341
+ };
342
+ rd.readAsText(f, 'UTF-8'); e.target.value = '';
343
+ };
344
+ $('#btn-wipe').onclick = () => {
345
+ if(!confirm('将清除 API Key、术语库、偏好、历史、翻译记忆、项目进度等全部本地数据。此操作不可撤销。确定继续?')) return;
346
+ ALL_KEYS.forEach(k => localStorage.removeItem(k));
347
+ // 刷新让所有模块从(已清空的)localStorage 重新初始化,避免内存残留数据被静默写回
348
+ toast('已清除全部数据,即将刷新…');
349
+ setTimeout(() => location.reload(), 600);
350
+ };
351
+ function renderDataStat(){
352
+ const size = ALL_KEYS.reduce((n,k) => n + (localStorage.getItem(k)||'').length, 0);
353
+ $('#dataStat').textContent = '术语 ' + TERMS.length + ' 条 · 偏好 ' + PREFS.length + ' 字 · 占用约 ' + (size/1024).toFixed(1) + ' KB';
354
+ renderHistory();
355
+ }
356
+ function renderHistory(){
357
+ const h = load(LS.history, []);
358
+ const tb = $('#histTable tbody');
359
+ if(!tb) return;
360
+ $('#histCount').textContent = h.length ? ('共 ' + h.length + ' 条记录') : '暂无记录';
361
+ if(!h.length){
362
+ tb.innerHTML = '<tr><td colspan="3"><div class="empty">还没有校对记录</div></td></tr>';
363
+ return;
364
+ }
365
+ tb.innerHTML = h.map((r, i) => {
366
+ const d = new Date(r.t);
367
+ const ts = d.toLocaleString('zh-CN', { month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit' });
368
+ return '<tr data-i="' + i + '">' +
369
+ '<td style="color:var(--tx3);font-size:12px;white-space:nowrap">' + esc(ts) + (r.ext ? ' <span class="tag p">延伸</span>' : '') + '</td>' +
370
+ '<td style="font-size:12.5px;color:var(--tx2)">' + esc((r.title||'').slice(0,60)) + '…</td>' +
371
+ '<td style="white-space:nowrap"><button class="btn gray sm" data-open>查看</button> <button class="btn gray sm" data-del>删除</button></td></tr>';
372
+ }).join('');
373
+ tb.querySelectorAll('tr').forEach(tr => {
374
+ const i = +tr.dataset.i;
375
+ tr.querySelector('[data-open]').onclick = () => {
376
+ const r = load(LS.history, [])[i];
377
+ if(!r) return;
378
+ LAST_OUT = r.out;
379
+ modal('历史记录 · ' + new Date(r.t).toLocaleString('zh-CN'), [
380
+ '<p style="font-size:12px;color:var(--tx3)">' + (r.ext ? '模式:术语/争议点延伸分析' : '模式:完整校对') + '</p>',
381
+ '<div style="background:var(--bg);border:1px solid var(--bd);border-radius:6px;padding:14px;max-height:52vh;overflow-y:auto">' + md(r.out) + '</div>',
382
+ '<p style="font-size:12px;color:var(--tx3);margin-top:12px">已载入到剪贴板来源,关闭后可直接点工作台页的「复制结果」或「转公众号格式」。</p>'
383
+ ].join(''));
384
+ };
385
+ tr.querySelector('[data-del]').onclick = () => {
386
+ const h2 = load(LS.history, []); h2.splice(i, 1); save(LS.history, h2); renderHistory();
387
+ };
388
+ });
389
+ }
390
+ $('#btn-hist-clr').onclick = () => {
391
+ if(!load(LS.history, []).length){ toast('历史已是空的'); return; }
392
+ if(confirm('确定清空全部校对历史?')){ save(LS.history, []); renderHistory(); toast('已清空'); }
393
+ };
394
+
395
+ /* ═══════════ 示例 ═══════════ */
396
+ const SAMPLE = {
397
+ src:`It is argued that the modern subject is constituted not prior to, but through, the very disciplinary apparatuses that claim merely to describe it. Foucault's account of the panopticon is instructive here: the inmate internalises the gaze to the point where surveillance becomes superfluous. What is at stake, then, is not simply the extent of coercion, but the manner in which power produces the categories by which we come to recognise ourselves as subjects at all.`,
398
+ dst:`有人认为,现代主体不是在规训机制之前构成的,而是通过这些机制构成的,而这些机制声称只是在描述它。福柯对全景敞视监狱的论述在此很有启发性:囚犯将目光内化到监视变得多余的程度。因此,问题的关键不仅仅是强制的程度,而是权力如何产生那些我们借以承认自己为主体的范畴。`
399
+ };
400
+ $('#btn-sample').onclick = () => {
401
+ $('#src').value = SAMPLE.src; $('#dst').value = SAMPLE.dst;
402
+ $('#lang').value = '英语'; $('#genre').value = '学术论文';
403
+ toast('已载入示例文本');
404
+ };
405
+ $('#btn-clear').onclick = () => {
406
+ ['src','dst','extra'].forEach(id => $('#' + id).value = '');
407
+ $('#out').innerHTML = ''; $('#stats').style.display = 'none'; LAST_OUT = '';
408
+ // P1:清空文件绑定
409
+ ['src','dst'].forEach(side => { __TP_FILES[side] = null; renderFileBar(side); });
410
+ };