dsh-bilingual-reader 0.1.0 → 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/web/app.js CHANGED
@@ -1,35 +1,102 @@
1
1
  const API = '/dsh-bilingual-reader/api'
2
+ const VIEW_KEY = 'dsh-bilingual-reader:view'
3
+ const FONT_KEY = 'dsh-bilingual-reader:font'
4
+ const POSITION_PREFIX = 'dsh-bilingual-reader:pos:'
5
+ const LAST_DOC_KEY = 'dsh-bilingual-reader:last-doc'
6
+ const VIEWS = new Set(['inline', 'bilingual', 'original', 'translation'])
7
+ const FONT_SCALES = [90, 100, 110, 120, 130]
2
8
 
3
9
  const $ = (selector, root = document) => root.querySelector(selector)
4
10
  const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]
5
11
 
12
+ function storedFontScale() {
13
+ try {
14
+ const value = Number(localStorage.getItem(FONT_KEY))
15
+ if (FONT_SCALES.includes(value)) return value
16
+ } catch {
17
+ // localStorage can be unavailable in hardened webviews; default is fine.
18
+ }
19
+ return 100
20
+ }
21
+
22
+ function storedView() {
23
+ try {
24
+ const value = localStorage.getItem(VIEW_KEY)
25
+ if (VIEWS.has(value)) return value
26
+ } catch {
27
+ // localStorage can be unavailable in hardened webviews; default is fine.
28
+ }
29
+ return 'inline'
30
+ }
31
+
6
32
  const state = {
7
33
  health: null,
8
34
  docs: [],
9
35
  doc: null,
10
- view: 'bilingual',
36
+ view: storedView(),
37
+ fontScale: storedFontScale(),
38
+ composerMode: 'url',
11
39
  poll: null,
12
40
  busy: false,
13
41
  glossary: [],
42
+ inboxAvailable: false,
43
+ restoreUntil: 0,
44
+ }
45
+
46
+ function applyFontScale(scale, persist = true) {
47
+ const index = FONT_SCALES.indexOf(Number(scale))
48
+ const safe = index === -1 ? FONT_SCALES.indexOf(100) : index
49
+ state.fontScale = FONT_SCALES[safe]
50
+ els.blocks.style.fontSize = `${state.fontScale}%`
51
+ els.fontSmaller.disabled = safe === 0
52
+ els.fontLarger.disabled = safe === FONT_SCALES.length - 1
53
+ if (persist) {
54
+ try {
55
+ localStorage.setItem(FONT_KEY, String(state.fontScale))
56
+ } catch {
57
+ // Preference persistence is optional.
58
+ }
59
+ }
60
+ }
61
+
62
+ function stepFont(delta) {
63
+ const index = FONT_SCALES.indexOf(state.fontScale)
64
+ const next = Math.min(FONT_SCALES.length - 1, Math.max(0, index + delta))
65
+ applyFontScale(FONT_SCALES[next])
66
+ }
67
+
68
+ const rendered = {
69
+ docId: null,
70
+ signatures: [],
14
71
  }
15
72
 
16
73
  const els = {
17
74
  form: $('#read-form'),
18
75
  url: $('#url-input'),
76
+ text: $('#text-input'),
77
+ composerModes: $$('.composer-modes button'),
19
78
  lang: $('#lang-select'),
20
79
  readBtn: $('#read-btn'),
21
80
  aiHint: $('#ai-hint'),
22
81
  notice: $('#notice'),
23
82
  docs: $('#docs'),
24
83
  refreshDocs: $('#refresh-docs'),
84
+ reader: $('.reader'),
25
85
  empty: $('#empty'),
26
86
  docView: $('#doc-view'),
27
87
  title: $('#doc-title'),
28
88
  meta: $('#doc-meta'),
29
89
  status: $('#doc-status'),
30
90
  progress: $('#progress-bar'),
91
+ progressWrap: $('#progress-wrap'),
31
92
  blocks: $('#blocks'),
93
+ fontSmaller: $('#font-smaller'),
94
+ fontReset: $('#font-reset'),
95
+ fontLarger: $('#font-larger'),
32
96
  exportLink: $('#export-link'),
97
+ inboxLink: $('#inbox-link'),
98
+ printBtn: $('#print-btn'),
99
+ copyBtn: $('#copy-btn'),
33
100
  retry: $('#retry-btn'),
34
101
  delete: $('#delete-btn'),
35
102
  glossaryBtn: $('#glossary-btn'),
@@ -37,6 +104,9 @@ const els = {
37
104
  glossaryDialog: $('#glossary-dialog'),
38
105
  glossaryClose: $('#glossary-close'),
39
106
  glossaryList: $('#glossary-list'),
107
+ glossaryExport: $('#glossary-export'),
108
+ glossaryImport: $('#glossary-import'),
109
+ glossaryFile: $('#glossary-file'),
40
110
  glossaryForm: $('#glossary-form'),
41
111
  termSource: $('#term-source'),
42
112
  termTarget: $('#term-target'),
@@ -104,7 +174,28 @@ function showGlossaryNotice(message, isError = false) {
104
174
  function setBusy(busy) {
105
175
  state.busy = busy
106
176
  els.readBtn.disabled = busy
107
- els.readBtn.textContent = busy ? '读取中…' : '读取并翻译'
177
+ els.readBtn.textContent = busy
178
+ ? '处理中…'
179
+ : state.composerMode === 'text' ? '翻译文本' : '读取并翻译'
180
+ }
181
+
182
+ function setComposerMode(mode) {
183
+ if (mode !== 'url' && mode !== 'text') return
184
+ state.composerMode = mode
185
+ const isUrl = mode === 'url'
186
+ els.url.hidden = !isUrl
187
+ els.url.required = isUrl
188
+ els.text.hidden = isUrl
189
+ els.text.required = !isUrl
190
+ for (const button of els.composerModes) {
191
+ const active = button.dataset.composeMode === mode
192
+ button.classList.toggle('active', active)
193
+ button.setAttribute('aria-pressed', String(active))
194
+ }
195
+ els.readBtn.textContent = isUrl ? '读取并翻译' : '翻译文本'
196
+ showNotice('')
197
+ const field = isUrl ? els.url : els.text
198
+ field.focus()
108
199
  }
109
200
 
110
201
  function renderDocs() {
@@ -128,6 +219,9 @@ async function loadDocs() {
128
219
  const data = await api('/docs?limit=30')
129
220
  state.docs = data.docs
130
221
  renderDocs()
222
+ // The list is a file snapshot; the open document is the source of truth for
223
+ // its own status, which avoids a stale "翻译中" after the final poll.
224
+ if (state.doc !== null) updateActiveDocItem(state.doc)
131
225
  }
132
226
 
133
227
  function startPolling() {
@@ -140,7 +234,7 @@ function startPolling() {
140
234
  try {
141
235
  const data = await api(`/docs/${encodeURIComponent(state.doc.id)}`)
142
236
  state.doc = data.doc
143
- renderDoc()
237
+ updateDocView()
144
238
  if (!['pending', 'running'].includes(state.doc.status)) {
145
239
  clearInterval(state.poll)
146
240
  state.poll = null
@@ -153,48 +247,183 @@ function startPolling() {
153
247
  }, 900)
154
248
  }
155
249
 
250
+ function positionKey(id) {
251
+ return `${POSITION_PREFIX}${id}`
252
+ }
253
+
254
+ function storedLastDoc() {
255
+ try {
256
+ return localStorage.getItem(LAST_DOC_KEY)
257
+ } catch {
258
+ return null
259
+ }
260
+ }
261
+
262
+ function rememberDoc(id) {
263
+ try {
264
+ localStorage.setItem(LAST_DOC_KEY, id)
265
+ } catch {
266
+ // Resume is optional.
267
+ }
268
+ }
269
+
270
+ function forgetDoc(id) {
271
+ try {
272
+ if (localStorage.getItem(LAST_DOC_KEY) === id) localStorage.removeItem(LAST_DOC_KEY)
273
+ } catch {
274
+ // Resume is optional.
275
+ }
276
+ }
277
+
278
+ function readerScrolls() {
279
+ return els.reader.scrollHeight > els.reader.clientHeight + 1
280
+ }
281
+
282
+ function currentScrollTop() {
283
+ if (readerScrolls()) return els.reader.scrollTop
284
+ return window.scrollY || document.documentElement.scrollTop || 0
285
+ }
286
+
287
+ function setScrollTop(value) {
288
+ // Set both: the page scrolls inside DSH's iframe, while the reader container
289
+ // becomes the scroller in some embeddings. The inactive one ignores the value.
290
+ els.reader.scrollTop = value
291
+ window.scrollTo(0, value)
292
+ }
293
+
294
+ function saveScroll() {
295
+ if (state.doc === null || Date.now() < state.restoreUntil) return
296
+ try {
297
+ localStorage.setItem(positionKey(state.doc.id), String(currentScrollTop()))
298
+ } catch {
299
+ // Position memory is optional.
300
+ }
301
+ }
302
+
303
+ let restoreToken = 0
304
+
305
+ function restoreScroll(id) {
306
+ let value = 0
307
+ try {
308
+ value = Number(localStorage.getItem(positionKey(id)))
309
+ } catch {
310
+ return
311
+ }
312
+ if (!Number.isFinite(value) || value <= 0) return
313
+ const token = ++restoreToken
314
+ state.restoreUntil = Date.now() + 500
315
+ const apply = () => {
316
+ if (token !== restoreToken || state.doc?.id !== id) return
317
+ setScrollTop(value)
318
+ }
319
+ // Layout is synchronous after innerHTML; timers also work in background
320
+ // webviews where requestAnimationFrame may be throttled.
321
+ setTimeout(apply, 0)
322
+ setTimeout(apply, 150)
323
+ }
324
+
156
325
  async function openDoc(id) {
326
+ saveScroll()
327
+ // While the new document renders, the browser can emit a scroll event at 0.
328
+ // Hold position writes until the saved position has been restored.
329
+ state.restoreUntil = Date.now() + 1000
157
330
  const data = await api(`/docs/${encodeURIComponent(id)}`)
158
331
  state.doc = data.doc
159
- renderDoc()
332
+ rememberDoc(id)
160
333
  renderDocs()
334
+ renderDoc()
335
+ restoreScroll(id)
161
336
  startPolling()
162
337
  }
163
338
 
339
+ function retryButton(block) {
340
+ return `<button type="button" class="badge-action" data-retry-block="${escapeAttr(block.id)}">重试此段</button>`
341
+ }
342
+
164
343
  function blockPlaceholder(block) {
165
344
  if (block.status === 'failed') {
166
- return `<p class="placeholder error">翻译失败${block.error ? `:${escapeHtml(block.error)}` : ''}</p>`
345
+ return `<p class="placeholder error">翻译失败${block.error ? `:${escapeHtml(block.error)}` : ''} ${retryButton(block)}</p>`
167
346
  }
168
347
  return '<p class="placeholder">待翻译</p>'
169
348
  }
170
349
 
350
+ function warningLabel(value) {
351
+ const text = String(value ?? '')
352
+ if (text.includes('保护片段')) return '保护片段丢失'
353
+ if (text.includes('术语未使用')) return '术语未命中'
354
+ if (text.includes('译文与原文')) return '可能未翻译'
355
+ return '需复核'
356
+ }
357
+
171
358
  function renderBlock(block) {
359
+ const id = ` data-block-id="${escapeAttr(block.id)}"`
172
360
  if (block.type === 'code' || block.type === 'hr') {
173
- return `<section class="block block-code">${block.originalHtml}</section>`
361
+ return `<section class="block block-code"${id}>${block.originalHtml}</section>`
174
362
  }
175
363
  if (block.translatable !== true) {
176
- return `<section class="block block-plain">${block.originalHtml}</section>`
364
+ return `<section class="block block-plain"${id}>${block.originalHtml}</section>`
177
365
  }
178
366
  const warning = block.warning
179
- ? `<span class="badge warn" title="${escapeAttr(block.warning)}">保护片段丢失</span>`
367
+ ? `<span class="badge warn" title="${escapeAttr(block.warning)}">${escapeHtml(warningLabel(block.warning))}</span>${retryButton(block)}`
180
368
  : ''
181
369
  const translation = block.translationHtml
182
370
  ? block.translationHtml
183
371
  : blockPlaceholder(block)
184
372
  return `
185
- <section class="block">
373
+ <section class="block"${id}>
186
374
  <div class="orig">${block.originalHtml}</div>
187
375
  <div class="trans">${warning}${translation}</div>
188
376
  </section>
189
377
  `
190
378
  }
191
379
 
192
- function renderDoc() {
380
+ function blockSignature(block) {
381
+ return [block.status, block.translation ?? '', block.warning ?? '', block.error ?? ''].join('\u0000')
382
+ }
383
+
384
+ function renderBlocksFull(doc) {
385
+ els.blocks.innerHTML = doc.blocks.map(renderBlock).join('')
386
+ rendered.docId = doc.id
387
+ rendered.signatures = doc.blocks.map(blockSignature)
388
+ }
389
+
390
+ /**
391
+ * Polling returns the whole document, but only a few blocks change per tick.
392
+ * Replacing just those sections avoids resetting scroll and text selection.
393
+ */
394
+ function updateBlocks(doc) {
395
+ if (rendered.docId !== doc.id || rendered.signatures.length !== doc.blocks.length) {
396
+ renderBlocksFull(doc)
397
+ return
398
+ }
399
+ const nodes = [...els.blocks.children]
400
+ doc.blocks.forEach((block, index) => {
401
+ const signature = blockSignature(block)
402
+ if (signature === rendered.signatures[index]) return
403
+ const node = nodes[index]
404
+ if (node === undefined) return
405
+ node.outerHTML = renderBlock(block)
406
+ rendered.signatures[index] = signature
407
+ })
408
+ }
409
+
410
+ function updateActiveDocItem(doc) {
411
+ const button = els.docs.querySelector(`[data-doc-id="${CSS.escape(doc.id)}"]`)
412
+ if (button === null) return
413
+ const sub = button.querySelector('.doc-item-sub')
414
+ if (sub === null) return
415
+ const percent = Math.round((doc.progress ?? 0) * 100)
416
+ sub.textContent = `${statusLabel(doc.status)} · ${percent}% · ${formatDate(doc.createdAt)}`
417
+ }
418
+
419
+ function renderDocChrome() {
193
420
  const doc = state.doc
194
421
  if (doc === null) {
195
422
  els.empty.hidden = false
196
423
  els.docView.hidden = true
197
- return
424
+ els.progressWrap.setAttribute('aria-valuenow', '0')
425
+ els.progressWrap.removeAttribute('aria-valuetext')
426
+ return false
198
427
  }
199
428
  els.empty.hidden = true
200
429
  els.docView.hidden = false
@@ -208,7 +437,10 @@ function renderDoc() {
208
437
  `请求 ${stats.requests ?? 0}`,
209
438
  ].filter(Boolean)
210
439
  els.meta.textContent = meta.join(' · ')
211
- els.progress.style.width = `${Math.round((doc.progress ?? 0) * 100)}%`
440
+ const percent = Math.round((doc.progress ?? 0) * 100)
441
+ els.progress.style.width = `${percent}%`
442
+ els.progressWrap.setAttribute('aria-valuenow', String(percent))
443
+ els.progressWrap.setAttribute('aria-valuetext', `${statusLabel(doc.status)} ${percent}%`)
212
444
  const failed = stats.failed ?? 0
213
445
  els.status.textContent = doc.error
214
446
  ? `${statusLabel(doc.status)} · ${doc.error}`
@@ -217,36 +449,79 @@ function renderDoc() {
217
449
  els.retry.hidden = !(failed > 0 || ['failed', 'partial', 'interrupted'].includes(doc.status))
218
450
  els.exportLink.href = `${API}/docs/${encodeURIComponent(doc.id)}/export`
219
451
  els.exportLink.setAttribute('download', `${doc.id}.bilingual.md`)
452
+ const canSaveToInbox = state.inboxAvailable && typeof doc.url === 'string' && doc.url.trim() !== ''
453
+ els.inboxLink.hidden = !canSaveToInbox
454
+ if (canSaveToInbox) {
455
+ els.inboxLink.href = `/dsh-reading-inbox/?clip=${encodeURIComponent(doc.url)}`
456
+ els.inboxLink.title = `在阅读箱中归档 ${doc.url}`
457
+ }
220
458
  els.blocks.className = `blocks view-${state.view}`
221
- els.blocks.innerHTML = doc.blocks.map(renderBlock).join('')
459
+ updateActiveDocItem(doc)
460
+ return true
461
+ }
462
+
463
+ async function detectReadingInbox() {
464
+ try {
465
+ const response = await fetch('/dsh-reading-inbox/api/health', { cache: 'no-store' })
466
+ state.inboxAvailable = response.ok
467
+ } catch {
468
+ state.inboxAvailable = false
469
+ }
470
+ if (state.doc !== null) renderDocChrome()
471
+ }
472
+
473
+ function renderDoc() {
474
+ if (!renderDocChrome()) return
475
+ renderBlocksFull(state.doc)
476
+ }
477
+
478
+ function updateDocView() {
479
+ if (!renderDocChrome()) return
480
+ updateBlocks(state.doc)
222
481
  }
223
482
 
224
483
  function setView(view) {
484
+ if (!VIEWS.has(view)) return
225
485
  state.view = view
226
486
  for (const button of $$('.view-switch button')) {
227
- button.classList.toggle('active', button.dataset.view === view)
487
+ const active = button.dataset.view === view
488
+ button.classList.toggle('active', active)
489
+ button.setAttribute('aria-pressed', String(active))
228
490
  }
229
491
  els.blocks.className = `blocks view-${view}`
492
+ try {
493
+ localStorage.setItem(VIEW_KEY, view)
494
+ } catch {
495
+ // Preference persistence is optional.
496
+ }
230
497
  }
231
498
 
232
- async function startRead(url) {
499
+ async function startDoc(path, body, progressNotice) {
233
500
  setBusy(true)
234
- showNotice('正在抓取正文…')
501
+ showNotice(progressNotice)
235
502
  try {
236
- const data = await api('/read', {
237
- method: 'POST',
238
- body: { url, targetLang: els.lang.value },
239
- })
503
+ const data = await api(path, { method: 'POST', body })
240
504
  showNotice('已开始翻译,完成后会自动刷新。')
241
505
  await loadDocs()
242
506
  await openDoc(data.doc.id)
507
+ return true
243
508
  } catch (error) {
244
509
  showNotice(error instanceof Error ? error.message : String(error), true)
510
+ return false
245
511
  } finally {
246
512
  setBusy(false)
247
513
  }
248
514
  }
249
515
 
516
+ function startRead(url) {
517
+ return startDoc('/read', { url, targetLang: els.lang.value }, '正在抓取正文…')
518
+ }
519
+
520
+ async function startText(text) {
521
+ const started = await startDoc('/read-text', { text, targetLang: els.lang.value }, '正在准备文本…')
522
+ if (started) els.text.value = ''
523
+ }
524
+
250
525
  async function retryDoc() {
251
526
  if (state.doc === null) return
252
527
  try {
@@ -258,11 +533,30 @@ async function retryDoc() {
258
533
  }
259
534
  }
260
535
 
536
+ async function retryBlock(blockId) {
537
+ if (state.doc === null) return
538
+ const id = state.doc.id
539
+ try {
540
+ await api(`/docs/${encodeURIComponent(id)}/blocks/${encodeURIComponent(blockId)}/retry`, { method: 'POST' })
541
+ await openDoc(id)
542
+ showNotice('已重试该段。')
543
+ } catch (error) {
544
+ showNotice(error instanceof Error ? error.message : String(error), true)
545
+ }
546
+ }
547
+
261
548
  async function deleteDoc() {
262
549
  if (state.doc === null) return
263
550
  if (!window.confirm(`删除《${state.doc.title}》?`)) return
264
551
  try {
265
- await api(`/docs/${encodeURIComponent(state.doc.id)}`, { method: 'DELETE' })
552
+ const id = state.doc.id
553
+ await api(`/docs/${encodeURIComponent(id)}`, { method: 'DELETE' })
554
+ try {
555
+ localStorage.removeItem(positionKey(id))
556
+ } catch {
557
+ // Position memory is optional.
558
+ }
559
+ forgetDoc(id)
266
560
  state.doc = null
267
561
  renderDoc()
268
562
  await loadDocs()
@@ -323,15 +617,61 @@ async function init() {
323
617
  } catch {
324
618
  els.docs.innerHTML = '<p class="sidebar-empty">读取最近文档失败。</p>'
325
619
  }
620
+ const params = new URLSearchParams(location.search)
621
+ const requestedDoc = params.get('doc')
622
+ if (requestedDoc !== null && requestedDoc.trim() !== '') {
623
+ try {
624
+ await openDoc(requestedDoc.trim())
625
+ } catch (error) {
626
+ showNotice(error instanceof Error ? error.message : String(error), true)
627
+ }
628
+ } else {
629
+ const lastDoc = storedLastDoc()
630
+ if (lastDoc !== null && state.docs.some(doc => doc.id === lastDoc)) {
631
+ await openDoc(lastDoc).catch(() => forgetDoc(lastDoc))
632
+ } else if (lastDoc !== null) {
633
+ forgetDoc(lastDoc)
634
+ }
635
+ }
636
+ const requestedUrl = params.get('url')
637
+ if (requestedDoc === null && requestedUrl !== null && /^https?:\/\//i.test(requestedUrl.trim())) {
638
+ const url = requestedUrl.trim()
639
+ setComposerMode('url')
640
+ els.url.value = url
641
+ showNotice('已填入链接,点击“读取并翻译”。')
642
+ if (params.get('start') === '1') void startRead(url)
643
+ }
644
+ void detectReadingInbox()
326
645
  }
327
646
 
328
647
  els.form.addEventListener('submit', event => {
329
648
  event.preventDefault()
649
+ if (state.busy) return
650
+ if (state.composerMode === 'text') {
651
+ const text = els.text.value.trim()
652
+ if (text === '') {
653
+ showNotice('请先粘贴要翻译的文本。', true)
654
+ return
655
+ }
656
+ void startText(text)
657
+ return
658
+ }
330
659
  const url = els.url.value.trim()
331
- if (url === '' || state.busy) return
660
+ if (url === '') return
332
661
  void startRead(url)
333
662
  })
334
663
 
664
+ for (const button of els.composerModes) {
665
+ button.addEventListener('click', () => setComposerMode(button.dataset.composeMode))
666
+ }
667
+
668
+ els.text.addEventListener('keydown', event => {
669
+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) {
670
+ event.preventDefault()
671
+ els.form.requestSubmit()
672
+ }
673
+ })
674
+
335
675
  els.refreshDocs.addEventListener('click', () => {
336
676
  void loadDocs().catch(error => showNotice(error.message, true))
337
677
  })
@@ -342,12 +682,39 @@ els.docs.addEventListener('click', event => {
342
682
  void openDoc(button.dataset.docId).catch(error => showNotice(error.message, true))
343
683
  })
344
684
 
685
+ els.blocks.addEventListener('click', event => {
686
+ const button = event.target.closest('[data-retry-block]')
687
+ if (button === null) return
688
+ void retryBlock(button.dataset.retryBlock)
689
+ })
690
+
345
691
  for (const button of $$('.view-switch button')) {
346
692
  button.addEventListener('click', () => setView(button.dataset.view))
347
693
  }
348
694
 
349
695
  els.retry.addEventListener('click', () => void retryDoc())
350
696
  els.delete.addEventListener('click', () => void deleteDoc())
697
+ els.printBtn.addEventListener('click', () => window.print())
698
+ els.copyBtn.addEventListener('click', async () => {
699
+ if (state.doc === null) return
700
+ const text = state.doc.blocks
701
+ .filter(block => block.translatable && block.translation)
702
+ .map(block => block.translation)
703
+ .join('\n\n')
704
+ if (text === '') {
705
+ showNotice('还没有可复制的译文。', true)
706
+ return
707
+ }
708
+ try {
709
+ await navigator.clipboard.writeText(text)
710
+ showNotice('已复制全部译文。')
711
+ } catch {
712
+ showNotice('复制失败,请手动选择文本。', true)
713
+ }
714
+ })
715
+ els.fontSmaller.addEventListener('click', () => stepFont(-1))
716
+ els.fontReset.addEventListener('click', () => applyFontScale(100))
717
+ els.fontLarger.addEventListener('click', () => stepFont(1))
351
718
 
352
719
  els.glossaryBtn.addEventListener('click', () => void openGlossary())
353
720
  els.glossaryClose.addEventListener('click', () => els.glossaryDialog.close())
@@ -355,6 +722,26 @@ els.glossaryDialog.addEventListener('click', event => {
355
722
  if (event.target === els.glossaryDialog) els.glossaryDialog.close()
356
723
  })
357
724
 
725
+ els.glossaryExport.href = `${API}/glossary/export`
726
+ els.glossaryImport.addEventListener('click', () => els.glossaryFile.click())
727
+ els.glossaryFile.addEventListener('change', async () => {
728
+ const file = els.glossaryFile.files?.[0]
729
+ if (file === undefined) return
730
+ try {
731
+ const parsed = JSON.parse(await file.text())
732
+ const terms = Array.isArray(parsed) ? parsed : parsed.terms
733
+ if (!Array.isArray(terms)) throw new Error('JSON 里没有 terms 数组')
734
+ const data = await api('/glossary/import', { method: 'POST', body: { terms } })
735
+ state.glossary = data.terms
736
+ renderGlossary()
737
+ showGlossaryNotice(`导入完成:新增 ${data.added},更新 ${data.updated},跳过 ${data.skipped}。`)
738
+ } catch (error) {
739
+ showGlossaryNotice(error instanceof Error ? error.message : String(error), true)
740
+ } finally {
741
+ els.glossaryFile.value = ''
742
+ }
743
+ })
744
+
358
745
  els.glossaryForm.addEventListener('submit', async event => {
359
746
  event.preventDefault()
360
747
  const source = els.termSource.value.trim()
@@ -393,8 +780,24 @@ els.glossaryList.addEventListener('click', async event => {
393
780
  }
394
781
  })
395
782
 
783
+ let scrollTimer = null
784
+ function scheduleScrollSave() {
785
+ if (state.doc === null || scrollTimer !== null) return
786
+ scrollTimer = setTimeout(() => {
787
+ scrollTimer = null
788
+ saveScroll()
789
+ }, 300)
790
+ }
791
+
792
+ window.addEventListener('scroll', scheduleScrollSave, { passive: true })
793
+ els.reader.addEventListener('scroll', scheduleScrollSave, { passive: true })
794
+
396
795
  window.addEventListener('beforeunload', () => {
397
796
  if (state.poll !== null) clearInterval(state.poll)
797
+ saveScroll()
398
798
  })
399
799
 
800
+ setView(state.view)
801
+ setComposerMode('url')
802
+ applyFontScale(state.fontScale, false)
400
803
  void init()