dsh-bilingual-reader 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.
package/web/app.js ADDED
@@ -0,0 +1,477 @@
1
+ const API = '/dsh-bilingual-reader/api'
2
+ const VIEW_KEY = 'dsh-bilingual-reader:view'
3
+ const VIEWS = new Set(['inline', 'bilingual', 'original', 'translation'])
4
+
5
+ const $ = (selector, root = document) => root.querySelector(selector)
6
+ const $$ = (selector, root = document) => [...root.querySelectorAll(selector)]
7
+
8
+ function storedView() {
9
+ try {
10
+ const value = localStorage.getItem(VIEW_KEY)
11
+ if (VIEWS.has(value)) return value
12
+ } catch {
13
+ // localStorage can be unavailable in hardened webviews; default is fine.
14
+ }
15
+ return 'inline'
16
+ }
17
+
18
+ const state = {
19
+ health: null,
20
+ docs: [],
21
+ doc: null,
22
+ view: storedView(),
23
+ poll: null,
24
+ busy: false,
25
+ glossary: [],
26
+ }
27
+
28
+ const rendered = {
29
+ docId: null,
30
+ signatures: [],
31
+ }
32
+
33
+ const els = {
34
+ form: $('#read-form'),
35
+ url: $('#url-input'),
36
+ lang: $('#lang-select'),
37
+ readBtn: $('#read-btn'),
38
+ aiHint: $('#ai-hint'),
39
+ notice: $('#notice'),
40
+ docs: $('#docs'),
41
+ refreshDocs: $('#refresh-docs'),
42
+ empty: $('#empty'),
43
+ docView: $('#doc-view'),
44
+ title: $('#doc-title'),
45
+ meta: $('#doc-meta'),
46
+ status: $('#doc-status'),
47
+ progress: $('#progress-bar'),
48
+ blocks: $('#blocks'),
49
+ exportLink: $('#export-link'),
50
+ retry: $('#retry-btn'),
51
+ delete: $('#delete-btn'),
52
+ glossaryBtn: $('#glossary-btn'),
53
+ glossaryCount: $('#glossary-count'),
54
+ glossaryDialog: $('#glossary-dialog'),
55
+ glossaryClose: $('#glossary-close'),
56
+ glossaryList: $('#glossary-list'),
57
+ glossaryForm: $('#glossary-form'),
58
+ termSource: $('#term-source'),
59
+ termTarget: $('#term-target'),
60
+ termNote: $('#term-note'),
61
+ glossaryNotice: $('#glossary-notice'),
62
+ }
63
+
64
+ function escapeHtml(value) {
65
+ return String(value ?? '')
66
+ .replaceAll('&', '&')
67
+ .replaceAll('<', '&lt;')
68
+ .replaceAll('>', '&gt;')
69
+ .replaceAll('"', '&quot;')
70
+ }
71
+
72
+ function escapeAttr(value) {
73
+ return escapeHtml(value).replaceAll("'", '&#39;')
74
+ }
75
+
76
+ async function api(path, options = {}) {
77
+ const headers = { ...(options.headers ?? {}) }
78
+ let body
79
+ if (options.body !== undefined) {
80
+ headers['content-type'] = 'application/json'
81
+ body = JSON.stringify(options.body)
82
+ }
83
+ const response = await fetch(`${API}${path}`, { ...options, headers, body })
84
+ const data = await response.json().catch(() => ({}))
85
+ if (!response.ok || data.ok === false) {
86
+ throw new Error(data.error || `HTTP ${response.status}`)
87
+ }
88
+ return data
89
+ }
90
+
91
+ function statusLabel(status) {
92
+ return {
93
+ pending: '待翻译',
94
+ running: '翻译中',
95
+ done: '已完成',
96
+ partial: '部分完成',
97
+ failed: '失败',
98
+ interrupted: '已中断',
99
+ }[status] ?? status
100
+ }
101
+
102
+ function formatDate(value) {
103
+ if (!value) return ''
104
+ const date = new Date(value)
105
+ if (Number.isNaN(date.getTime())) return ''
106
+ return `${date.getMonth() + 1}/${date.getDate()}`
107
+ }
108
+
109
+ function showNotice(message, isError = false) {
110
+ els.notice.textContent = message
111
+ els.notice.hidden = message === ''
112
+ els.notice.classList.toggle('error', isError)
113
+ }
114
+
115
+ function showGlossaryNotice(message, isError = false) {
116
+ els.glossaryNotice.textContent = message
117
+ els.glossaryNotice.hidden = message === ''
118
+ els.glossaryNotice.classList.toggle('error', isError)
119
+ }
120
+
121
+ function setBusy(busy) {
122
+ state.busy = busy
123
+ els.readBtn.disabled = busy
124
+ els.readBtn.textContent = busy ? '读取中…' : '读取并翻译'
125
+ }
126
+
127
+ function renderDocs() {
128
+ if (state.docs.length === 0) {
129
+ els.docs.innerHTML = '<p class="sidebar-empty">还没有文档。</p>'
130
+ return
131
+ }
132
+ els.docs.innerHTML = state.docs.map(doc => {
133
+ const active = state.doc?.id === doc.id ? ' active' : ''
134
+ const percent = Math.round((doc.progress ?? 0) * 100)
135
+ return `
136
+ <button type="button" class="doc-item${active}" data-doc-id="${escapeAttr(doc.id)}">
137
+ <span class="doc-item-title">${escapeHtml(doc.title)}</span>
138
+ <span class="doc-item-sub">${escapeHtml(statusLabel(doc.status))} · ${percent}% · ${escapeHtml(formatDate(doc.createdAt))}</span>
139
+ </button>
140
+ `
141
+ }).join('')
142
+ }
143
+
144
+ async function loadDocs() {
145
+ const data = await api('/docs?limit=30')
146
+ state.docs = data.docs
147
+ renderDocs()
148
+ }
149
+
150
+ function startPolling() {
151
+ if (state.poll !== null) clearInterval(state.poll)
152
+ state.poll = null
153
+ if (state.doc === null) return
154
+ if (!['pending', 'running'].includes(state.doc.status)) return
155
+ state.poll = setInterval(async () => {
156
+ if (state.doc === null) return
157
+ try {
158
+ const data = await api(`/docs/${encodeURIComponent(state.doc.id)}`)
159
+ state.doc = data.doc
160
+ updateDocView()
161
+ if (!['pending', 'running'].includes(state.doc.status)) {
162
+ clearInterval(state.poll)
163
+ state.poll = null
164
+ await loadDocs()
165
+ }
166
+ } catch {
167
+ clearInterval(state.poll)
168
+ state.poll = null
169
+ }
170
+ }, 900)
171
+ }
172
+
173
+ async function openDoc(id) {
174
+ const data = await api(`/docs/${encodeURIComponent(id)}`)
175
+ state.doc = data.doc
176
+ renderDoc()
177
+ renderDocs()
178
+ startPolling()
179
+ }
180
+
181
+ function blockPlaceholder(block) {
182
+ if (block.status === 'failed') {
183
+ return `<p class="placeholder error">翻译失败${block.error ? `:${escapeHtml(block.error)}` : ''}</p>`
184
+ }
185
+ return '<p class="placeholder">待翻译</p>'
186
+ }
187
+
188
+ function renderBlock(block) {
189
+ const id = ` data-block-id="${escapeAttr(block.id)}"`
190
+ if (block.type === 'code' || block.type === 'hr') {
191
+ return `<section class="block block-code"${id}>${block.originalHtml}</section>`
192
+ }
193
+ if (block.translatable !== true) {
194
+ return `<section class="block block-plain"${id}>${block.originalHtml}</section>`
195
+ }
196
+ const warning = block.warning
197
+ ? `<span class="badge warn" title="${escapeAttr(block.warning)}">保护片段丢失</span>`
198
+ : ''
199
+ const translation = block.translationHtml
200
+ ? block.translationHtml
201
+ : blockPlaceholder(block)
202
+ return `
203
+ <section class="block"${id}>
204
+ <div class="orig">${block.originalHtml}</div>
205
+ <div class="trans">${warning}${translation}</div>
206
+ </section>
207
+ `
208
+ }
209
+
210
+ function blockSignature(block) {
211
+ return [block.status, block.translation ?? '', block.warning ?? '', block.error ?? ''].join('\u0000')
212
+ }
213
+
214
+ function renderBlocksFull(doc) {
215
+ els.blocks.innerHTML = doc.blocks.map(renderBlock).join('')
216
+ rendered.docId = doc.id
217
+ rendered.signatures = doc.blocks.map(blockSignature)
218
+ }
219
+
220
+ /**
221
+ * Polling returns the whole document, but only a few blocks change per tick.
222
+ * Replacing just those sections avoids resetting scroll and text selection.
223
+ */
224
+ function updateBlocks(doc) {
225
+ if (rendered.docId !== doc.id || rendered.signatures.length !== doc.blocks.length) {
226
+ renderBlocksFull(doc)
227
+ return
228
+ }
229
+ const nodes = [...els.blocks.children]
230
+ doc.blocks.forEach((block, index) => {
231
+ const signature = blockSignature(block)
232
+ if (signature === rendered.signatures[index]) return
233
+ const node = nodes[index]
234
+ if (node === undefined) return
235
+ node.outerHTML = renderBlock(block)
236
+ rendered.signatures[index] = signature
237
+ })
238
+ }
239
+
240
+ function updateActiveDocItem(doc) {
241
+ const button = els.docs.querySelector(`[data-doc-id="${CSS.escape(doc.id)}"]`)
242
+ if (button === null) return
243
+ const sub = button.querySelector('.doc-item-sub')
244
+ if (sub === null) return
245
+ const percent = Math.round((doc.progress ?? 0) * 100)
246
+ sub.textContent = `${statusLabel(doc.status)} · ${percent}% · ${formatDate(doc.createdAt)}`
247
+ }
248
+
249
+ function renderDocChrome() {
250
+ const doc = state.doc
251
+ if (doc === null) {
252
+ els.empty.hidden = false
253
+ els.docView.hidden = true
254
+ return false
255
+ }
256
+ els.empty.hidden = true
257
+ els.docView.hidden = false
258
+ els.title.textContent = doc.title
259
+ const stats = doc.stats ?? {}
260
+ const meta = [
261
+ doc.siteName,
262
+ doc.targetLang,
263
+ `${stats.done ?? 0}/${stats.translatable ?? 0} 段`,
264
+ `缓存 ${stats.cached ?? 0}`,
265
+ `请求 ${stats.requests ?? 0}`,
266
+ ].filter(Boolean)
267
+ els.meta.textContent = meta.join(' · ')
268
+ els.progress.style.width = `${Math.round((doc.progress ?? 0) * 100)}%`
269
+ const failed = stats.failed ?? 0
270
+ els.status.textContent = doc.error
271
+ ? `${statusLabel(doc.status)} · ${doc.error}`
272
+ : `${statusLabel(doc.status)} · ${Math.round((doc.progress ?? 0) * 100)}%`
273
+ els.status.classList.toggle('error', ['failed', 'partial', 'interrupted'].includes(doc.status))
274
+ els.retry.hidden = !(failed > 0 || ['failed', 'partial', 'interrupted'].includes(doc.status))
275
+ els.exportLink.href = `${API}/docs/${encodeURIComponent(doc.id)}/export`
276
+ els.exportLink.setAttribute('download', `${doc.id}.bilingual.md`)
277
+ els.blocks.className = `blocks view-${state.view}`
278
+ updateActiveDocItem(doc)
279
+ return true
280
+ }
281
+
282
+ function renderDoc() {
283
+ if (!renderDocChrome()) return
284
+ renderBlocksFull(state.doc)
285
+ }
286
+
287
+ function updateDocView() {
288
+ if (!renderDocChrome()) return
289
+ updateBlocks(state.doc)
290
+ }
291
+
292
+ function setView(view) {
293
+ if (!VIEWS.has(view)) return
294
+ state.view = view
295
+ for (const button of $$('.view-switch button')) {
296
+ const active = button.dataset.view === view
297
+ button.classList.toggle('active', active)
298
+ button.setAttribute('aria-pressed', String(active))
299
+ }
300
+ els.blocks.className = `blocks view-${view}`
301
+ try {
302
+ localStorage.setItem(VIEW_KEY, view)
303
+ } catch {
304
+ // Preference persistence is optional.
305
+ }
306
+ }
307
+
308
+ async function startRead(url) {
309
+ setBusy(true)
310
+ showNotice('正在抓取正文…')
311
+ try {
312
+ const data = await api('/read', {
313
+ method: 'POST',
314
+ body: { url, targetLang: els.lang.value },
315
+ })
316
+ showNotice('已开始翻译,完成后会自动刷新。')
317
+ await loadDocs()
318
+ await openDoc(data.doc.id)
319
+ } catch (error) {
320
+ showNotice(error instanceof Error ? error.message : String(error), true)
321
+ } finally {
322
+ setBusy(false)
323
+ }
324
+ }
325
+
326
+ async function retryDoc() {
327
+ if (state.doc === null) return
328
+ try {
329
+ await api(`/docs/${encodeURIComponent(state.doc.id)}/retry`, { method: 'POST' })
330
+ await openDoc(state.doc.id)
331
+ showNotice('已重新开始翻译失败段落。')
332
+ } catch (error) {
333
+ showNotice(error instanceof Error ? error.message : String(error), true)
334
+ }
335
+ }
336
+
337
+ async function deleteDoc() {
338
+ if (state.doc === null) return
339
+ if (!window.confirm(`删除《${state.doc.title}》?`)) return
340
+ try {
341
+ await api(`/docs/${encodeURIComponent(state.doc.id)}`, { method: 'DELETE' })
342
+ state.doc = null
343
+ renderDoc()
344
+ await loadDocs()
345
+ showNotice('已删除。')
346
+ } catch (error) {
347
+ showNotice(error instanceof Error ? error.message : String(error), true)
348
+ }
349
+ }
350
+
351
+ function renderGlossary() {
352
+ els.glossaryCount.textContent = String(state.glossary.length)
353
+ if (state.glossary.length === 0) {
354
+ els.glossaryList.innerHTML = '<p class="sidebar-empty">术语表为空。</p>'
355
+ return
356
+ }
357
+ els.glossaryList.innerHTML = state.glossary.map(term => `
358
+ <div class="glossary-item">
359
+ <span class="glossary-term">${escapeHtml(term.source)}</span>
360
+ <span class="glossary-arrow">→</span>
361
+ <span class="glossary-target">${escapeHtml(term.target)}</span>
362
+ ${term.note ? `<span class="glossary-note">${escapeHtml(term.note)}</span>` : ''}
363
+ <button type="button" class="icon-button glossary-remove" data-source="${escapeAttr(term.source)}" title="删除">×</button>
364
+ </div>
365
+ `).join('')
366
+ }
367
+
368
+ async function openGlossary() {
369
+ try {
370
+ const data = await api('/glossary')
371
+ state.glossary = data.terms
372
+ renderGlossary()
373
+ showGlossaryNotice('')
374
+ els.glossaryDialog.showModal()
375
+ } catch (error) {
376
+ showNotice(error instanceof Error ? error.message : String(error), true)
377
+ }
378
+ }
379
+
380
+ async function init() {
381
+ try {
382
+ const health = await api('/health')
383
+ state.health = health
384
+ els.lang.innerHTML = health.languages
385
+ .map(language => `<option value="${escapeAttr(language.code)}">${escapeHtml(language.label)}</option>`)
386
+ .join('')
387
+ els.lang.value = health.targetLang
388
+ els.glossaryCount.textContent = String(health.glossary)
389
+ els.aiHint.textContent = health.ai
390
+ ? '使用 DSH 默认模型翻译;内容、术语表和缓存都保存在本机。'
391
+ : '没有检测到可用的 DSH 默认模型;配置模型后才能翻译,已翻译的文档仍可浏览。'
392
+ els.aiHint.classList.toggle('error', health.ai !== true)
393
+ } catch (error) {
394
+ els.aiHint.textContent = `无法连接插件:${error instanceof Error ? error.message : String(error)}`
395
+ els.aiHint.classList.add('error')
396
+ }
397
+ try {
398
+ await loadDocs()
399
+ } catch {
400
+ els.docs.innerHTML = '<p class="sidebar-empty">读取最近文档失败。</p>'
401
+ }
402
+ }
403
+
404
+ els.form.addEventListener('submit', event => {
405
+ event.preventDefault()
406
+ const url = els.url.value.trim()
407
+ if (url === '' || state.busy) return
408
+ void startRead(url)
409
+ })
410
+
411
+ els.refreshDocs.addEventListener('click', () => {
412
+ void loadDocs().catch(error => showNotice(error.message, true))
413
+ })
414
+
415
+ els.docs.addEventListener('click', event => {
416
+ const button = event.target.closest('[data-doc-id]')
417
+ if (button === null) return
418
+ void openDoc(button.dataset.docId).catch(error => showNotice(error.message, true))
419
+ })
420
+
421
+ for (const button of $$('.view-switch button')) {
422
+ button.addEventListener('click', () => setView(button.dataset.view))
423
+ }
424
+
425
+ els.retry.addEventListener('click', () => void retryDoc())
426
+ els.delete.addEventListener('click', () => void deleteDoc())
427
+
428
+ els.glossaryBtn.addEventListener('click', () => void openGlossary())
429
+ els.glossaryClose.addEventListener('click', () => els.glossaryDialog.close())
430
+ els.glossaryDialog.addEventListener('click', event => {
431
+ if (event.target === els.glossaryDialog) els.glossaryDialog.close()
432
+ })
433
+
434
+ els.glossaryForm.addEventListener('submit', async event => {
435
+ event.preventDefault()
436
+ const source = els.termSource.value.trim()
437
+ const target = els.termTarget.value.trim()
438
+ if (source === '' || target === '') return
439
+ try {
440
+ const data = await api('/glossary', {
441
+ method: 'POST',
442
+ body: { action: 'add', source, target, note: els.termNote.value.trim() },
443
+ })
444
+ state.glossary = data.terms
445
+ renderGlossary()
446
+ els.termSource.value = ''
447
+ els.termTarget.value = ''
448
+ els.termNote.value = ''
449
+ els.termSource.focus()
450
+ showGlossaryNotice('已添加。')
451
+ } catch (error) {
452
+ showGlossaryNotice(error instanceof Error ? error.message : String(error), true)
453
+ }
454
+ })
455
+
456
+ els.glossaryList.addEventListener('click', async event => {
457
+ const button = event.target.closest('.glossary-remove')
458
+ if (button === null) return
459
+ try {
460
+ const data = await api('/glossary', {
461
+ method: 'POST',
462
+ body: { action: 'remove', source: button.dataset.source },
463
+ })
464
+ state.glossary = data.terms
465
+ renderGlossary()
466
+ showGlossaryNotice('已删除。')
467
+ } catch (error) {
468
+ showGlossaryNotice(error instanceof Error ? error.message : String(error), true)
469
+ }
470
+ })
471
+
472
+ window.addEventListener('beforeunload', () => {
473
+ if (state.poll !== null) clearInterval(state.poll)
474
+ })
475
+
476
+ setView(state.view)
477
+ void init()
@@ -0,0 +1,5 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <rect width="64" height="64" rx="16" fill="#2f6f4f"/>
3
+ <path d="M14 18h24v4H27v4h9c-1 8-4 13-9 17l-3-3c4-3 6-7 7-14h-4c-1 5-4 9-9 12l-2-3c5-3 7-6 8-9h-9v-4h12v-4H14z" fill="#fff"/>
4
+ <path d="M42 20h5l8 24h-5l-1.7-6h-8.6L38 44h-5l9-24zm-1.2 14h5.4L43.5 26z" fill="#d9efe2"/>
5
+ </svg>
package/web/index.html ADDED
@@ -0,0 +1,99 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>双语阅读 · DSH</title>
7
+ <link rel="icon" href="./favicon.svg" type="image/svg+xml">
8
+ <link rel="stylesheet" href="./style.css">
9
+ </head>
10
+ <body>
11
+ <div id="app">
12
+ <header class="topbar">
13
+ <div class="brand">
14
+ <span class="brand-mark" aria-hidden="true">译</span>
15
+ <div>
16
+ <h1>双语阅读</h1>
17
+ <p>网页与文档的结构化双语对照 · 术语表 · 缓存</p>
18
+ </div>
19
+ </div>
20
+ <div class="top-actions">
21
+ <button type="button" id="glossary-btn" class="button ghost">术语表 <span id="glossary-count">0</span></button>
22
+ </div>
23
+ </header>
24
+
25
+ <section class="composer">
26
+ <form id="read-form" autocomplete="off">
27
+ <input id="url-input" type="url" placeholder="粘贴网页链接,例如 https://example.com/article" required>
28
+ <select id="lang-select" aria-label="目标语言"></select>
29
+ <button type="submit" id="read-btn" class="button primary">读取并翻译</button>
30
+ </form>
31
+ <p class="hint" id="ai-hint">正在检查模型…</p>
32
+ <p class="notice" id="notice" role="status" hidden></p>
33
+ </section>
34
+
35
+ <main class="layout">
36
+ <aside class="sidebar" aria-label="最近文档">
37
+ <div class="sidebar-head">
38
+ <h2>最近</h2>
39
+ <button type="button" id="refresh-docs" class="icon-button" title="刷新">↻</button>
40
+ </div>
41
+ <div id="docs" class="docs"></div>
42
+ </aside>
43
+
44
+ <section class="reader" aria-label="阅读区">
45
+ <div id="empty" class="empty-state">
46
+ <div class="empty-mark" aria-hidden="true">译</div>
47
+ <h2>把网页读成双语</h2>
48
+ <p>粘贴一个公开文章链接,或让 Agent 调用 <code>bilingual_read_url</code>。代码、公式、链接和表格保持原样,只翻译正文。</p>
49
+ <ul>
50
+ <li>上下 / 对照 / 原文 / 译文四种视图</li>
51
+ <li>术语表 + 内容哈希缓存,重复段落不再调用模型</li>
52
+ <li>导出双语 Markdown,保留标题层级与代码块</li>
53
+ </ul>
54
+ </div>
55
+
56
+ <div id="doc-view" class="doc-view" hidden>
57
+ <div class="doc-head">
58
+ <div class="doc-heading">
59
+ <h2 id="doc-title"></h2>
60
+ <div class="doc-meta" id="doc-meta"></div>
61
+ </div>
62
+ <div class="doc-actions">
63
+ <div class="view-switch" role="group" aria-label="视图">
64
+ <button type="button" data-view="inline" class="active">上下</button>
65
+ <button type="button" data-view="bilingual">对照</button>
66
+ <button type="button" data-view="original">原文</button>
67
+ <button type="button" data-view="translation">译文</button>
68
+ </div>
69
+ <a id="export-link" class="button" href="#" download>导出双语 Markdown</a>
70
+ <button type="button" id="retry-btn" class="button" hidden>重试失败段</button>
71
+ <button type="button" id="delete-btn" class="button danger">删除</button>
72
+ </div>
73
+ </div>
74
+ <div class="progress" aria-hidden="true"><div id="progress-bar"></div></div>
75
+ <p class="doc-status" id="doc-status"></p>
76
+ <article id="blocks" class="blocks view-inline"></article>
77
+ </div>
78
+ </section>
79
+ </main>
80
+
81
+ <dialog id="glossary-dialog" class="dialog">
82
+ <div class="dialog-head">
83
+ <h2>术语表</h2>
84
+ <button type="button" id="glossary-close" class="icon-button" aria-label="关闭">×</button>
85
+ </div>
86
+ <p class="dialog-hint">翻译时会强制使用这些译法。示例:token → 令牌。</p>
87
+ <div id="glossary-list" class="glossary-list"></div>
88
+ <form id="glossary-form" class="glossary-form" autocomplete="off">
89
+ <input id="term-source" type="text" placeholder="原文术语" required maxlength="80">
90
+ <input id="term-target" type="text" placeholder="译法" required maxlength="80">
91
+ <input id="term-note" type="text" placeholder="备注(可选)" maxlength="160">
92
+ <button type="submit" class="button primary">添加</button>
93
+ </form>
94
+ <p class="notice" id="glossary-notice" role="status" hidden></p>
95
+ </dialog>
96
+ </div>
97
+ <script src="./app.js"></script>
98
+ </body>
99
+ </html>