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,774 @@
1
+ /* ═══════════════════════════════════════════════════════════════
2
+ 对外接口层(正式版新增)—— 供自研翻译工具对接,三选一:
3
+ ① URL 参数:index.html?src=原文&dst=译文&lang=英语&autostart=1
4
+ 支持:src dst lang genre tone depth style variant extra
5
+ terms(JSON) prefs options(JSON) autostart
6
+ ② postMessage:你们的页面用 iframe 嵌入本工具后,
7
+ iframe.contentWindow.postMessage({type:'transproof:fill', payload:{...}}, '*')
8
+ 事件:transproof:fill(灌数据)/ transproof:run(开始校对)
9
+ / transproof:stop;回执 transproof:complete / transproof:error
10
+ ③ window.TransProof 全局对象:
11
+ TransProof.fill({...}) / .run() / .runExt() / .stop()
12
+ / .getResult() / .setTerms([...]) / .getTerms() / .version
13
+ 详见《二次开发指南.md》
14
+ ═══════════════════════════════════════════════════════════════ */
15
+ function applyPayload(p){
16
+ if(!p || typeof p !== 'object') return false;
17
+ let touched = false;
18
+ const setVal = (sel, v) => {
19
+ const el = $(sel);
20
+ if(el && v !== undefined && v !== null && v !== ''){ el.value = String(v); touched = true; }
21
+ };
22
+ setVal('#src', p.src); setVal('#dst', p.dst);
23
+ setVal('#lang', p.lang); setVal('#genre', p.genre);
24
+ setVal('#tone', p.tone); setVal('#depth', p.depth);
25
+ setVal('#style', p.style); setVal('#variant', p.variant);
26
+ setVal('#extra', p.extra);
27
+ if(Array.isArray(p.terms) && p.terms.length){
28
+ let n = 0;
29
+ p.terms.forEach(t => {
30
+ if(t && t.src && t.dst){
31
+ const ex = TERMS.find(x => x.src.toLowerCase() === String(t.src).toLowerCase());
32
+ if(ex){ ex.dst = t.dst; if(t.note) ex.note = t.note; }
33
+ else { TERMS.push({ src:t.src, dst:t.dst, cat:t.cat||'其他', note:t.note||'' }); }
34
+ n++;
35
+ }
36
+ });
37
+ if(n){ save(LS.terms, TERMS); renderTerms(); toast('已接收 ' + n + ' 条外部术语'); }
38
+ }
39
+ if(typeof p.prefs === 'string' && p.prefs){ PREFS = p.prefs; save(LS.prefs, PREFS); $('#prefs').value = PREFS; }
40
+ if(p.options && typeof p.options === 'object'){
41
+ const map = {term:'c-term', note:'c-note', ext:'c-ext', format:'c-format', deai:'c-deai', ask:'c-ask', noun:'ts-c-noun'};
42
+ for(const [k,id] of Object.entries(map)){
43
+ if(p.options[k] !== undefined){ const el = $('#'+id); if(el){ el.checked = !!p.options[k]; } }
44
+ }
45
+ }
46
+ if(p.apiKey || p.baseUrl || p.model){
47
+ CFG = Object.assign(CFG, {
48
+ apiKey: p.apiKey || CFG.apiKey,
49
+ baseUrl: (p.baseUrl || CFG.baseUrl).replace(/\/+$/,''),
50
+ model: p.model || CFG.model
51
+ });
52
+ save(LS.cfg, CFG); fillCfg(); updateDot();
53
+ }
54
+ return touched;
55
+ }
56
+ /* ① URL 参数 */
57
+ (function fromURL(){
58
+ const q = new URLSearchParams(location.search);
59
+ const p = {};
60
+ ['src','dst','lang','genre','tone','depth','style','variant','extra','prefs','apiKey','baseUrl','model'].forEach(k => { if(q.get(k)) p[k] = q.get(k); });
61
+ try{
62
+ if(q.get('terms')) p.terms = JSON.parse(q.get('terms'));
63
+ if(q.get('options')) p.options = JSON.parse(q.get('options'));
64
+ }catch(e){}
65
+ const touched = applyPayload(p);
66
+ if(touched) toast('已从链接载入数据');
67
+ if(q.get('autostart') === '1' && q.get('dst')) setTimeout(() => run(false), 400);
68
+ })();
69
+ /* ② postMessage(iframe 嵌入场景) */
70
+ window.addEventListener('message', e => {
71
+ const d = e.data;
72
+ if(!d || !d.type || !String(d.type).startsWith('transproof:')) return;
73
+ const cmd = d.type.slice(11);
74
+ if(cmd === 'fill'){
75
+ applyPayload(d.payload);
76
+ if(d.payload && d.payload.autostart) setTimeout(() => run(false), 300);
77
+ try{ e.source.postMessage({type:'transproof:filled'}, '*'); }catch(_){}
78
+ }else if(cmd === 'run'){
79
+ run(false);
80
+ }else if(cmd === 'runExt'){
81
+ run(true);
82
+ }else if(cmd === 'stop'){
83
+ if(ABORT) ABORT.abort();
84
+ }else if(cmd === 'parseFile'){
85
+ // d.payload = { side:'src'|'dst', file:File|Blob, fileName?:string, b64?:string, mime?:string }
86
+ (async()=>{
87
+ try{
88
+ let file = d.payload.file;
89
+ if(!file && d.payload.b64){
90
+ const bin = atob(d.payload.b64);
91
+ const bytes = new Uint8Array(bin.length);
92
+ for(let i=0;i<bin.length;i++) bytes[i] = bin.charCodeAt(i);
93
+ file = new File([bytes], d.payload.fileName || 'remote.bin', { type: d.payload.mime || 'application/octet-stream' });
94
+ }
95
+ const data = await parseFile(file, d.payload.side || 'src', ()=>{});
96
+ __TP_FILES[d.payload.side || 'src'] = data;
97
+ renderFileBar(d.payload.side || 'src');
98
+ fillFromChapter(d.payload.side || 'src', -1);
99
+ try{ e.source.postMessage({type:'transproof:parsed', payload:{ side:d.payload.side, kind:data.kind, chapters:data.chapters.length }}, '*'); }catch(_){}
100
+ }catch(err){
101
+ try{ e.source.postMessage({type:'transproof:error', detail:{ message:'parseFile: '+err.message }}, '*'); }catch(_){}
102
+ }
103
+ })();
104
+ }else if(cmd === 'setChapter'){
105
+ fillFromChapter(d.payload.side, d.payload.idx);
106
+ }else if(cmd === 'clearFile'){
107
+ const side = d.payload && d.payload.side;
108
+ if(side){ __TP_FILES[side] = null; renderFileBar(side); $('#'+side).value = ''; }
109
+ }
110
+ });
111
+ /* ③ 全局 API */
112
+ window.TransProof = {
113
+ version: APP_VERSION,
114
+ // 3.0 新增:专有译词库接口
115
+ gloss: {
116
+ data: () => JSON.parse(JSON.stringify(GLOSS)),
117
+ importFile: (file) => parseGlossFile(file).then(parsed => glossIngest(parsed)),
118
+ exportFiltered: (fmt) => glossExport(fmt, glossFiltered()),
119
+ syncTerms: () => { $('#btn-g-sync').click(); },
120
+ stats: () => ({
121
+ terms: GLOSS.terms.length,
122
+ sources: GLOSS.sources.length,
123
+ confirmed: GLOSS.terms.filter(t=>t.status==='confirmed').length,
124
+ recommended: GLOSS.terms.filter(t=>t.recommend==='rec').length
125
+ })
126
+ },
127
+ fill: applyPayload,
128
+ run: () => run(false),
129
+ runExt: () => run(true),
130
+ stop: () => { if(ABORT) ABORT.abort(); },
131
+ getResult: () => LAST_OUT,
132
+ setResult: (t) => { LAST_OUT = String(t || ''); $('#out').innerHTML = md(LAST_OUT); saveTask(); },
133
+ isRunning: () => RUNNING,
134
+ setTerms: list => { if(Array.isArray(list)){ TERMS = list.filter(t=>t&&t.src&&t.dst).map(t=>({src:t.src,dst:t.dst,cat:t.cat||'其他',note:t.note||''})); save(LS.terms,TERMS); renderTerms(); } },
135
+ getTerms: () => TERMS.slice(),
136
+ exportTerms: () => JSON.stringify(TERMS, null, 2),
137
+ // P1:文件输入接口
138
+ parseFile: (file, side='src') => parseFile(file, side, ()=>{}),
139
+ getFiles: () => ({ src: __TP_FILES.src && { ...__TP_FILES.src }, dst: __TP_FILES.dst && { ...__TP_FILES.dst } }),
140
+ setChapter: (side, idx) => { fillFromChapter(side, idx); },
141
+ clearFile: (side) => { __TP_FILES[side] = null; renderFileBar(side); $('#'+side).value = ''; },
142
+ // 3.1:文档模式——下载"图片排版保留、仅替换文字"的校对后 Word
143
+ exportDocx: () => exportProofreadDocx(),
144
+ isDocModeReady: () => docModeActive()
145
+ };
146
+
147
+ /* ═══════════ 专有译词库 · UI 渲染与交互 ═══════════ */
148
+ let G_SORT = { key:'', dir:1 };
149
+ let G_SEL = new Set();
150
+
151
+ /* M4(T-012 · v4.32.0):术语权威分级唯一闸门 —— 只有「已批准(confirmed)」词条
152
+ 才允许注入提示词;待审/已拒绝一律不进提示词。所有提示词注入点都必须走这里,
153
+ 杜绝各处重复过滤、漏过滤(此前 02-prompts-reverse 提炼方针就漏了 status 过滤)。 */
154
+ function approvedGloss(){
155
+ return GLOSS.terms.filter(t => t && t.status === 'confirmed' && t.foreign && t.zh);
156
+ }
157
+
158
+ function renderGloss(){
159
+ renderGlossStats();
160
+ renderCollections();
161
+ renderGlossFilters();
162
+ renderGlossTable();
163
+ if(typeof renderGvPanel === 'function') renderGvPanel();
164
+ const has = GLOSS.terms.length > 0;
165
+ $('#btn-g-export').disabled = !has;
166
+ $('#btn-g-sync').disabled = !has;
167
+ $('#g-empty').style.display = has ? 'none' : '';
168
+ $('#g-filter-card').style.display = has ? '' : 'none';
169
+ }
170
+ function renderCollections(){
171
+ const box = $('#g-collections');
172
+ if(!box) return;
173
+ const cols = GLOSS.collections || [];
174
+ if(!cols.length){
175
+ box.innerHTML = '<div class="g-col-empty">暂无集合 — 用「📂 智能扫描文件」自动生成,一个文件/一本书 = 一个集合</div>';
176
+ return;
177
+ }
178
+ box.innerHTML = cols.map(c => {
179
+ const n = GLOSS.terms.filter(t => (t.collections || []).includes(c.id)).length;
180
+ const on = c.enabled !== false;
181
+ return '<div class="g-col" data-cid="' + esc(c.id) + '">' +
182
+ '<label class="g-col-chk"><input type="checkbox" data-cen ' + (on ? 'checked' : '') + '></label>' +
183
+ '<div class="g-col-name">' + esc(c.name) +
184
+ '<span class="g-col-meta">' + n + ' 条 · ' + esc(c.source || '手动') + '</span></div>' +
185
+ '<button class="btn gray sm" data-crename title="重命名">✎</button>' +
186
+ '<button class="btn gray sm" data-cdel title="删除集合(不移除术语)">🗑</button>' +
187
+ '</div>';
188
+ }).join('');
189
+ box.querySelectorAll('.g-col').forEach(el => {
190
+ const cid = el.dataset.cid;
191
+ el.querySelector('[data-cen]').onchange = e => {
192
+ const c = getCollection(cid); if(c){ c.enabled = e.target.checked; saveGloss(); }
193
+ renderGlossTable();
194
+ };
195
+ el.querySelector('[data-crename]').onclick = () => {
196
+ const c = getCollection(cid); if(!c) return;
197
+ const nm = prompt('重命名集合:', c.name); if(nm && nm.trim()){ c.name = nm.trim(); saveGloss(); renderCollections(); }
198
+ };
199
+ el.querySelector('[data-cdel]').onclick = () => {
200
+ const c = getCollection(cid); if(!c) return;
201
+ const n = GLOSS.terms.filter(t => (t.collections || []).includes(c.id)).length;
202
+ if(!confirm('删除集合「' + c.name + '」?集合内 ' + n + ' 条术语不会被删除,只是移出集合。')) return;
203
+ GLOSS.terms.forEach(t => { t.collections = (t.collections || []).filter(x => x !== cid); });
204
+ GLOSS.collections = GLOSS.collections.filter(x => x.id !== cid);
205
+ saveGloss(); renderGloss();
206
+ };
207
+ });
208
+ }
209
+ function openCollectionPicker(){
210
+ const cols = GLOSS.collections || [];
211
+ const rows = cols.map(c => {
212
+ const n = GLOSS.terms.filter(t => (t.collections || []).includes(c.id)).length;
213
+ const on = c.enabled !== false;
214
+ return '<label class="gcol-pick" style="display:flex;align-items:center;gap:8px;padding:7px 6px;border-bottom:1px solid var(--bd);cursor:pointer">' +
215
+ '<input type="checkbox" data-cid="' + esc(c.id) + '" ' + (on ? 'checked' : '') + '>' +
216
+ '<span style="flex:1;font-weight:500">' + esc(c.name) + '</span>' +
217
+ '<span class="muted sm">' + n + ' 条</span></label>';
218
+ }).join('');
219
+ modal('📚 选择翻译集合',
220
+ (cols.length ? rows : '<div class="muted" style="padding:8px 4px">暂无集合 — 请到「专有译词库」页点「📂 智能扫描文件」导入,会自动建立集合。</div>') +
221
+ '<div class="gcol-tip muted sm" style="margin-top:8px">勾选的集合,翻译/校对时其内「已确认」术语会被锁定一致。</div>' +
222
+ '<div style="margin-top:12px;display:flex;justify-content:flex-end;gap:8px">' +
223
+ '<button class="btn gray sm" onclick="closeModal()">取消</button>' +
224
+ '<button class="btn pri sm" id="gcol-done">完成</button></div>');
225
+ $('#gcol-done').onclick = () => {
226
+ $$('#mBody input[data-cid]').forEach(b => {
227
+ const c = getCollection(b.dataset.cid); if(c) c.enabled = b.checked;
228
+ });
229
+ saveGloss(); renderGloss();
230
+ closeModal();
231
+ const active = cols.filter(c => c.enabled !== false).length;
232
+ toast(active ? ('已启用 ' + active + ' 个集合,术语锁定会注入其中术语。') : '已停用全部集合,集合术语不再注入。');
233
+ };
234
+ }
235
+ function glossFiltered(){
236
+ let list = GLOSS.terms.slice();
237
+ const q = normText($('#g-q') ? $('#g-q').value : '').toLowerCase();
238
+ const st = $('#g-f-status') ? $('#g-f-status').value : '';
239
+ const rc = $('#g-f-rec') ? $('#g-f-rec').value : '';
240
+ const sr = $('#g-f-src') ? $('#g-f-src').value : '';
241
+ const tg = $('#g-f-tag') ? $('#g-f-tag').value : '';
242
+ const ty = $('#g-f-type') ? $('#g-f-type').value : '';
243
+ if(q) list = list.filter(t =>
244
+ t.zh.toLowerCase().includes(q) || (t.foreign||'').toLowerCase().includes(q) ||
245
+ (t.aliases||[]).some(a => a.toLowerCase().includes(q)) || (t.note||'').toLowerCase().includes(q));
246
+ if(st) list = list.filter(t => (t.status||'pending') === st);
247
+ if(rc) list = list.filter(t => (t.recommend||'') === rc);
248
+ if(sr) list = list.filter(t => (t.sources||[]).indexOf(sr) >= 0);
249
+ if(tg) list = list.filter(t => (t.tags||[]).indexOf(tg) >= 0);
250
+ if(ty) list = list.filter(t => (t.type||'') === ty);
251
+ const cl = $('#g-f-col') ? $('#g-f-col').value : '';
252
+ if(cl) list = list.filter(t => (t.collections||[]).includes(cl));
253
+ if(G_SORT.key){
254
+ const k = G_SORT.key;
255
+ list.sort((a,b) => {
256
+ const av = String(a[k]||''), bv = String(b[k]||'');
257
+ return av.localeCompare(bv, 'zh') * G_SORT.dir;
258
+ });
259
+ }
260
+ return list;
261
+ }
262
+ function renderGlossStats(){
263
+ const t = GLOSS.terms;
264
+ const confirmed = t.filter(x=>x.status==='confirmed').length;
265
+ const pending = t.filter(x=>x.status==='pending'||!x.status).length;
266
+ const rec = t.filter(x=>x.recommend==='rec').length;
267
+ const conflicts = t.filter(x=>(x.note||'').indexOf('⚠')>=0).length;
268
+ $('#g-stats-bar').innerHTML = '<span>词条 <b>' + t.length + '</b></span>' +
269
+ '<span>来源 <b>' + GLOSS.sources.length + '</b></span>' +
270
+ '<span>已确认 <b style="color:var(--ok)">' + confirmed + '</b></span>' +
271
+ '<span>待审核 <b style="color:var(--warn)">' + pending + '</b></span>' +
272
+ '<span>推荐译名 <b style="color:var(--ac)">' + rec + '</b></span>' +
273
+ (conflicts ? '<span>⚠ 冲突 <b style="color:var(--err)">' + conflicts + '</b></span>' : '');
274
+ }
275
+ function renderGlossFilters(){
276
+ // 来源下拉
277
+ const srcSel = $('#g-f-src'); const curSrc = srcSel.value;
278
+ srcSel.innerHTML = '<option value="">全部来源</option>' +
279
+ GLOSS.sources.map(s => '<option value="' + esc(s.id) + '">' + esc(s.name) + '</option>').join('');
280
+ srcSel.value = curSrc;
281
+ // 标签下拉(收集全部标签)
282
+ const tagSet = new Set();
283
+ GLOSS.terms.forEach(t => (t.tags||[]).forEach(x => tagSet.add(x)));
284
+ const tagSel = $('#g-f-tag'); const curTag = tagSel.value;
285
+ tagSel.innerHTML = '<option value="">全部标签</option>' +
286
+ Array.from(tagSet).sort().map(x => '<option value="' + esc(x) + '">' + esc(x) + '</option>').join('');
287
+ tagSel.value = curTag;
288
+ // 集合下拉
289
+ const colSel = $('#g-f-col'); const curCol = colSel.value;
290
+ colSel.innerHTML = '<option value="">全部集合</option>' +
291
+ (GLOSS.collections || []).map(c => '<option value="' + esc(c.id) + '">' + esc(c.name) + '</option>').join('');
292
+ colSel.value = curCol;
293
+ }
294
+ function renderGlossTable(){
295
+ const list = glossFiltered();
296
+ $('#g-count').textContent = list.length + ' / ' + GLOSS.terms.length + ' 条';
297
+ const tb = $('#g-tbody');
298
+ if(!list.length){
299
+ tb.innerHTML = '<tr><td colspan="10" style="text-align:center;color:var(--tx3);padding:24px">(无匹配词条)</td></tr>';
300
+ return;
301
+ }
302
+ tb.innerHTML = list.map(t => {
303
+ const srcNames = (t.sources||[]).map(sid => {
304
+ const s = GLOSS.sources.find(x => x.id === sid);
305
+ return s ? s.name : '?';
306
+ }).join('、');
307
+ const pages = (t.occurrences||[]).reduce((a,o)=>a.concat(o.pages||[]), []).slice(0,6).join(',');
308
+ const recLabel = t.recommend === 'rec' ? '<span class="r">★推荐</span>' : t.recommend === 'ban' ? '<span class="b">禁用</span>' : '<span class="a">允许</span>';
309
+ return '<tr data-id="' + t.id + '" class="' + (G_SEL.has(t.id) ? 'sel' : '') + '">' +
310
+ '<td><input type="checkbox" data-ck style="width:auto;padding:0" ' + (G_SEL.has(t.id) ? 'checked' : '') + '></td>' +
311
+ '<td style="font-weight:500">' + esc(t.zh || '—') + (pages ? '<div class="g-alias">pp.' + esc(pages) + '</div>' : '') + '</td>' +
312
+ '<td style="color:var(--tx2)">' + esc(t.foreign || '—') + '</td>' +
313
+ '<td class="g-alias">' + (t.aliases||[]).map(esc).join('、') + '</td>' +
314
+ '<td>' + esc(t.type || '—') + '</td>' +
315
+ '<td>' + (t.tags||[]).map(x => '<span class="g-tag">' + esc(x) + '</span>').join('') + '</td>' +
316
+ '<td class="g-src" title="' + esc(srcNames) + '">' + esc(srcNames) + '</td>' +
317
+ '<td><span class="g-status ' + (t.status||'pending') + '">' + (G_ST_LABEL[t.status||'pending']) + '</span>' +
318
+ '<div style="display:flex;gap:4px;margin-top:4px">' +
319
+ (t.status !== 'confirmed' ? '<button class="btn gray sm" data-approve title="批准此条,校对时锁定一致(M4)">✓ 批准</button>' : '') +
320
+ (t.status !== 'pending' ? '<button class="btn gray sm" data-topend title="打回待审核(改词/存疑都先回这里)">↺ 待审</button>' : '') +
321
+ (t.status !== 'rejected' ? '<button class="btn gray sm" data-toreject title="拒绝此条,不再注入提示词">✗ 拒绝</button>' : '') +
322
+ '</div></td>' +
323
+ '<td class="g-rec">' + recLabel + '</td>' +
324
+ '<td style="white-space:nowrap">' + (t.url ? '<a class="btn gray sm" href="' + esc(t.url) + '" target="_blank" rel="noopener" title="查看依据 URL">🔗</a> ' : '<button class="btn gray sm" data-gv-url2 title="回填依据 URL">🔗</button> ') + '<button class="btn gray sm" data-lookup title="联网查证通行译法">🔎</button> <button class="btn gray sm" data-verify title="AI 核查该条收录是否正确(v4.26.0)">🤖 核查</button> <button class="btn gray sm" data-edit>编辑</button> <button class="btn gray sm" data-merge1 title="把另一条合并进此条">⇄</button> <button class="btn gray sm" data-del title="删除此条">🗑</button></td>' +
325
+ '</tr>';
326
+ }).join('');
327
+ // 行事件
328
+ tb.querySelectorAll('tr').forEach(tr => {
329
+ const t = GLOSS.terms.find(x => String(x.id) === tr.dataset.id);
330
+ if(!t) return;
331
+ const id = t.id;
332
+ tr.querySelector('[data-ck]').onchange = e => {
333
+ if(e.target.checked) G_SEL.add(id); else G_SEL.delete(id);
334
+ tr.classList.toggle('sel', e.target.checked);
335
+ renderGlossBatch();
336
+ };
337
+ tr.querySelector('[data-lookup]').onclick = () => glossLookup(id);
338
+ const bUrl2 = tr.querySelector('[data-gv-url2]'); if(bUrl2) bUrl2.onclick = () => { if(typeof gvSetUrl === 'function') gvSetUrl(t); };
339
+ const bAp = tr.querySelector('[data-approve]'); if(bAp) bAp.onclick = () => glossSetStatus(id, 'confirmed');
340
+ const bPd = tr.querySelector('[data-topend]'); if(bPd) bPd.onclick = () => glossSetStatus(id, 'pending');
341
+ const bRj = tr.querySelector('[data-toreject]'); if(bRj) bRj.onclick = () => glossSetStatus(id, 'rejected');
342
+ tr.querySelector('[data-verify]').onclick = async () => {
343
+ const items = [{ src: t.foreign || '', dst: t.zh || '', extra: t.type || '' }];
344
+ const vs = await verifyEntries(items, tr.querySelector('[data-verify]'));
345
+ if(!vs) return;
346
+ showVerifyResults(items, vs, {
347
+ // M4:ok → 一键批准为「已批准」;bad/采纳建议 → 打回待审核
348
+ onApprove: () => { glossSetStatus(t.id, 'confirmed'); },
349
+ onAdopt: (k, v) => {
350
+ if(!v.suggest) return false;
351
+ t.zh = v.suggest; t.status = 'pending';
352
+ saveGloss(); glossLog('status', 'term:'+t.id, 'adopt', 'pending');
353
+ renderGlossTable();
354
+ toast('已改为建议译法,状态回到「待审核」');
355
+ return true;
356
+ }
357
+ });
358
+ };
359
+ tr.querySelector('[data-edit]').onclick = () => glossEdit(id);
360
+ tr.querySelector('[data-merge1]').onclick = () => glossMergeInto(id);
361
+ tr.querySelector('[data-del]').onclick = () => glossDelete(id);
362
+ });
363
+ renderGlossBatch();
364
+ }
365
+ function renderGlossBatch(){
366
+ const bar = $('#g-batch');
367
+ const has = G_SEL.size > 0;
368
+ $('#g-sel-n').textContent = G_SEL.size;
369
+ // 批量栏常显:未勾选时按钮禁用,勾选后启用(解决「找不到批量入口」的发现性问题)
370
+ bar.querySelectorAll('button').forEach(b => { b.disabled = !has; });
371
+ }
372
+
373
+ // ── 单条删除词条 ──
374
+ function glossDelete(id){
375
+ const t = GLOSS.terms.find(x => String(x.id) === String(id));
376
+ if(!t) return;
377
+ const label = t.zh || t.foreign || ('#' + id);
378
+ if(!confirm('删除词条「' + label + '」?不可恢复。')) return;
379
+ GLOSS.terms = GLOSS.terms.filter(x => String(x.id) !== String(id));
380
+ G_SEL.delete(id);
381
+ saveGloss(); renderGloss(); toast('已删除「' + label + '」');
382
+ }
383
+
384
+ // ── M4(T-012)单条状态迁移:待审 ⇄ 已批准 ⇄ 已拒绝,toast + 持久化 + 变更日志 ──
385
+ const G_ST_LABEL = { pending:'待审核', confirmed:'已批准', rejected:'已拒绝' };
386
+ function glossSetStatus(id, status){
387
+ const t = GLOSS.terms.find(x => String(x.id) === String(id));
388
+ if(!t) return false;
389
+ const label = t.zh || t.foreign || ('#' + id);
390
+ if(t.status === status){ toast('「' + label + '」已是「' + G_ST_LABEL[status] + '」'); return false; }
391
+ const before = t.status || 'pending';
392
+ t.status = status;
393
+ t.updated = Date.now();
394
+ saveGloss();
395
+ glossLog('status', 'term:' + t.id, before, status);
396
+ renderGlossTable();
397
+ toast('「' + label + '」→ ' + G_ST_LABEL[status] + (status === 'confirmed' ? '(校对时会被锁定一致)' : '(不再注入提示词)'));
398
+ return true;
399
+ }
400
+
401
+ // ── 争议术语联网查证(P2 #8)──
402
+ function glossLookup(id){
403
+ const t = GLOSS.terms.find(x => String(x.id) === String(id));
404
+ if(!t){ toast('术语不存在', 'e'); return; }
405
+ const f = (t.foreign || '').trim();
406
+ const z = (t.zh || '').trim();
407
+ if(!f && !z){ toast('该术语没有可查证的文字', 'w'); return; }
408
+ // 外文 + 中文一起检索,提高学术库命中率
409
+ const q = [f, z].filter(Boolean).join(' ');
410
+ const urls = {
411
+ scholar: 'https://scholar.google.com/scholar?q=' + encodeURIComponent(q),
412
+ baidu: 'https://xueshu.baidu.com/s?wd=' + encodeURIComponent(q),
413
+ cnki: 'https://kns.cnki.net/kns8s/defaultresult/index?kw=' + encodeURIComponent(q),
414
+ wiki: 'https://zh.wikipedia.org/wiki/' + encodeURIComponent(f || z),
415
+ };
416
+ modal('🔎 术语查证', [
417
+ '<div style="font-size:13px;color:var(--tx2);margin-bottom:6px">查证术语</div>',
418
+ '<div style="font-size:15px;font-weight:600;margin-bottom:12px">' + esc(f || '—') + (z ? ' <span style="color:var(--tx2);font-weight:400">' + esc(z) + '</span>' : '') + '</div>',
419
+ '<div style="font-size:12px;color:var(--tx3);margin-bottom:14px">在学术库检索该术语的通行译法与用法(新标签页打开,不消耗 token)</div>',
420
+ '<div style="display:flex;gap:8px;flex-wrap:wrap">' +
421
+ '<button class="btn sm" data-lk="scholar">🔍 Google Scholar</button>' +
422
+ '<button class="btn sm" data-lk="baidu">🔍 百度学术</button>' +
423
+ '<button class="btn sm" data-lk="cnki">🔍 CNKI 知网</button>' +
424
+ '<button class="btn sm" data-lk="wiki">🔍 维基百科</button>' +
425
+ '<button class="btn gray" data-lk="close">关闭</button>' +
426
+ '</div>'
427
+ ].join(''));
428
+ $$('#mBody [data-lk]').forEach(b => {
429
+ b.onclick = () => { b.dataset.lk === 'close' ? closeModal() : window.open(urls[b.dataset.lk], '_blank'); };
430
+ });
431
+ }
432
+
433
+ // ── 词条编辑弹层 ──
434
+ function glossEdit(id){
435
+ const t = GLOSS.terms.find(x => x.id === id); if(!t) return;
436
+ const allTags = new Set(); GLOSS.terms.forEach(x => (x.tags||[]).forEach(g => allTags.add(g)));
437
+ modal('编辑词条 #' + t.id, [
438
+ '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">',
439
+ '<div><label class="f">中文主词形(推荐译名)</label><input id="ge-zh" value="' + esc(t.zh) + '"></div>',
440
+ '<div><label class="f">外文原文</label><input id="ge-fn" value="' + esc(t.foreign) + '"></div>',
441
+ '<div><label class="f">类型</label><select id="ge-type">' + ['人物','概念','著作','学派','机构','事件','其他'].map(x =>
442
+ '<option ' + (t.type===x?'selected':'') + '>' + x + '</option>').join('') + '</select></div>',
443
+ '<div><label class="f">推荐度</label><select id="ge-rec"><option value="">(未设置)</option><option value="rec" ' + (t.recommend==='rec'?'selected':'') + '>★ 推荐译名</option><option value="allow" ' + (t.recommend==='allow'?'selected':'') + '>允许使用</option><option value="ban" ' + (t.recommend==='ban'?'selected':'') + '>🚫 禁用译名</option></select></div>',
444
+ '</div>',
445
+ '<div style="margin-top:10px"><label class="f">别名 / 异译(每行一个)</label><textarea id="ge-alias" rows="2">' + esc((t.aliases||[]).join('\n')) + '</textarea></div>',
446
+ '<div style="margin-top:10px"><label class="f">标签(逗号分隔;已有:' + esc(Array.from(allTags).join('、') || '无') + ')</label><input id="ge-tags" value="' + esc((t.tags||[]).join(',')) + '"></div>',
447
+ '<div style="margin-top:10px"><label class="f">状态</label><select id="ge-st">' +
448
+ '<option value="pending" ' + (t.status==='pending'?'selected':'') + '>待审核</option>' +
449
+ '<option value="confirmed" ' + (t.status==='confirmed'?'selected':'') + '>已确认</option>' +
450
+ '<option value="rejected" ' + (t.status==='rejected'?'selected':'') + '>已拒绝</option></select></div>',
451
+ '<div style="margin-top:10px"><label class="f">依据 URL(证明这条译法的真链接,可留空)</label><input id="ge-url" value="' + esc(t.url||'') + '" placeholder="https://…"></div>',
452
+ '<div style="margin-top:10px"><label class="f">备注</label><textarea id="ge-note" rows="2">' + esc(t.note||'') + '</textarea></div>',
453
+ '<div style="margin-top:14px;display:flex;gap:8px"><button class="btn pri sm" id="ge-save">保存</button>' +
454
+ '<button class="btn sm" id="ge-autotag">🏷 自动打标签</button>' +
455
+ '<span style="flex:1"></span><button class="btn gray sm" id="ge-del">🗑 删除词条</button></div>'
456
+ ].join(''));
457
+ $('#ge-save').onclick = () => {
458
+ const before = JSON.stringify({ zh:t.zh, foreign:t.foreign, status:t.status, recommend:t.recommend });
459
+ t.zh = normText($('#ge-zh').value); t.foreign = normText($('#ge-fn').value);
460
+ t.type = $('#ge-type').value; t.recommend = $('#ge-rec').value;
461
+ t.aliases = $('#ge-alias').value.split('\n').map(s => s.trim()).filter(Boolean);
462
+ t.tags = $('#ge-tags').value.split(/[,,、]/).map(s => s.trim()).filter(Boolean);
463
+ t.status = $('#ge-st').value;
464
+ t.url = normText($('#ge-url').value);
465
+ t.note = $('#ge-note').value;
466
+ t.updated = Date.now();
467
+ saveGloss(); glossLog('edit', 'term:'+t.id, before, JSON.stringify({ zh:t.zh, foreign:t.foreign, status:t.status, recommend:t.recommend }));
468
+ closeModal(); renderGloss(); toast('已保存');
469
+ };
470
+ $('#ge-autotag').onclick = () => {
471
+ const n = applyAutoTags(t);
472
+ $('#ge-tags').value = (t.tags||[]).join(',');
473
+ toast(n ? '打了 ' + n + ' 个标签' : '无新标签命中');
474
+ };
475
+ $('#ge-del').onclick = () => {
476
+ GLOSS.terms = GLOSS.terms.filter(x => x.id !== t.id);
477
+ G_SEL.delete(t.id);
478
+ saveGloss(); glossLog('delete', 'term:'+t.id, JSON.stringify({zh:t.zh,foreign:t.foreign}), null);
479
+ closeModal(); renderGloss(); toast('已删除');
480
+ };
481
+ }
482
+
483
+ // ── 合并核心:把 ids 里的词条并入 targetId ──
484
+ function mergeTermsInto(targetId, ids){
485
+ const tgt = GLOSS.terms.find(t => t.id === targetId);
486
+ if(!tgt) return 0;
487
+ const before = ids.map(id => JSON.stringify(GLOSS.terms.find(t=>t.id===id)));
488
+ for(const id of ids){
489
+ const s = GLOSS.terms.find(x => x.id === id); if(!s) continue;
490
+ if(s.zh && s.zh !== tgt.zh && !(tgt.aliases||[]).includes(s.zh)) (tgt.aliases = tgt.aliases||[]).push(s.zh);
491
+ (s.aliases||[]).forEach(a => { if(a !== tgt.zh && !(tgt.aliases||[]).includes(a)) tgt.aliases.push(a); });
492
+ if(!tgt.foreign && s.foreign) tgt.foreign = s.foreign;
493
+ (s.sources||[]).forEach(x => { if(tgt.sources.indexOf(x) < 0) tgt.sources.push(x); });
494
+ (s.occurrences||[]).forEach(o => tgt.occurrences.push(o));
495
+ (s.tags||[]).forEach(x => { if((tgt.tags||[]).indexOf(x) < 0) tgt.tags.push(x); });
496
+ if(s.note) tgt.note = (tgt.note ? tgt.note + ';' : '') + s.note;
497
+ }
498
+ GLOSS.terms = GLOSS.terms.filter(x => !ids.includes(x.id));
499
+ ids.forEach(id => G_SEL.delete(id));
500
+ tgt.updated = Date.now();
501
+ saveGloss(); glossLog('merge', 'term:'+targetId, before.join('\n'), JSON.stringify({ zh:tgt.zh, foreign:tgt.foreign, aliases:tgt.aliases }));
502
+ return ids.length;
503
+ }
504
+
505
+ // ── 合并:把 A 并入 B ──
506
+ function glossMergeInto(targetId){
507
+ const others = GLOSS.terms.filter(t => t.id !== targetId);
508
+ if(!others.length){ toast('没有其他词条可合并', 'e'); return; }
509
+ const tgt = GLOSS.terms.find(t => t.id === targetId);
510
+ modal('合并到「' + (tgt.zh||tgt.foreign) + '」', [
511
+ '<p style="font-size:12.5px;color:var(--tx2);margin-bottom:10px">选择要被合并进来的词条(被选中的词条将消失,其别名 / 标签 / 来源 / 页码全部并入目标词条):</p>',
512
+ '<div style="max-height:40vh;overflow:auto;border:1px solid var(--bd);border-radius:6px">' +
513
+ others.map(t => '<label style="display:flex;gap:8px;padding:7px 10px;border-bottom:1px solid var(--bd);cursor:pointer;align-items:center">' +
514
+ '<input type="checkbox" data-mid="' + t.id + '" style="width:auto;padding:0">' +
515
+ '<b>' + esc(t.zh||'—') + '</b><span style="color:var(--tx3)">' + esc(t.foreign||'') + '</span>' +
516
+ '<span class="g-alias">' + (t.aliases||[]).map(esc).join('、') + '</span></label>').join('') +
517
+ '</div>',
518
+ '<div style="margin-top:12px"><button class="btn pri sm" id="gm-go">执行合并</button> <button class="btn gray sm" id="gm-cancel">取消</button></div>'
519
+ ].join(''));
520
+ $('#gm-cancel').onclick = closeModal;
521
+ $('#gm-go').onclick = () => {
522
+ const ids = Array.from(document.querySelectorAll('[data-mid]:checked')).map(x => +x.dataset.mid);
523
+ if(!ids.length){ toast('先勾选要合并的词条', 'e'); return; }
524
+ const n = mergeTermsInto(targetId, ids);
525
+ closeModal(); renderGloss(); toast('已合并 ' + n + ' 条');
526
+ };
527
+ }
528
+
529
+ // ── 批量操作 ──
530
+ function glossBatch(fn){
531
+ const ids = Array.from(G_SEL);
532
+ let n = 0;
533
+ for(const id of ids){ const t = GLOSS.terms.find(x => x.id === id); if(t && fn(t) !== false) n++; }
534
+ if(n){ saveGloss(); renderGloss(); }
535
+ toast('已更新 ' + n + ' 条');
536
+ }
537
+
538
+ // ── 导入向导 ──
539
+ $('#btn-g-import').onclick = () => $('#g-file').click();
540
+ $('#g-file').onchange = async e => {
541
+ const f = e.target.files[0]; e.target.value = '';
542
+ if(!f) return;
543
+ const btn = $('#btn-g-import');
544
+ btn.disabled = true; btn.textContent = '⏳ 解析中…';
545
+ try{
546
+ const parsed = await parseGlossFile(f);
547
+ // 预览 + 确认
548
+ const sample = parsed.entries.slice(0, 15);
549
+ modal('导入预览 · ' + f.name + '(共识别 ' + parsed.entries.length + ' 条)', [
550
+ '<div class="g-preview"><table><tr><th>中文</th><th>外文</th><th>页码</th><th>附加</th></tr>' +
551
+ sample.map(x => '<tr><td>' + esc(x.zh||'—') + '</td><td>' + esc(x.foreign||'—') + '</td><td>' + esc((x.pages||[]).join(',')) + '</td><td style="color:var(--tx3)">' + esc(x.cat || x.note || '') + '</td></tr>').join('') +
552
+ (parsed.entries.length > 15 ? '<tr><td colspan="4" style="color:var(--tx3)">… 其余 ' + (parsed.entries.length-15) + ' 条略</td></tr>' : '') +
553
+ '</table></div>',
554
+ '<p style="font-size:12px;color:var(--tx3);margin:10px 0">入库时自动:繁体转简体、全半角统一、外文相同的词条自动合并别名。</p>',
555
+ '<div style="display:flex;gap:8px"><button class="btn pri sm" id="gi-go">✓ 确认导入</button>' +
556
+ '<label style="display:flex;gap:6px;align-items:center;font-size:12.5px;cursor:pointer"><input type="checkbox" id="gi-autotag" checked style="width:auto"> 导入后自动打标签</label></div>'
557
+ ].join(''));
558
+ $('#gi-go').onclick = async () => {
559
+ const doAutoTag = !!(document.querySelector('#gi-autotag') && document.querySelector('#gi-autotag').checked);
560
+ closeModal();
561
+ const r = await glossIngest(parsed);
562
+ if(doAutoTag){ const n = applyAutoTagsAll(); if(n) saveGloss(); }
563
+ btn.disabled = false; btn.textContent = '📂 导入索引 / 术语库';
564
+ renderGloss();
565
+ toast('导入完成:新增 ' + r.added + ',合并 ' + r.merged + (r.conflicts ? ',⚠冲突 ' + r.conflicts : '') + (r.aliasAdded ? ',别名 +' + r.aliasAdded : ''));
566
+ };
567
+ }catch(err){
568
+ btn.disabled = false; btn.textContent = '📂 导入索引 / 术语库';
569
+ toast('导入失败:' + err.message, 'e');
570
+ }
571
+ };
572
+
573
+ // ── 智能扫描文件(LLM 抽词 → 自动建集合)──
574
+ $('#btn-g-scan').onclick = () => $('#g-scan-file').click();
575
+ $('#g-scan-file').onchange = async e => {
576
+ const f = e.target.files[0]; e.target.value = '';
577
+ if(!f) return;
578
+ const btn = $('#btn-g-scan');
579
+ btn.disabled = true; btn.textContent = '🤖 扫描中…';
580
+ try{
581
+ const r = await smartScanFile(f, (msg) => { btn.textContent = '🤖 ' + msg; });
582
+ btn.disabled = false; btn.textContent = '🤖 智能扫描文件';
583
+ if(r && r.total){
584
+ toast('智能扫描完成:抽取 ' + r.total + ' 条术语 → 集合(新增 ' + r.added + ',合并 ' + r.merged + ')。高置信度已自动确认,低置信度请到词条列表人工审核。');
585
+ }
586
+ }catch(err){
587
+ btn.disabled = false; btn.textContent = '🤖 智能扫描文件';
588
+ toast('智能扫描失败:' + err.message, 'e');
589
+ }
590
+ };
591
+
592
+ // ── 自动标签规则管理 ──
593
+ $('#btn-g-rules').onclick = () => {
594
+ ensureRules();
595
+ modal('自动标签规则(正则匹配 中文/外文/别名 → 打标签)', [
596
+ '<div style="max-height:44vh;overflow:auto" id="gr-list">' +
597
+ GLOSS.rules.map((r,i) => '<div style="display:flex;gap:6px;align-items:center;padding:5px 0;border-bottom:1px solid var(--bd)">' +
598
+ '<input type="checkbox" data-ri="' + i + '" ' + (r.on!==false?'checked':'') + ' style="width:auto;padding:0" title="启用">' +
599
+ '<input data-rp="' + i + '" value="' + esc(r.pattern) + '" style="flex:1;font-family:var(--f-mono);font-variant-numeric:tabular-nums;font-size:12px" placeholder="正则">' +
600
+ '<span style="color:var(--tx3)">→</span>' +
601
+ '<input data-rt="' + i + '" value="' + esc(r.tag) + '" style="flex:0 0 150px" placeholder="标签名">' +
602
+ '<button class="btn gray sm" data-rd="' + i + '">✕</button></div>').join('') +
603
+ '</div>',
604
+ '<div style="margin-top:10px;display:flex;gap:8px"><button class="btn sm" id="gr-add">+ 新增规则</button>' +
605
+ '<button class="btn pri sm" id="gr-apply">保存并对全部词条重新打标</button>' +
606
+ '<button class="btn gray sm" id="gr-saveonly">仅保存规则</button></div>'
607
+ ].join(''));
608
+ GLOSS.rules.forEach((r,i) => {
609
+ const row = document.querySelector('[data-ri="' + i + '"]');
610
+ if(row) row.onchange = e => r.on = e.target.checked;
611
+ const rp = document.querySelector('[data-rp="' + i + '"]'); if(rp) rp.onchange = e => r.pattern = e.target.value;
612
+ const rt = document.querySelector('[data-rt="' + i + '"]'); if(rt) rt.onchange = e => r.tag = e.target.value;
613
+ const rd = document.querySelector('[data-rd="' + i + '"]'); if(rd) rd.onclick = () => { GLOSS.rules.splice(i,1); saveGloss(); closeModal(); $('#btn-g-rules').click(); };
614
+ });
615
+ $('#gr-add').onclick = () => { GLOSS.rules.push({ id:'r'+Date.now(), pattern:'', tag:'', on:true }); saveGloss(); closeModal(); $('#btn-g-rules').click(); };
616
+ $('#gr-saveonly').onclick = () => { saveGloss(); closeModal(); toast('规则已保存'); };
617
+ $('#gr-apply').onclick = () => {
618
+ saveGloss();
619
+ const n = applyAutoTagsAll();
620
+ closeModal(); toast('规则已保存,新打标签 ' + n + ' 个');
621
+ };
622
+ };
623
+
624
+ // ── 统计 ──
625
+ $('#btn-g-stats').onclick = () => {
626
+ const t = GLOSS.terms;
627
+ const byType = {}, byTag = {}, bySrc = {};
628
+ t.forEach(x => { byType[x.type||'未分类'] = (byType[x.type||'未分类']||0)+1; (x.tags||[]).forEach(g => byTag[g]=(byTag[g]||0)+1); });
629
+ GLOSS.sources.forEach(s => bySrc[s.name] = t.filter(x => (x.sources||[]).indexOf(s.id)>=0).length);
630
+ const rows = arr => Object.entries(arr).sort((a,b)=>b[1]-a[1]).map(([k,v]) => '<tr><td>' + esc(k) + '</td><td>' + v + '</td></tr>').join('');
631
+ modal('词库统计', [
632
+ '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;font-size:12.5px">',
633
+ '<div><b>按类型</b><table class="g-preview" style="margin-top:6px">' + rows(byType) + '</table></div>',
634
+ '<div><b>按标签</b><table class="g-preview" style="margin-top:6px">' + rows(byTag) + '</table></div>',
635
+ '<div><b>按来源</b><table class="g-preview" style="margin-top:6px">' + rows(bySrc) + '</table></div>',
636
+ '</div>',
637
+ '<p style="font-size:11.5px;color:var(--tx3);margin-top:10px">变更日志:' + GLOSS.log.length + ' 条(最近 ' + Math.min(5, GLOSS.log.length) + ' 条:' +
638
+ GLOSS.log.slice(0,5).map(l => l.action + '@' + new Date(l.t).toLocaleTimeString('zh-CN')).join(';') + ')</p>'
639
+ ].join(''));
640
+ };
641
+
642
+ // ── 导出 ──
643
+ $('#btn-g-export').onclick = () => {
644
+ const list = glossFiltered();
645
+ if(!list.length){ toast('当前筛选下无词条', 'e'); return; }
646
+ modal('导出 ' + list.length + ' 条(按当前筛选)', [
647
+ '<p style="font-size:12px;color:var(--tx3);margin-bottom:10px">CSV / Excel 的列结构与术语库导入兼容(src,外文 / dst,中文 / cat,类型 / note,备注)。</p>',
648
+ '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px">' +
649
+ ['csv:CSV 表格', 'xlsx:Excel 工作簿', 'json:JSON 数组', 'md:Markdown 索引', 'docx:Word 索引', 'tbx:TBX 术语库']
650
+ .map(x => { const [k, label] = x.split(':'); return '<button class="btn" data-exp="' + k + '" style="padding:10px">' + label + '</button>'; }).join('') +
651
+ '</div>'
652
+ ].join(''));
653
+ document.querySelectorAll('[data-exp]').forEach(b => b.onclick = () => { closeModal(); glossExport(b.dataset.exp, list); });
654
+ };
655
+ async function glossExport(fmt, list){
656
+ try{
657
+ const stamp = today();
658
+ if(fmt === 'csv'){
659
+ const csv = 'src,dst,cat,note\n' + list.map(t => csvEsc(t.foreign||'') + ',' + csvEsc(t.zh||'') + ',' + csvEsc(t.type||'') + ',' + csvEsc(((t.note||'') + ((t.occurrences||[]).length ? ' [页码:' + (t.occurrences||[]).map(o=>o.pages.join('/')).join(';') + ']' : '')) )).join('\n');
660
+ dl('译词库_' + stamp + '.csv', '\uFEFF' + csv, 'text/csv');
661
+ } else if(fmt === 'json'){
662
+ dl('译词库_' + stamp + '.json', JSON.stringify(list.map(t => ({ zh:t.zh, foreign:t.foreign, aliases:t.aliases, type:t.type, tags:t.tags, status:t.status, recommend:t.recommend, note:t.note, sources:(t.sources||[]).map(s => (GLOSS.sources.find(x=>x.id===s)||{}).name).filter(Boolean), pages:(t.occurrences||[]).map(o=>o.pages).flat() })), null, 2), 'application/json');
663
+ } else if(fmt === 'md'){
664
+ const md = '# 专有译词库导出\n\n> ' + list.length + ' 条 · ' + new Date().toLocaleString('zh-CN') + '\n\n' +
665
+ '| 中文主词 | 外文 | 别名 | 类型 | 标签 | 状态 | 页码 |\n|---|---|---|---|---|---|---|\n' +
666
+ list.map(t => '| ' + [t.zh, t.foreign, (t.aliases||[]).join('、'), t.type, (t.tags||[]).join('、'), ({pending:'待审',confirmed:'已确认',rejected:'已拒'}[t.status||'pending']), (t.occurrences||[]).map(o=>o.pages.join(',')).join(';')].map(x => String(x||'—').replace(/\|/g,'\\|')).join(' | ') + ' |').join('\n');
667
+ dl('译词库_' + stamp + '.md', md, 'text/markdown');
668
+ } else if(fmt === 'xlsx'){
669
+ await loadLib('XLSX', ['https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js', 'https://unpkg.com/xlsx@0.18.5/dist/xlsx.full.min.js']);
670
+ const ws = window.XLSX.utils.aoa_to_sheet([['src','dst','cat','aliases','tags','status','recommend','note','pages']].concat(
671
+ list.map(t => [t.foreign||'', t.zh||'', t.type||'', (t.aliases||[]).join('、'), (t.tags||[]).join('、'), t.status||'', t.recommend||'', t.note||'', ((t.occurrences||[]).map(o=>(o.pages||[]).join(','))||[]).join(';')])));
672
+ const wb = window.XLSX.utils.book_new();
673
+ window.XLSX.utils.book_append_sheet(wb, ws, '词库');
674
+ window.XLSX.writeFile(wb, '译词库_' + stamp + '.xlsx');
675
+ } else if(fmt === 'docx'){
676
+ await loadLib('docx', ['https://cdn.jsdelivr.net/npm/docx@8.5.0/build/index.umd.js', 'https://unpkg.com/docx@8.5.0/build/index.umd.js']);
677
+ const D = window.docx;
678
+ const paras = [ new D.Paragraph({ text:'专有译词库', heading:D.HeadingLevel.HEADING_1 }),
679
+ new D.Paragraph({ children:[ new D.TextRun({ text: list.length + ' 条 · ' + new Date().toLocaleString('zh-CN'), italics:true, color:'888888' }) ] }),
680
+ new D.Paragraph({ text:'' }) ];
681
+ const tableRows = [ new D.TableRow({ tableHeader:true, children: ['中文主词','外文','别名','类型','标签','页码'].map(h => new D.TableCell({ children:[ new D.Paragraph({ children:[ new D.TextRun({ text:h, bold:true }) ] }) ] })) }) ];
682
+ list.forEach(t => {
683
+ tableRows.push(new D.TableRow({ children: [t.zh||'', t.foreign||'', (t.aliases||[]).join('、'), t.type||'', (t.tags||[]).join('、'), (t.occurrences||[]).map(o=>o.pages.join(',')).join(';')].map(c => new D.TableCell({ children:[ new D.Paragraph({ children:[ new D.TextRun(String(c))] }) ] })) }));
684
+ });
685
+ const doc = new D.Document({ sections: [{ children: paras.concat([ new D.Table({ rows: tableRows, width:{ size:100, type:D.WidthType.PERCENTAGE } }) ]) }] });
686
+ const blob = await D.Packer.toBlob(doc);
687
+ dlBlob('译词库_' + stamp + '.docx', blob);
688
+ } else if(fmt === 'tbx'){
689
+ const tbx = '<?xml version="1.0" encoding="UTF-8"?>\n<martif type="TBX" xml:lang="zh">\n <martifHeader><fileDesc><sourceDesc><p>transproof glossary export</p></sourceDesc></fileDesc></martifHeader>\n <text><body>\n' +
690
+ list.filter(t => t.foreign).map(t =>
691
+ ' <termEntry id="g' + t.id + '">\n' +
692
+ ' <langSet xml:lang="en"><tig><term>' + esc(t.foreign) + '</term></tig></langSet>\n' +
693
+ ' <langSet xml:lang="zh"><tig><term>' + esc(t.zh) + '</term></tig></langSet>\n' +
694
+ ' </termEntry>'
695
+ ).join('\n') + '\n </body></text>\n</martif>';
696
+ dl('译词库_' + stamp + '.tbx', tbx, 'application/xml');
697
+ }
698
+ toast('已导出 ' + fmt.toUpperCase() + ',' + list.length + ' 条');
699
+ }catch(err){ toast('导出失败:' + err.message, 'e'); }
700
+ }
701
+ function csvEsc(s){ s = String(s==null?'':s); return /[",\n]/.test(s) ? '"' + s.replace(/"/g,'""') + '"' : s; }
702
+ function dlBlob(name, blob){
703
+ const a = document.createElement('a');
704
+ a.href = URL.createObjectURL(blob); a.download = name; a.click();
705
+ // 60 秒后再回收:过早 revoke 在慢速下载 / 内嵌浏览器环境会把文件截断成损坏包
706
+ setTimeout(() => URL.revokeObjectURL(a.href), 60000);
707
+ }
708
+
709
+ // ── 同步到术语库(核心联动)──
710
+ $('#btn-g-sync').onclick = () => {
711
+ const cands = GLOSS.terms.filter(t => t.status === 'confirmed' && t.recommend !== 'ban' && t.foreign && t.zh);
712
+ if(!cands.length){ toast('没有可同步的词条(需「已确认」状态且有中外文对照)', 'e'); return; }
713
+ let added = 0, updated = 0;
714
+ for(const t of cands){
715
+ const ex = TERMS.find(x => x.src.toLowerCase() === t.foreign.toLowerCase());
716
+ const noteParts = [];
717
+ if((t.tags||[]).length) noteParts.push(t.tags.join('、'));
718
+ if(t.aliases && t.aliases.length) noteParts.push('别名:' + t.aliases.join('、'));
719
+ if(t.note) noteParts.push(t.note);
720
+ const pagesStr = (t.occurrences||[]).map(o=>(o.pages||[]).join(',')).filter(Boolean).join(';');
721
+ if(pagesStr) noteParts.push('页码:' + pagesStr);
722
+ if(ex){ ex.dst = t.zh; ex.note = noteParts.join(';'); ex.cat = t.type || ex.cat || '其他'; updated++; }
723
+ else { TERMS.push({ src:t.foreign, dst:t.zh, cat:t.type || '其他', note:noteParts.join(';') }); added++; }
724
+ }
725
+ save(LS.terms, TERMS); renderTerms();
726
+ glossLog('sync', 'terms', null, { added, updated });
727
+ toast('同步完成:新增 ' + added + ' 条,更新 ' + updated + ' 条 → 术语库');
728
+ };
729
+
730
+ // ── 表头排序 ──
731
+ document.querySelectorAll('#g-table th[data-sort]').forEach(th => {
732
+ th.onclick = () => {
733
+ const k = th.dataset.sort;
734
+ G_SORT.dir = (G_SORT.key === k) ? -G_SORT.dir : 1;
735
+ G_SORT.key = k;
736
+ renderGlossTable();
737
+ };
738
+ });
739
+ // ── 筛选事件 ──
740
+ ['g-q','g-f-status','g-f-rec','g-f-src','g-f-tag','g-f-type','g-f-col'].forEach(id => {
741
+ const el = document.getElementById(id);
742
+ if(el) el.addEventListener(el.tagName === 'INPUT' ? 'input' : 'change', renderGlossTable);
743
+ });
744
+ $('#g-f-reset').onclick = () => {
745
+ ['g-q','g-f-status','g-f-rec','g-f-src','g-f-tag','g-f-type','g-f-col'].forEach(id => { const el = document.getElementById(id); if(el) el.value = ''; });
746
+ renderGlossTable();
747
+ };
748
+ // ── 批量按钮 ──
749
+ $('#g-all').onchange = e => {
750
+ const list = glossFiltered();
751
+ if(e.target.checked) list.forEach(t => G_SEL.add(t.id)); else { list.forEach(t => G_SEL.delete(t.id)); }
752
+ renderGlossTable();
753
+ };
754
+ $('#g-b-confirm').onclick = () => glossBatch(t => { t.status = 'confirmed'; });
755
+ $('#g-b-pend').onclick = () => glossBatch(t => { t.status = 'pending'; });
756
+ $('#g-b-reject').onclick = () => glossBatch(t => { t.status = 'rejected'; });
757
+ $('#g-b-rec').onclick = () => glossBatch(t => { t.recommend = 'rec'; });
758
+ $('#g-b-ban').onclick = () => glossBatch(t => { t.recommend = 'ban'; });
759
+ $('#g-b-merge').onclick = () => {
760
+ const ids = Array.from(G_SEL);
761
+ if(ids.length < 2){ toast('合并需至少勾选 2 条:第一条为目标,其余并入', 'e'); return; }
762
+ const tgt = GLOSS.terms.find(t => t.id === ids[0]);
763
+ if(!tgt) return;
764
+ const mergeIds = ids.slice(1);
765
+ if(!confirm('把选中的 ' + mergeIds.length + ' 条并入「' + (tgt.zh||tgt.foreign) + '」?其别名/标签/来源/页码会并入目标词条。')) return;
766
+ const n = mergeTermsInto(tgt.id, mergeIds);
767
+ renderGloss(); toast('已合并 ' + n + ' 条');
768
+ };
769
+ $('#g-b-del').onclick = () => {
770
+ if(!G_SEL.size) return;
771
+ if(!confirm('删除选中的 ' + G_SEL.size + ' 条词条?不可恢复。')) return;
772
+ GLOSS.terms = GLOSS.terms.filter(t => !G_SEL.has(t.id));
773
+ saveGloss(); G_SEL.clear(); renderGloss(); toast('已删除');
774
+ };