dsh-reading-inbox 0.2.1 → 0.4.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,785 +1,1014 @@
1
- const $ = (selector, root = document) => root.querySelector(selector)
2
-
3
- const state = {
4
- q: '',
5
- status: 'all',
6
- tag: '',
7
- items: [],
8
- total: 0,
9
- selected: null,
10
- stats: null,
11
- listToken: 0,
12
- selection: null,
13
- selectionColor: 'yellow',
14
- }
15
-
16
- const ANNOTATION_COLORS = ['yellow', 'green', 'blue', 'red']
17
-
18
- const els = {
19
- layout: $('#layout'),
20
- list: $('#list'),
21
- detail: $('#detail'),
22
- search: $('#search'),
23
- tabs: $('#tabs'),
24
- stats: $('#stats'),
25
- clipForm: $('#clip-form'),
26
- clipUrl: $('#clip-url'),
27
- clipTags: $('#clip-tags'),
28
- clipSubmit: $('#clip-submit'),
29
- tagFilter: $('#tag-filter'),
30
- tagFilterName: $('#tag-filter-name'),
31
- tagClear: $('#tag-clear'),
32
- selectionToolbar: $('#selection-toolbar'),
33
- selectionQuote: $('#selection-quote'),
34
- selectionNote: $('#selection-note'),
35
- toast: $('#toast'),
36
- }
37
-
38
- function codePointLength(value) {
39
- return Array.from(String(value ?? '')).length
40
- }
41
-
42
- function codePointSlice(value, start, end) {
43
- return Array.from(String(value ?? '')).slice(start, end).join('')
44
- }
45
-
46
- function codePointToUtf16(value, index) {
47
- let codePoints = 0
48
- let offset = 0
49
- while (offset < value.length && codePoints < index) {
50
- const code = value.charCodeAt(offset)
51
- if (code >= 0xd800 && code <= 0xdbff && offset + 1 < value.length) offset += 1
52
- offset += 1
53
- codePoints += 1
54
- }
55
- return offset
56
- }
57
-
58
- function escapeHtml(value) {
59
- return String(value ?? '')
60
- .replaceAll('&', '&amp;')
61
- .replaceAll('<', '&lt;')
62
- .replaceAll('>', '&gt;')
63
- .replaceAll('"', '&quot;')
64
- .replaceAll("'", '&#39;')
65
- }
66
-
67
- function escapeAttr(value) {
68
- return escapeHtml(value).replaceAll('`', '&#96;')
69
- }
70
-
71
- function fmtDate(value) {
72
- if (!value) return ''
73
- const date = new Date(value)
74
- if (Number.isNaN(date.getTime())) return ''
75
- return new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(date)
76
- }
77
-
78
- function fmtWords(value) {
79
- const number = Number(value) || 0
80
- return number >= 10_000 ? `${(number / 10_000).toFixed(1)} 万字` : `${number} 字`
81
- }
82
-
83
- function statusLabel(status) {
84
- return { unread: '未读', reading: '在读', read: '已读', archived: '归档' }[status] ?? status
85
- }
86
-
87
- let toastTimer
88
- function toast(message, isError = false) {
89
- clearTimeout(toastTimer)
90
- els.toast.textContent = message
91
- els.toast.classList.toggle('error', isError)
92
- els.toast.hidden = false
93
- toastTimer = setTimeout(() => { els.toast.hidden = true }, 2800)
94
- }
95
-
96
- async function api(path, options = {}) {
97
- const response = await fetch(`./api${path}`, {
98
- credentials: 'same-origin',
99
- ...options,
100
- headers: {
101
- ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
102
- ...(options.headers ?? {}),
103
- },
104
- })
105
- let body = null
106
- try {
107
- body = await response.json()
108
- } catch {
109
- body = null
110
- }
111
- if (!response.ok || body?.ok === false) {
112
- throw new Error(body?.error || `请求失败:HTTP ${response.status}`)
113
- }
114
- return body
115
- }
116
-
117
- function tagButton(tag) {
118
- return `<button type="button" class="tag" data-tag="${escapeAttr(tag)}">${escapeHtml(tag)}</button>`
119
- }
120
-
121
- function updateTabs() {
122
- for (const tab of els.tabs.querySelectorAll('[data-status]')) {
123
- tab.classList.toggle('active', tab.dataset.status === state.status)
124
- }
125
- const stats = state.stats
126
- if (stats !== null) {
127
- $('#count-all').textContent = String(stats.all ?? 0)
128
- $('#count-unread').textContent = String(stats.unread ?? 0)
129
- $('#count-reading').textContent = String(stats.reading ?? 0)
130
- $('#count-read').textContent = String(stats.read ?? 0)
131
- $('#count-archived').textContent = String(stats.archived ?? 0)
132
- els.stats.textContent = `共 ${stats.all ?? 0} 篇 · 未读 ${stats.unread ?? 0} · 在读 ${stats.reading ?? 0} · 已读 ${stats.read ?? 0} · 归档 ${stats.archived ?? 0}`
133
- }
134
- }
135
-
136
- async function loadStats() {
137
- try {
138
- const data = await api('/stats')
139
- state.stats = data
140
- updateTabs()
141
- if (data.warnings?.length) toast(data.warnings[0], true)
142
- } catch (error) {
143
- toast(error.message, true)
144
- }
145
- }
146
-
147
- function renderListLoading() {
148
- els.list.replaceChildren(...Array.from({ length: 4 }, () => {
149
- const skeleton = document.createElement('div')
150
- skeleton.className = 'skeleton'
151
- return skeleton
152
- }))
153
- }
154
-
155
- function emptyListMessage() {
156
- if (state.q !== '') return `没有找到包含“${state.q}”的文章。`
157
- if (state.tag !== '') return `没有标签为“${state.tag}”的文章。`
158
- if (state.status === 'unread') return '收件箱是空的。把网页链接粘贴到上方开始收藏。'
159
- if (state.status === 'reading') return '没有正在读的文章。'
160
- if (state.status === 'archived') return '还没有归档的文章。'
161
- return '还没有文章。粘贴一个网页链接开始。'
162
- }
163
-
164
- function renderList() {
165
- if (state.items.length === 0) {
166
- const empty = document.createElement('div')
167
- empty.className = 'list-empty'
168
- empty.textContent = emptyListMessage()
169
- els.list.replaceChildren(empty)
170
- return
171
- }
172
-
173
- const fragment = document.createDocumentFragment()
174
- for (const item of state.items) {
175
- const article = document.createElement('article')
176
- article.className = 'item'
177
- if (state.selected?.id === item.id) article.classList.add('selected')
178
- article.dataset.id = item.id
179
- article.tabIndex = 0
180
- article.setAttribute('role', 'button')
181
- article.innerHTML = `
182
- <div class="item-top">
183
- <span class="site">${escapeHtml(item.site || item.url)}</span>
184
- <time>${fmtDate(item.clippedAt)}</time>
185
- </div>
186
- <h3>${escapeHtml(item.title)}</h3>
187
- <p class="excerpt">${escapeHtml(item.excerpt || '')}</p>
188
- <div class="item-bottom">
189
- <span class="status-dot ${escapeAttr(item.status)}"></span>
190
- <span>${statusLabel(item.status)}</span>
191
- <span>·</span>
192
- <span>${fmtWords(item.wordCount)}</span>
193
- ${item.annotationCount > 0 ? `<span>·</span><span>${item.annotationCount} 批注</span>` : ''}
194
- ${item.tags.slice(0, 3).map(tagButton).join('')}
195
- </div>
196
- `
197
- fragment.append(article)
198
- }
199
- els.list.replaceChildren(fragment)
200
- }
201
-
202
- async function loadList() {
203
- const token = ++state.listToken
204
- renderListLoading()
205
- const params = new URLSearchParams({ status: state.status, limit: '100' })
206
- if (state.q !== '') params.set('q', state.q)
207
- if (state.tag !== '') params.set('tag', state.tag)
208
-
209
- try {
210
- const data = await api(`/items?${params.toString()}`)
211
- if (token !== state.listToken) return
212
- state.items = data.items
213
- state.total = data.total
214
- renderList()
215
- } catch (error) {
216
- if (token !== state.listToken) return
217
- const failed = document.createElement('div')
218
- failed.className = 'list-empty'
219
- failed.textContent = error.message
220
- els.list.replaceChildren(failed)
221
- toast(error.message, true)
222
- }
223
- }
224
-
225
- function updateSelectedInList() {
226
- for (const element of els.list.querySelectorAll('.item')) {
227
- element.classList.toggle('selected', element.dataset.id === state.selected?.id)
228
- }
229
- }
230
-
231
- function annotationColorButtons(current, annotationId) {
232
- return ANNOTATION_COLORS.map(color => `
233
- <button type="button" class="color-dot ${color}${color === current ? ' active' : ''}"
234
- data-action="annotation-color" data-color="${color}" data-annotation-id="${escapeAttr(annotationId)}"
235
- aria-label="${color}"></button>`).join('')
236
- }
237
-
238
- function renderAnnotationSection(annotations) {
239
- const list = Array.isArray(annotations) ? annotations : []
240
- const items = list.map(annotation => {
241
- const stale = annotation.status === 'stale'
242
- return `
243
- <article class="annotation-item${stale ? ' stale' : ''}" data-annotation-id="${escapeAttr(annotation.id)}">
244
- <div class="annotation-top">
245
- <span class="color-dot ${escapeAttr(annotation.color || 'yellow')}"></span>
246
- <span class="annotation-status">${stale ? '原文已变化,未能定位' : '已定位'}</span>
247
- <span class="annotation-spacer"></span>
248
- ${stale ? '' : '<button type="button" class="button small" data-action="jump-annotation">定位</button>'}
249
- <button type="button" class="button small danger" data-action="delete-annotation">删除</button>
250
- </div>
251
- <blockquote>${escapeHtml(annotation.quote)}</blockquote>
252
- <div class="annotation-note-row">
253
- <input class="annotation-note" data-annotation-id="${escapeAttr(annotation.id)}"
254
- value="${escapeAttr(annotation.note || '')}" placeholder="写批注…" maxlength="2000">
255
- <button type="button" class="button small" data-action="save-annotation-note">保存</button>
256
- </div>
257
- <div class="annotation-colors">${annotationColorButtons(annotation.color || 'yellow', annotation.id)}</div>
258
- </article>`
259
- }).join('')
260
- return `
261
- <section class="annotation-section" id="annotations">
262
- <div class="annotation-head">
263
- <h3>批注 <span>${list.length}</span></h3>
264
- <p>${list.length === 0 ? '选中正文文字即可高亮、写批注。' : '点击批注定位到原文;导出 Markdown 时会一起带上。'}</p>
265
- </div>
266
- ${items || '<div class="annotation-empty">还没有批注。</div>'}
267
- </section>`
268
- }
269
-
270
- function wrapCodePointRange(root, start, end, annotation) {
271
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
272
- const nodes = []
273
- let position = 0
274
- let node
275
- while ((node = walker.nextNode()) !== null) {
276
- const length = codePointLength(node.data)
277
- nodes.push({ node, start: position, end: position + length })
278
- position += length
279
- }
280
-
281
- for (const entry of nodes) {
282
- if (entry.end <= start || entry.start >= end) continue
283
- const localStart = Math.max(0, start - entry.start)
284
- const localEnd = Math.min(entry.end - entry.start, end - entry.start)
285
- if (localEnd <= localStart) continue
286
-
287
- let target = entry.node
288
- const utf16Start = codePointToUtf16(target.data, localStart)
289
- const utf16End = codePointToUtf16(target.data, localEnd)
290
- if (utf16Start > 0) target = target.splitText(utf16Start)
291
- if (utf16End - utf16Start < target.data.length) target.splitText(utf16End - utf16Start)
292
- if (target.data === '') continue
293
-
294
- const mark = document.createElement('mark')
295
- mark.className = `hl hl-${annotation.color || 'yellow'}`
296
- mark.dataset.annotationId = annotation.id
297
- if (annotation.note) mark.title = annotation.note
298
- target.parentNode.insertBefore(mark, target)
299
- mark.append(target)
300
- }
301
- }
302
-
303
- function applyHighlights(root, annotations) {
304
- if (!root) return
305
- const active = (Array.isArray(annotations) ? annotations : [])
306
- .filter(annotation => annotation.status !== 'stale' && annotation.startOffset >= 0 && annotation.endOffset > annotation.startOffset)
307
- .sort((a, b) => a.startOffset - b.startOffset)
308
- for (const annotation of active) {
309
- wrapCodePointRange(root, annotation.startOffset, annotation.endOffset, annotation)
310
- }
311
- }
312
-
313
- function focusAnnotation(annotationId) {
314
- const target = els.detail.querySelector(`.annotation-item[data-annotation-id="${CSS.escape(annotationId)}"]`)
315
- if (target === null) return
316
- target.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
317
- target.classList.add('pulse')
318
- setTimeout(() => target.classList.remove('pulse'), 1200)
319
- }
320
-
321
- function scrollToAnnotation(annotationId) {
322
- const mark = els.detail.querySelector(`.article mark[data-annotation-id="${CSS.escape(annotationId)}"]`)
323
- if (mark === null) {
324
- focusAnnotation(annotationId)
325
- return
326
- }
327
- mark.scrollIntoView({ block: 'center', behavior: 'smooth' })
328
- mark.classList.add('pulse')
329
- setTimeout(() => mark.classList.remove('pulse'), 1200)
330
- }
331
-
332
- function hideSelectionToolbar() {
333
- if (!els.selectionToolbar) return
334
- els.selectionToolbar.hidden = true
335
- state.selection = null
336
- state.selectionColor = 'yellow'
337
- if (els.selectionNote) els.selectionNote.value = ''
338
- }
339
-
340
- function captureSelection() {
341
- const article = els.detail.querySelector('.article')
342
- if (!article) return null
343
- const selection = window.getSelection()
344
- if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
345
- const range = selection.getRangeAt(0)
346
- if (!article.contains(range.startContainer) || !article.contains(range.endContainer)) return null
347
-
348
- const fullText = article.textContent
349
- const before = document.createRange()
350
- before.selectNodeContents(article)
351
- before.setEnd(range.startContainer, range.startOffset)
352
- const after = document.createRange()
353
- after.selectNodeContents(article)
354
- after.setStart(range.endContainer, range.endOffset)
355
-
356
- let start = codePointLength(before.toString())
357
- let end = codePointLength(fullText) - codePointLength(after.toString())
358
- if (end <= start) return null
359
-
360
- while (start < end && /\s/.test(codePointSlice(fullText, start, start + 1))) start += 1
361
- while (end > start && /\s/.test(codePointSlice(fullText, end - 1, end))) end -= 1
362
- const quote = codePointSlice(fullText, start, end)
363
- if (quote.trim() === '') return null
364
-
365
- return {
366
- quote,
367
- startOffset: start,
368
- endOffset: end,
369
- prefix: codePointSlice(fullText, Math.max(0, start - 32), start),
370
- suffix: codePointSlice(fullText, end, end + 32),
371
- rect: range.getBoundingClientRect(),
372
- }
373
- }
374
-
375
- function showSelectionToolbar(selection) {
376
- if (!els.selectionToolbar) return
377
- state.selection = selection
378
- state.selectionColor = 'yellow'
379
- els.selectionQuote.textContent = `“${selection.quote.slice(0, 140)}${selection.quote.length > 140 ? '…' : ''}”`
380
- els.selectionNote.value = ''
381
- for (const dot of els.selectionToolbar.querySelectorAll('[data-color]')) {
382
- dot.classList.toggle('active', dot.dataset.color === 'yellow')
383
- }
384
- els.selectionToolbar.hidden = false
385
- const width = els.selectionToolbar.offsetWidth
386
- const height = els.selectionToolbar.offsetHeight
387
- const rect = selection.rect
388
- const left = Math.min(
389
- Math.max(8, rect.left + rect.width / 2 - width / 2),
390
- window.innerWidth - width - 8,
391
- )
392
- const top = rect.bottom + height + 12 > window.innerHeight
393
- ? Math.max(8, rect.top - height - 8)
394
- : rect.bottom + 8
395
- els.selectionToolbar.style.left = `${left}px`
396
- els.selectionToolbar.style.top = `${top}px`
397
- }
398
-
399
- function updateSelectionToolbar() {
400
- const selection = captureSelection()
401
- if (selection === null) {
402
- hideSelectionToolbar()
403
- return
404
- }
405
- showSelectionToolbar(selection)
406
- }
407
-
408
- async function saveSelectionAnnotation() {
409
- const item = state.selected
410
- const selection = state.selection
411
- if (item === null || selection === null) return
412
- const button = els.selectionToolbar?.querySelector('[data-action="save-highlight"]')
413
- if (button) button.disabled = true
414
- try {
415
- await api(`/items/${encodeURIComponent(item.id)}/annotations`, {
416
- method: 'POST',
417
- body: JSON.stringify({
418
- quote: selection.quote,
419
- startOffset: selection.startOffset,
420
- endOffset: selection.endOffset,
421
- prefix: selection.prefix,
422
- suffix: selection.suffix,
423
- color: state.selectionColor,
424
- note: els.selectionNote?.value ?? '',
425
- }),
426
- })
427
- window.getSelection()?.removeAllRanges()
428
- hideSelectionToolbar()
429
- toast('已添加批注')
430
- await select(item.id)
431
- await loadList()
432
- } catch (error) {
433
- toast(error.message, true)
434
- } finally {
435
- if (button) button.disabled = false
436
- }
437
- }
438
-
439
- function renderDetail() {
440
- hideSelectionToolbar()
441
- const item = state.selected
442
- if (item === null) {
443
- els.detail.innerHTML = `
444
- <div class="empty-state">
445
- <div class="empty-icon" aria-hidden="true">📄</div>
446
- <h2>选择一篇文章</h2>
447
- <p>从左侧打开,或把网页链接粘贴到上方保存。</p>
448
- </div>
449
- `
450
- return
451
- }
452
-
453
- const tags = item.tags.map(tagButton).join('')
454
- const author = item.author ? `<span>${escapeHtml(item.author)}</span><span>·</span>` : ''
455
- const published = item.published ? `<span>${escapeHtml(item.published.slice(0, 10))}</span><span>·</span>` : ''
456
- const truncated = item.truncated ? '<p class="article-note">原文较长,保存时已截断。</p>' : ''
457
- const annotations = Array.isArray(item.annotations) ? item.annotations : []
458
- const annotationMeta = annotations.length > 0
459
- ? `<span>·</span><span>${annotations.length} 批注</span>`
460
- : ''
461
-
462
- els.detail.innerHTML = `
463
- <div class="detail-head">
464
- <div class="detail-meta">
465
- <span>${escapeHtml(item.site || '未命名来源')}</span><span>·</span>
466
- <span>${fmtDate(item.clippedAt)}</span><span>·</span>
467
- <span>${fmtWords(item.wordCount)}</span><span>·</span>
468
- <span>${statusLabel(item.status)}</span>${annotationMeta}
469
- </div>
470
- <h2>${escapeHtml(item.title)}</h2>
471
- <div class="detail-sub">
472
- ${author}${published}
473
- <a href="${escapeAttr(item.url)}" target="_blank" rel="noopener noreferrer">打开原文</a>
474
- </div>
475
- <div class="actions">
476
- <button type="button" class="button ghost mobile-back" data-action="back">返回</button>
477
- <button type="button" class="button" data-action="status">${item.status === 'read' ? '标记未读' : '标记已读'}</button>
478
- <button type="button" class="button" data-action="archive">${item.status === 'archived' ? '移出归档' : '归档'}</button>
479
- <button type="button" class="button" data-action="copy">复制链接</button>
480
- <a class="button" href="./api/items/${encodeURIComponent(item.id)}/export" download="${escapeAttr(item.id)}.md">导出 Markdown</a>
481
- </div>
482
- <div class="detail-tags">
483
- ${tags}
484
- <input id="tag-edit" type="text" placeholder="编辑标签…" value="${escapeAttr(item.tags.join(', '))}" aria-label="编辑标签">
485
- <button type="button" class="button" data-action="save-tags">保存标签</button>
486
- </div>
487
- </div>
488
- <article class="article">${item.html}${truncated}</article>
489
- ${renderAnnotationSection(annotations)}
490
- `
491
-
492
- applyHighlights(els.detail.querySelector('.article'), annotations)
493
- }
494
-
495
- async function select(id) {
496
- try {
497
- const data = await api(`/items/${encodeURIComponent(id)}`)
498
- state.selected = data.item
499
- renderDetail()
500
- updateSelectedInList()
501
- els.layout.classList.add('detail-open')
502
- } catch (error) {
503
- toast(error.message, true)
504
- }
505
- }
506
-
507
- async function updateItem(id, patch) {
508
- try {
509
- await api(`/items/${encodeURIComponent(id)}`, {
510
- method: 'PATCH',
511
- body: JSON.stringify(patch),
512
- })
513
- toast('已更新')
514
- await loadStats()
515
- await loadList()
516
- if (state.selected?.id === id) await select(id)
517
- } catch (error) {
518
- toast(error.message, true)
519
- }
520
- }
521
-
522
- function setTag(tag) {
523
- state.tag = tag
524
- state.tagFilterName.textContent = tag
525
- els.tagFilter.hidden = false
526
- if (state.status !== 'all') {
527
- state.status = 'all'
528
- updateTabs()
529
- }
530
- loadList()
531
- }
532
-
533
- function clearTag() {
534
- state.tag = ''
535
- els.tagFilter.hidden = true
536
- loadList()
537
- }
538
-
539
- function moveSelection(delta) {
540
- if (state.items.length === 0) return
541
- const current = state.items.findIndex(item => item.id === state.selected?.id)
542
- const next = Math.max(0, Math.min(state.items.length - 1, current === -1 ? 0 : current + delta))
543
- const item = state.items[next]
544
- if (item !== undefined) {
545
- select(item.id)
546
- els.list.querySelector(`[data-id="${CSS.escape(item.id)}"]`)?.scrollIntoView({ block: 'nearest' })
547
- }
548
- }
549
-
550
- els.clipForm.addEventListener('submit', async event => {
551
- event.preventDefault()
552
- let url = els.clipUrl.value.trim()
553
- if (url === '') {
554
- els.clipUrl.focus()
555
- return
556
- }
557
- if (!/^https?:\/\//i.test(url)) url = `https://${url}`
558
- const tags = els.clipTags.value.split(/[,,]/).map(value => value.trim()).filter(Boolean)
559
- els.clipSubmit.disabled = true
560
- els.clipSubmit.textContent = '保存中…'
561
- try {
562
- const data = await api('/clip', {
563
- method: 'POST',
564
- body: JSON.stringify({ url, tags }),
565
- })
566
- const clip = data.clip
567
- toast(clip.duplicate ? '这个链接已经在收件箱里了' : '已保存到阅读收件箱')
568
- els.clipUrl.value = ''
569
- els.clipTags.value = ''
570
- await loadStats()
571
- await loadList()
572
- await select(clip.id)
573
- } catch (error) {
574
- toast(error.message, true)
575
- } finally {
576
- els.clipSubmit.disabled = false
577
- els.clipSubmit.textContent = '保存'
578
- }
579
- })
580
-
581
- let searchTimer
582
- els.search.addEventListener('input', () => {
583
- clearTimeout(searchTimer)
584
- searchTimer = setTimeout(() => {
585
- state.q = els.search.value.trim()
586
- loadList()
587
- }, 220)
588
- })
589
-
590
- els.tabs.addEventListener('click', event => {
591
- const tab = event.target.closest('[data-status]')
592
- if (tab === null) return
593
- state.status = tab.dataset.status
594
- updateTabs()
595
- loadList()
596
- })
597
-
598
- els.tagClear.addEventListener('click', clearTag)
599
-
600
- els.list.addEventListener('click', event => {
601
- const tag = event.target.closest('[data-tag]')
602
- if (tag !== null) {
603
- event.stopPropagation()
604
- setTag(tag.dataset.tag)
605
- return
606
- }
607
- const item = event.target.closest('.item')
608
- if (item !== null) select(item.dataset.id)
609
- })
610
-
611
- els.list.addEventListener('keydown', event => {
612
- if (event.key !== 'Enter' && event.key !== ' ') return
613
- const item = event.target.closest('.item')
614
- if (item === null) return
615
- event.preventDefault()
616
- select(item.dataset.id)
617
- })
618
-
619
- els.detail.addEventListener('click', async event => {
620
- const tag = event.target.closest('[data-tag]')
621
- if (tag !== null) {
622
- setTag(tag.dataset.tag)
623
- return
624
- }
625
- const mark = event.target.closest('mark[data-annotation-id]')
626
- if (mark !== null) {
627
- focusAnnotation(mark.dataset.annotationId)
628
- return
629
- }
630
- const action = event.target.closest('[data-action]')?.dataset.action
631
- if (action === undefined) return
632
- const item = state.selected
633
- if (item === null) return
634
- const annotationItem = event.target.closest('.annotation-item')
635
- const annotationId = annotationItem?.dataset.annotationId
636
-
637
- if (action === 'back') {
638
- els.layout.classList.remove('detail-open')
639
- return
640
- }
641
- if (action === 'status') {
642
- await updateItem(item.id, { status: item.status === 'read' ? 'unread' : 'read' })
643
- return
644
- }
645
- if (action === 'archive') {
646
- await updateItem(item.id, { status: item.status === 'archived' ? 'read' : 'archived' })
647
- return
648
- }
649
- if (action === 'copy') {
650
- try {
651
- await navigator.clipboard.writeText(item.url)
652
- toast('已复制链接')
653
- } catch {
654
- toast('复制失败,请手动复制地址栏', true)
655
- }
656
- return
657
- }
658
- if (action === 'save-tags') {
659
- const input = $('#tag-edit')
660
- const tags = (input?.value ?? '').split(/[,,]/).map(value => value.trim()).filter(Boolean)
661
- await updateItem(item.id, { tags })
662
- return
663
- }
664
- if (action === 'jump-annotation') {
665
- if (annotationId !== undefined) scrollToAnnotation(annotationId)
666
- return
667
- }
668
- if (action === 'delete-annotation') {
669
- if (annotationId === undefined) return
670
- try {
671
- await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
672
- method: 'DELETE',
673
- })
674
- toast('已删除批注')
675
- await select(item.id)
676
- await loadList()
677
- } catch (error) {
678
- toast(error.message, true)
679
- }
680
- return
681
- }
682
- if (action === 'save-annotation-note') {
683
- if (annotationId === undefined) return
684
- const note = annotationItem.querySelector('.annotation-note')?.value ?? ''
685
- try {
686
- await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
687
- method: 'PATCH',
688
- body: JSON.stringify({ note }),
689
- })
690
- toast('批注已保存')
691
- await select(item.id)
692
- await loadList()
693
- } catch (error) {
694
- toast(error.message, true)
695
- }
696
- return
697
- }
698
- if (action === 'annotation-color') {
699
- if (annotationId === undefined) return
700
- const color = event.target.closest('[data-color]')?.dataset.color
701
- if (color === undefined) return
702
- try {
703
- await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
704
- method: 'PATCH',
705
- body: JSON.stringify({ color }),
706
- })
707
- toast('颜色已更新')
708
- await select(item.id)
709
- await loadList()
710
- } catch (error) {
711
- toast(error.message, true)
712
- }
713
- }
714
- })
715
-
716
- if (els.selectionToolbar !== null) {
717
- els.selectionToolbar.addEventListener('mousedown', event => {
718
- if (event.target.closest('button') !== null) event.preventDefault()
719
- })
720
- els.selectionToolbar.addEventListener('click', event => {
721
- const color = event.target.closest('[data-color]')?.dataset.color
722
- if (color !== undefined) {
723
- state.selectionColor = color
724
- for (const dot of els.selectionToolbar.querySelectorAll('[data-color]')) {
725
- dot.classList.toggle('active', dot.dataset.color === color)
726
- }
727
- return
728
- }
729
- const action = event.target.closest('[data-action]')?.dataset.action
730
- if (action === 'save-highlight') saveSelectionAnnotation()
731
- })
732
- }
733
-
734
- let selectionTimer
735
- els.detail.addEventListener('mouseup', () => {
736
- clearTimeout(selectionTimer)
737
- selectionTimer = setTimeout(updateSelectionToolbar, 0)
738
- })
739
- els.detail.addEventListener('keyup', event => {
740
- if (!event.shiftKey) return
741
- clearTimeout(selectionTimer)
742
- selectionTimer = setTimeout(updateSelectionToolbar, 0)
743
- })
744
- els.detail.addEventListener('scroll', hideSelectionToolbar, { passive: true })
745
- window.addEventListener('resize', hideSelectionToolbar)
746
- els.detail.addEventListener('keydown', event => {
747
- if (event.key !== 'Enter') return
748
- const input = event.target.closest?.('.annotation-note')
749
- if (input === null || input === undefined) return
750
- event.preventDefault()
751
- input.closest('.annotation-item')?.querySelector('[data-action="save-annotation-note"]')?.click()
752
- })
753
-
754
- document.addEventListener('keydown', event => {
755
- const target = event.target
756
- const typing = target instanceof HTMLElement && (target.matches('input, textarea, select') || target.isContentEditable)
757
- if (event.key === '/' && !typing) {
758
- event.preventDefault()
759
- els.search.focus()
760
- return
761
- }
762
- if (event.key === 'Escape') {
763
- hideSelectionToolbar()
764
- if (document.activeElement === els.search) {
765
- els.search.value = ''
766
- state.q = ''
767
- loadList()
768
- } else {
769
- els.layout.classList.remove('detail-open')
770
- }
771
- return
772
- }
773
- if (typing) return
774
- if (event.key === 'j') {
775
- event.preventDefault()
776
- moveSelection(1)
777
- } else if (event.key === 'k') {
778
- event.preventDefault()
779
- moveSelection(-1)
780
- }
781
- })
782
-
783
- updateTabs()
784
- loadStats()
785
- loadList()
1
+ const $ = (selector, root = document) => root.querySelector(selector)
2
+
3
+ const state = {
4
+ q: '',
5
+ status: 'all',
6
+ tag: '',
7
+ items: [],
8
+ total: 0,
9
+ selected: null,
10
+ stats: null,
11
+ listToken: 0,
12
+ selection: null,
13
+ selectionColor: 'yellow',
14
+ views: [],
15
+ }
16
+
17
+ const ANNOTATION_COLORS = ['yellow', 'green', 'blue', 'red']
18
+
19
+ const els = {
20
+ layout: $('#layout'),
21
+ list: $('#list'),
22
+ detail: $('#detail'),
23
+ search: $('#search'),
24
+ tabs: $('#tabs'),
25
+ stats: $('#stats'),
26
+ clipForm: $('#clip-form'),
27
+ clipUrl: $('#clip-url'),
28
+ clipTags: $('#clip-tags'),
29
+ clipSubmit: $('#clip-submit'),
30
+ saveTextToggle: $('#save-text-toggle'),
31
+ textPanel: $('#text-panel'),
32
+ textForm: $('#text-form'),
33
+ textTitle: $('#text-title'),
34
+ textUrl: $('#text-url'),
35
+ textTags: $('#text-tags'),
36
+ textBody: $('#text-body'),
37
+ textCancel: $('#text-cancel'),
38
+ exportAll: $('#export-all'),
39
+ importToggle: $('#import-toggle'),
40
+ importFile: $('#import-file'),
41
+ tagFilter: $('#tag-filter'),
42
+ tagFilterName: $('#tag-filter-name'),
43
+ tagClear: $('#tag-clear'),
44
+ selectionToolbar: $('#selection-toolbar'),
45
+ selectionQuote: $('#selection-quote'),
46
+ selectionNote: $('#selection-note'),
47
+ views: $('#views'),
48
+ saveView: $('#save-view'),
49
+ viewForm: $('#view-form'),
50
+ viewName: $('#view-name'),
51
+ viewCancel: $('#view-cancel'),
52
+ toast: $('#toast'),
53
+ }
54
+
55
+ function codePointLength(value) {
56
+ return Array.from(String(value ?? '')).length
57
+ }
58
+
59
+ function codePointSlice(value, start, end) {
60
+ return Array.from(String(value ?? '')).slice(start, end).join('')
61
+ }
62
+
63
+ function codePointToUtf16(value, index) {
64
+ let codePoints = 0
65
+ let offset = 0
66
+ while (offset < value.length && codePoints < index) {
67
+ const code = value.charCodeAt(offset)
68
+ if (code >= 0xd800 && code <= 0xdbff && offset + 1 < value.length) offset += 1
69
+ offset += 1
70
+ codePoints += 1
71
+ }
72
+ return offset
73
+ }
74
+
75
+ function escapeHtml(value) {
76
+ return String(value ?? '')
77
+ .replaceAll('&', '&amp;')
78
+ .replaceAll('<', '&lt;')
79
+ .replaceAll('>', '&gt;')
80
+ .replaceAll('"', '&quot;')
81
+ .replaceAll("'", '&#39;')
82
+ }
83
+
84
+ function escapeAttr(value) {
85
+ return escapeHtml(value).replaceAll('`', '&#96;')
86
+ }
87
+
88
+ function fmtDate(value) {
89
+ if (!value) return ''
90
+ const date = new Date(value)
91
+ if (Number.isNaN(date.getTime())) return ''
92
+ return new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).format(date)
93
+ }
94
+
95
+ function fmtWords(value) {
96
+ const number = Number(value) || 0
97
+ return number >= 10_000 ? `${(number / 10_000).toFixed(1)} 万字` : `${number} 字`
98
+ }
99
+
100
+ function statusLabel(status) {
101
+ return { unread: '未读', reading: '在读', read: '已读', archived: '归档' }[status] ?? status
102
+ }
103
+
104
+ let toastTimer
105
+ function toast(message, isError = false) {
106
+ clearTimeout(toastTimer)
107
+ els.toast.textContent = message
108
+ els.toast.classList.toggle('error', isError)
109
+ els.toast.hidden = false
110
+ toastTimer = setTimeout(() => { els.toast.hidden = true }, 2800)
111
+ }
112
+
113
+ async function api(path, options = {}) {
114
+ const response = await fetch(`./api${path}`, {
115
+ ...options,
116
+ headers: {
117
+ ...(options.body === undefined ? {} : { 'content-type': 'application/json' }),
118
+ ...(options.headers ?? {}),
119
+ },
120
+ })
121
+ let body = null
122
+ try {
123
+ body = await response.json()
124
+ } catch {
125
+ body = null
126
+ }
127
+ if (!response.ok || body?.ok === false) {
128
+ throw new Error(body?.error || `请求失败:HTTP ${response.status}`)
129
+ }
130
+ return body
131
+ }
132
+
133
+ function tagButton(tag) {
134
+ return `<button type="button" class="tag" data-tag="${escapeAttr(tag)}">${escapeHtml(tag)}</button>`
135
+ }
136
+
137
+ function updateTabs() {
138
+ for (const tab of els.tabs.querySelectorAll('[data-status]')) {
139
+ tab.classList.toggle('active', tab.dataset.status === state.status)
140
+ }
141
+ const stats = state.stats
142
+ if (stats !== null) {
143
+ $('#count-all').textContent = String(stats.all ?? 0)
144
+ $('#count-unread').textContent = String(stats.unread ?? 0)
145
+ $('#count-reading').textContent = String(stats.reading ?? 0)
146
+ $('#count-read').textContent = String(stats.read ?? 0)
147
+ $('#count-archived').textContent = String(stats.archived ?? 0)
148
+ els.stats.textContent = `共 ${stats.all ?? 0} 篇 · 未读 ${stats.unread ?? 0} · 在读 ${stats.reading ?? 0} · 已读 ${stats.read ?? 0} · 归档 ${stats.archived ?? 0}`
149
+ }
150
+ }
151
+
152
+ async function loadStats() {
153
+ try {
154
+ const data = await api('/stats')
155
+ state.stats = data
156
+ updateTabs()
157
+ if (data.warnings?.length) toast(data.warnings[0], true)
158
+ } catch (error) {
159
+ toast(error.message, true)
160
+ }
161
+ }
162
+
163
+ function currentViewQuery() {
164
+ const parts = []
165
+ if (state.q.trim() !== '') parts.push(state.q.trim())
166
+ if (state.status !== 'all') parts.push(`is:${state.status}`)
167
+ if (state.tag !== '') parts.push(`tag:${state.tag}`)
168
+ return parts.join(' ')
169
+ }
170
+
171
+ function hideViewForm() {
172
+ if (!els.viewForm) return
173
+ els.viewForm.hidden = true
174
+ els.viewName.value = ''
175
+ }
176
+
177
+ function showViewForm() {
178
+ if (!els.viewForm) return
179
+ els.viewForm.hidden = false
180
+ els.viewName.value = ''
181
+ els.viewName.focus()
182
+ }
183
+
184
+ function renderViews() {
185
+ if (!els.views) return
186
+ const fragment = document.createDocumentFragment()
187
+ for (const view of state.views) {
188
+ const chip = document.createElement('span')
189
+ chip.className = 'view-chip'
190
+ const apply = document.createElement('button')
191
+ apply.type = 'button'
192
+ apply.className = 'view-name'
193
+ apply.textContent = view.name
194
+ apply.title = view.query
195
+ apply.dataset.viewQuery = view.query
196
+ const remove = document.createElement('button')
197
+ remove.type = 'button'
198
+ remove.className = 'view-remove'
199
+ remove.textContent = '×'
200
+ remove.title = '删除视图'
201
+ remove.dataset.removeView = view.id
202
+ chip.append(apply, remove)
203
+ fragment.append(chip)
204
+ }
205
+ els.views.replaceChildren(fragment)
206
+ }
207
+
208
+ async function loadViews() {
209
+ if (!els.views) return
210
+ try {
211
+ const data = await api('/views')
212
+ state.views = Array.isArray(data.views) ? data.views : []
213
+ renderViews()
214
+ } catch (error) {
215
+ toast(error.message, true)
216
+ }
217
+ }
218
+
219
+ async function saveCurrentView() {
220
+ const query = currentViewQuery()
221
+ if (query === '') {
222
+ toast('先输入搜索或选择筛选', true)
223
+ return
224
+ }
225
+ const name = els.viewName.value.trim()
226
+ if (name === '') {
227
+ els.viewName.focus()
228
+ return
229
+ }
230
+ try {
231
+ await api('/views', { method: 'POST', body: JSON.stringify({ name, query }) })
232
+ hideViewForm()
233
+ await loadViews()
234
+ toast('视图已保存')
235
+ } catch (error) {
236
+ toast(error.message, true)
237
+ }
238
+ }
239
+
240
+ async function applyView(query) {
241
+ els.search.value = query
242
+ state.q = query.trim()
243
+ state.status = 'all'
244
+ state.tag = ''
245
+ els.tagFilter.hidden = true
246
+ updateTabs()
247
+ hideViewForm()
248
+ await loadList()
249
+ }
250
+
251
+ async function removeView(id) {
252
+ try {
253
+ await api(`/views/${encodeURIComponent(id)}`, { method: 'DELETE' })
254
+ await loadViews()
255
+ toast('视图已删除')
256
+ } catch (error) {
257
+ toast(error.message, true)
258
+ }
259
+ }
260
+
261
+ function renderListLoading() {
262
+ els.list.replaceChildren(...Array.from({ length: 4 }, () => {
263
+ const skeleton = document.createElement('div')
264
+ skeleton.className = 'skeleton'
265
+ return skeleton
266
+ }))
267
+ }
268
+
269
+ function emptyListMessage() {
270
+ if (state.q !== '') return `没有找到包含“${state.q}”的文章。`
271
+ if (state.tag !== '') return `没有标签为“${state.tag}”的文章。`
272
+ if (state.status === 'unread') return '收件箱是空的。把网页链接粘贴到上方开始收藏。'
273
+ if (state.status === 'reading') return '没有正在读的文章。'
274
+ if (state.status === 'archived') return '还没有归档的文章。'
275
+ return '还没有文章。粘贴一个网页链接开始。'
276
+ }
277
+
278
+ function renderList() {
279
+ if (state.items.length === 0) {
280
+ const empty = document.createElement('div')
281
+ empty.className = 'list-empty'
282
+ empty.textContent = emptyListMessage()
283
+ els.list.replaceChildren(empty)
284
+ return
285
+ }
286
+
287
+ const fragment = document.createDocumentFragment()
288
+ for (const item of state.items) {
289
+ const article = document.createElement('article')
290
+ article.className = 'item'
291
+ if (state.selected?.id === item.id) article.classList.add('selected')
292
+ article.dataset.id = item.id
293
+ article.tabIndex = 0
294
+ article.setAttribute('role', 'button')
295
+ article.innerHTML = `
296
+ <div class="item-top">
297
+ <span class="site">${escapeHtml(item.site || item.url)}</span>
298
+ <time>${fmtDate(item.clippedAt)}</time>
299
+ </div>
300
+ <h3>${escapeHtml(item.title)}</h3>
301
+ <p class="excerpt">${escapeHtml(item.snippet || item.excerpt || '')}</p>
302
+ <div class="item-bottom">
303
+ <span class="status-dot ${escapeAttr(item.status)}"></span>
304
+ <span>${statusLabel(item.status)}</span>
305
+ <span>·</span>
306
+ <span>${fmtWords(item.wordCount)}</span>
307
+ ${item.annotationCount > 0 ? `<span>·</span><span>${item.annotationCount} 批注</span>` : ''}
308
+ ${item.tags.slice(0, 3).map(tagButton).join('')}
309
+ </div>
310
+ `
311
+ fragment.append(article)
312
+ }
313
+ els.list.replaceChildren(fragment)
314
+ }
315
+
316
+ async function loadList() {
317
+ const token = ++state.listToken
318
+ renderListLoading()
319
+ const params = new URLSearchParams({ status: state.status, limit: '100' })
320
+ if (state.q !== '') params.set('q', state.q)
321
+ if (state.tag !== '') params.set('tag', state.tag)
322
+
323
+ try {
324
+ const data = await api(`/items?${params.toString()}`)
325
+ if (token !== state.listToken) return
326
+ state.items = data.items
327
+ state.total = data.total
328
+ renderList()
329
+ } catch (error) {
330
+ if (token !== state.listToken) return
331
+ const failed = document.createElement('div')
332
+ failed.className = 'list-empty'
333
+ failed.textContent = error.message
334
+ els.list.replaceChildren(failed)
335
+ toast(error.message, true)
336
+ }
337
+ }
338
+
339
+ function updateSelectedInList() {
340
+ for (const element of els.list.querySelectorAll('.item')) {
341
+ element.classList.toggle('selected', element.dataset.id === state.selected?.id)
342
+ }
343
+ }
344
+
345
+ function annotationColorButtons(current, annotationId) {
346
+ return ANNOTATION_COLORS.map(color => `
347
+ <button type="button" class="color-dot ${color}${color === current ? ' active' : ''}"
348
+ data-action="annotation-color" data-color="${color}" data-annotation-id="${escapeAttr(annotationId)}"
349
+ aria-label="${color}"></button>`).join('')
350
+ }
351
+
352
+ function renderAnnotationSection(annotations) {
353
+ const list = Array.isArray(annotations) ? annotations : []
354
+ const items = list.map(annotation => {
355
+ const stale = annotation.status === 'stale'
356
+ return `
357
+ <article class="annotation-item${stale ? ' stale' : ''}" data-annotation-id="${escapeAttr(annotation.id)}">
358
+ <div class="annotation-top">
359
+ <span class="color-dot ${escapeAttr(annotation.color || 'yellow')}"></span>
360
+ <span class="annotation-status">${stale ? '原文已变化,未能定位' : '已定位'}</span>
361
+ <span class="annotation-spacer"></span>
362
+ ${stale ? '' : '<button type="button" class="button small" data-action="jump-annotation">定位</button>'}
363
+ <button type="button" class="button small danger" data-action="delete-annotation">删除</button>
364
+ </div>
365
+ <blockquote>${escapeHtml(annotation.quote)}</blockquote>
366
+ <div class="annotation-note-row">
367
+ <input class="annotation-note" data-annotation-id="${escapeAttr(annotation.id)}"
368
+ value="${escapeAttr(annotation.note || '')}" placeholder="写批注…" maxlength="2000">
369
+ <button type="button" class="button small" data-action="save-annotation-note">保存</button>
370
+ </div>
371
+ <div class="annotation-colors">${annotationColorButtons(annotation.color || 'yellow', annotation.id)}</div>
372
+ </article>`
373
+ }).join('')
374
+ return `
375
+ <section class="annotation-section" id="annotations">
376
+ <div class="annotation-head">
377
+ <h3>批注 <span>${list.length}</span></h3>
378
+ <p>${list.length === 0 ? '选中正文文字即可高亮、写批注。' : '点击批注定位到原文;导出 Markdown 时会一起带上。'}</p>
379
+ </div>
380
+ ${items || '<div class="annotation-empty">还没有批注。</div>'}
381
+ </section>`
382
+ }
383
+
384
+ function wrapCodePointRange(root, start, end, annotation) {
385
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
386
+ const nodes = []
387
+ let position = 0
388
+ let node
389
+ while ((node = walker.nextNode()) !== null) {
390
+ const length = codePointLength(node.data)
391
+ nodes.push({ node, start: position, end: position + length })
392
+ position += length
393
+ }
394
+
395
+ for (const entry of nodes) {
396
+ if (entry.end <= start || entry.start >= end) continue
397
+ const localStart = Math.max(0, start - entry.start)
398
+ const localEnd = Math.min(entry.end - entry.start, end - entry.start)
399
+ if (localEnd <= localStart) continue
400
+
401
+ let target = entry.node
402
+ const utf16Start = codePointToUtf16(target.data, localStart)
403
+ const utf16End = codePointToUtf16(target.data, localEnd)
404
+ if (utf16Start > 0) target = target.splitText(utf16Start)
405
+ if (utf16End - utf16Start < target.data.length) target.splitText(utf16End - utf16Start)
406
+ if (target.data === '') continue
407
+
408
+ const mark = document.createElement('mark')
409
+ mark.className = `hl hl-${annotation.color || 'yellow'}`
410
+ mark.dataset.annotationId = annotation.id
411
+ if (annotation.note) mark.title = annotation.note
412
+ target.parentNode.insertBefore(mark, target)
413
+ mark.append(target)
414
+ }
415
+ }
416
+
417
+ function applyHighlights(root, annotations) {
418
+ if (!root) return
419
+ const active = (Array.isArray(annotations) ? annotations : [])
420
+ .filter(annotation => annotation.status !== 'stale' && annotation.startOffset >= 0 && annotation.endOffset > annotation.startOffset)
421
+ .sort((a, b) => a.startOffset - b.startOffset)
422
+ for (const annotation of active) {
423
+ wrapCodePointRange(root, annotation.startOffset, annotation.endOffset, annotation)
424
+ }
425
+ }
426
+
427
+ function focusAnnotation(annotationId) {
428
+ const target = els.detail.querySelector(`.annotation-item[data-annotation-id="${CSS.escape(annotationId)}"]`)
429
+ if (target === null) return
430
+ target.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
431
+ target.classList.add('pulse')
432
+ setTimeout(() => target.classList.remove('pulse'), 1200)
433
+ }
434
+
435
+ function scrollToAnnotation(annotationId) {
436
+ const mark = els.detail.querySelector(`.article mark[data-annotation-id="${CSS.escape(annotationId)}"]`)
437
+ if (mark === null) {
438
+ focusAnnotation(annotationId)
439
+ return
440
+ }
441
+ mark.scrollIntoView({ block: 'center', behavior: 'smooth' })
442
+ mark.classList.add('pulse')
443
+ setTimeout(() => mark.classList.remove('pulse'), 1200)
444
+ }
445
+
446
+ function hideSelectionToolbar() {
447
+ if (!els.selectionToolbar) return
448
+ els.selectionToolbar.hidden = true
449
+ state.selection = null
450
+ state.selectionColor = 'yellow'
451
+ if (els.selectionNote) els.selectionNote.value = ''
452
+ }
453
+
454
+ function captureSelection() {
455
+ const article = els.detail.querySelector('.article')
456
+ if (!article) return null
457
+ const selection = window.getSelection()
458
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null
459
+ const range = selection.getRangeAt(0)
460
+ if (!article.contains(range.startContainer) || !article.contains(range.endContainer)) return null
461
+
462
+ const fullText = article.textContent
463
+ const before = document.createRange()
464
+ before.selectNodeContents(article)
465
+ before.setEnd(range.startContainer, range.startOffset)
466
+ const after = document.createRange()
467
+ after.selectNodeContents(article)
468
+ after.setStart(range.endContainer, range.endOffset)
469
+
470
+ let start = codePointLength(before.toString())
471
+ let end = codePointLength(fullText) - codePointLength(after.toString())
472
+ if (end <= start) return null
473
+
474
+ while (start < end && /\s/.test(codePointSlice(fullText, start, start + 1))) start += 1
475
+ while (end > start && /\s/.test(codePointSlice(fullText, end - 1, end))) end -= 1
476
+ const quote = codePointSlice(fullText, start, end)
477
+ if (quote.trim() === '') return null
478
+
479
+ return {
480
+ quote,
481
+ startOffset: start,
482
+ endOffset: end,
483
+ prefix: codePointSlice(fullText, Math.max(0, start - 32), start),
484
+ suffix: codePointSlice(fullText, end, end + 32),
485
+ rect: range.getBoundingClientRect(),
486
+ }
487
+ }
488
+
489
+ function showSelectionToolbar(selection) {
490
+ if (!els.selectionToolbar) return
491
+ state.selection = selection
492
+ state.selectionColor = 'yellow'
493
+ els.selectionQuote.textContent = `“${selection.quote.slice(0, 140)}${selection.quote.length > 140 ? '…' : ''}”`
494
+ els.selectionNote.value = ''
495
+ for (const dot of els.selectionToolbar.querySelectorAll('[data-color]')) {
496
+ dot.classList.toggle('active', dot.dataset.color === 'yellow')
497
+ }
498
+ els.selectionToolbar.hidden = false
499
+ const width = els.selectionToolbar.offsetWidth
500
+ const height = els.selectionToolbar.offsetHeight
501
+ const rect = selection.rect
502
+ const left = Math.min(
503
+ Math.max(8, rect.left + rect.width / 2 - width / 2),
504
+ window.innerWidth - width - 8,
505
+ )
506
+ const top = rect.bottom + height + 12 > window.innerHeight
507
+ ? Math.max(8, rect.top - height - 8)
508
+ : rect.bottom + 8
509
+ els.selectionToolbar.style.left = `${left}px`
510
+ els.selectionToolbar.style.top = `${top}px`
511
+ }
512
+
513
+ function updateSelectionToolbar() {
514
+ const selection = captureSelection()
515
+ if (selection === null) {
516
+ hideSelectionToolbar()
517
+ return
518
+ }
519
+ showSelectionToolbar(selection)
520
+ }
521
+
522
+ async function saveSelectionAnnotation() {
523
+ const item = state.selected
524
+ const selection = state.selection
525
+ if (item === null || selection === null) return
526
+ const button = els.selectionToolbar?.querySelector('[data-action="save-highlight"]')
527
+ if (button) button.disabled = true
528
+ try {
529
+ await api(`/items/${encodeURIComponent(item.id)}/annotations`, {
530
+ method: 'POST',
531
+ body: JSON.stringify({
532
+ quote: selection.quote,
533
+ startOffset: selection.startOffset,
534
+ endOffset: selection.endOffset,
535
+ prefix: selection.prefix,
536
+ suffix: selection.suffix,
537
+ color: state.selectionColor,
538
+ note: els.selectionNote?.value ?? '',
539
+ }),
540
+ })
541
+ window.getSelection()?.removeAllRanges()
542
+ hideSelectionToolbar()
543
+ toast('已添加批注')
544
+ await select(item.id)
545
+ await loadList()
546
+ } catch (error) {
547
+ toast(error.message, true)
548
+ } finally {
549
+ if (button) button.disabled = false
550
+ }
551
+ }
552
+
553
+ function renderDetail() {
554
+ hideSelectionToolbar()
555
+ const item = state.selected
556
+ if (item === null) {
557
+ els.detail.innerHTML = `
558
+ <div class="empty-state">
559
+ <div class="empty-icon" aria-hidden="true">📄</div>
560
+ <h2>选择一篇文章</h2>
561
+ <p>从左侧打开,或把网页链接粘贴到上方保存。</p>
562
+ </div>
563
+ `
564
+ return
565
+ }
566
+
567
+ const tags = item.tags.map(tagButton).join('')
568
+ const author = item.author ? `<span>${escapeHtml(item.author)}</span><span>·</span>` : ''
569
+ const published = item.published ? `<span>${escapeHtml(item.published.slice(0, 10))}</span><span>·</span>` : ''
570
+ const truncated = item.truncated ? '<p class="article-note">原文较长,保存时已截断。</p>' : ''
571
+ const sourceLink = item.url ? `<a href="${escapeAttr(item.url)}" target="_blank" rel="noopener noreferrer">打开原文</a>` : ''
572
+ const annotations = Array.isArray(item.annotations) ? item.annotations : []
573
+ const annotationMeta = annotations.length > 0
574
+ ? `<span>·</span><span>${annotations.length} 批注</span>`
575
+ : ''
576
+
577
+ els.detail.innerHTML = `
578
+ <div class="detail-head">
579
+ <div class="detail-meta">
580
+ <span>${escapeHtml(item.site || '未命名来源')}</span><span>·</span>
581
+ <span>${fmtDate(item.clippedAt)}</span><span>·</span>
582
+ <span>${fmtWords(item.wordCount)}</span><span>·</span>
583
+ <span>${statusLabel(item.status)}</span>${annotationMeta}
584
+ </div>
585
+ <h2>${escapeHtml(item.title)}</h2>
586
+ <div class="detail-sub">
587
+ ${author}${published}${sourceLink}
588
+ </div>
589
+ <div class="actions">
590
+ <button type="button" class="button ghost mobile-back" data-action="back">返回</button>
591
+ <button type="button" class="button" data-action="status">${item.status === 'read' ? '标记未读' : '标记已读'}</button>
592
+ <button type="button" class="button" data-action="archive">${item.status === 'archived' ? '移出归档' : '归档'}</button>
593
+ <button type="button" class="button" data-action="copy">复制链接</button>
594
+ <a class="button" href="./api/items/${encodeURIComponent(item.id)}/export" download="${escapeAttr(item.id)}.md">导出 Markdown</a>
595
+ </div>
596
+ <div class="detail-tags">
597
+ ${tags}
598
+ <input id="tag-edit" type="text" placeholder="编辑标签…" value="${escapeAttr(item.tags.join(', '))}" aria-label="编辑标签">
599
+ <button type="button" class="button" data-action="save-tags">保存标签</button>
600
+ </div>
601
+ </div>
602
+ <article class="article">${item.html}${truncated}</article>
603
+ ${renderAnnotationSection(annotations)}
604
+ `
605
+
606
+ applyHighlights(els.detail.querySelector('.article'), annotations)
607
+ }
608
+
609
+ async function select(id) {
610
+ try {
611
+ const data = await api(`/items/${encodeURIComponent(id)}`)
612
+ state.selected = data.item
613
+ renderDetail()
614
+ updateSelectedInList()
615
+ els.layout.classList.add('detail-open')
616
+ } catch (error) {
617
+ toast(error.message, true)
618
+ }
619
+ }
620
+
621
+ async function updateItem(id, patch) {
622
+ try {
623
+ await api(`/items/${encodeURIComponent(id)}`, {
624
+ method: 'PATCH',
625
+ body: JSON.stringify(patch),
626
+ })
627
+ toast('已更新')
628
+ await loadStats()
629
+ await loadList()
630
+ if (state.selected?.id === id) await select(id)
631
+ } catch (error) {
632
+ toast(error.message, true)
633
+ }
634
+ }
635
+
636
+ function setTag(tag) {
637
+ state.tag = tag
638
+ state.tagFilterName.textContent = tag
639
+ els.tagFilter.hidden = false
640
+ if (state.status !== 'all') {
641
+ state.status = 'all'
642
+ updateTabs()
643
+ }
644
+ loadList()
645
+ }
646
+
647
+ function clearTag() {
648
+ state.tag = ''
649
+ els.tagFilter.hidden = true
650
+ loadList()
651
+ }
652
+
653
+ function moveSelection(delta) {
654
+ if (state.items.length === 0) return
655
+ const current = state.items.findIndex(item => item.id === state.selected?.id)
656
+ const next = Math.max(0, Math.min(state.items.length - 1, current === -1 ? 0 : current + delta))
657
+ const item = state.items[next]
658
+ if (item !== undefined) {
659
+ select(item.id)
660
+ els.list.querySelector(`[data-id="${CSS.escape(item.id)}"]`)?.scrollIntoView({ block: 'nearest' })
661
+ }
662
+ }
663
+
664
+ els.clipForm.addEventListener('submit', async event => {
665
+ event.preventDefault()
666
+ let url = els.clipUrl.value.trim()
667
+ if (url === '') {
668
+ els.clipUrl.focus()
669
+ return
670
+ }
671
+ if (!/^https?:\/\//i.test(url)) url = `https://${url}`
672
+ const tags = els.clipTags.value.split(/[,,]/).map(value => value.trim()).filter(Boolean)
673
+ els.clipSubmit.disabled = true
674
+ els.clipSubmit.textContent = '保存中…'
675
+ try {
676
+ const data = await api('/clip', {
677
+ method: 'POST',
678
+ body: JSON.stringify({ url, tags }),
679
+ })
680
+ const clip = data.clip
681
+ toast(clip.duplicate ? '这个链接已经在收件箱里了' : '已保存到阅读收件箱')
682
+ els.clipUrl.value = ''
683
+ els.clipTags.value = ''
684
+ await loadStats()
685
+ await loadList()
686
+ await select(clip.id)
687
+ } catch (error) {
688
+ toast(error.message, true)
689
+ } finally {
690
+ els.clipSubmit.disabled = false
691
+ els.clipSubmit.textContent = '保存'
692
+ }
693
+ })
694
+
695
+ let searchTimer
696
+ function showTextPanel() {
697
+ if (!els.textPanel) return
698
+ els.textPanel.hidden = false
699
+ els.textTitle.value = ''
700
+ els.textUrl.value = ''
701
+ els.textTags.value = ''
702
+ els.textBody.value = ''
703
+ els.textBody.focus()
704
+ }
705
+
706
+ function hideTextPanel() {
707
+ if (!els.textPanel) return
708
+ els.textPanel.hidden = true
709
+ }
710
+
711
+ if (els.saveTextToggle) els.saveTextToggle.addEventListener('click', showTextPanel)
712
+ if (els.textCancel) els.textCancel.addEventListener('click', hideTextPanel)
713
+ if (els.textForm) {
714
+ els.textForm.addEventListener('submit', async event => {
715
+ event.preventDefault()
716
+ const text = els.textBody.value.trim()
717
+ if (text === '') {
718
+ els.textBody.focus()
719
+ return
720
+ }
721
+ const submit = els.textForm.querySelector('button[type="submit"]')
722
+ if (submit) submit.disabled = true
723
+ try {
724
+ const data = await api('/save-text', {
725
+ method: 'POST',
726
+ body: JSON.stringify({
727
+ title: els.textTitle.value.trim(),
728
+ url: els.textUrl.value.trim(),
729
+ tags: els.textTags.value.split(/[,,]/).map(value => value.trim()).filter(Boolean),
730
+ text,
731
+ }),
732
+ })
733
+ const clip = data.clip
734
+ hideTextPanel()
735
+ toast(clip.duplicate ? '这个链接已经在收件箱里了' : '已保存到阅读收件箱')
736
+ await loadStats()
737
+ await loadList()
738
+ await select(clip.id)
739
+ } catch (error) {
740
+ toast(error.message, true)
741
+ } finally {
742
+ if (submit) submit.disabled = false
743
+ }
744
+ })
745
+ }
746
+
747
+ async function exportAll() {
748
+ try {
749
+ const response = await fetch('./api/export?format=json')
750
+ if (!response.ok) throw new Error(`导出失败:HTTP ${response.status}`)
751
+ const blob = await response.blob()
752
+ const link = document.createElement('a')
753
+ const url = URL.createObjectURL(blob)
754
+ link.href = url
755
+ link.download = 'dsh-reading-inbox.json'
756
+ document.body.append(link)
757
+ link.click()
758
+ link.remove()
759
+ setTimeout(() => URL.revokeObjectURL(url), 1_000)
760
+ toast('已导出全部')
761
+ } catch (error) {
762
+ toast(error.message, true)
763
+ }
764
+ }
765
+
766
+ if (els.exportAll) els.exportAll.addEventListener('click', exportAll)
767
+ if (els.importToggle && els.importFile) {
768
+ els.importToggle.addEventListener('click', () => els.importFile.click())
769
+ els.importFile.addEventListener('change', async () => {
770
+ const file = els.importFile.files?.[0]
771
+ if (!file) return
772
+ try {
773
+ const bundle = JSON.parse(await file.text())
774
+ const data = await api('/import', { method: 'POST', body: JSON.stringify(bundle) })
775
+ const errors = Array.isArray(data.errors) && data.errors.length > 0 ? `,${data.errors.length} 条错误` : ''
776
+ toast(`导入 ${data.imported} 篇,跳过 ${data.skipped} 篇${errors}`)
777
+ await loadStats()
778
+ await loadList()
779
+ await loadViews()
780
+ } catch (error) {
781
+ toast(error.message, true)
782
+ } finally {
783
+ els.importFile.value = ''
784
+ }
785
+ })
786
+ }
787
+
788
+ els.search.addEventListener('input', () => {
789
+ clearTimeout(searchTimer)
790
+ searchTimer = setTimeout(() => {
791
+ state.q = els.search.value.trim()
792
+ loadList()
793
+ }, 220)
794
+ })
795
+
796
+ if (els.saveView) els.saveView.addEventListener('click', showViewForm)
797
+ if (els.viewCancel) els.viewCancel.addEventListener('click', hideViewForm)
798
+ if (els.viewForm) {
799
+ els.viewForm.addEventListener('submit', event => {
800
+ event.preventDefault()
801
+ saveCurrentView()
802
+ })
803
+ }
804
+ if (els.views) {
805
+ els.views.addEventListener('click', event => {
806
+ const remove = event.target.closest('[data-remove-view]')
807
+ if (remove !== null) {
808
+ event.stopPropagation()
809
+ removeView(remove.dataset.removeView)
810
+ return
811
+ }
812
+ const apply = event.target.closest('[data-view-query]')
813
+ if (apply !== null) applyView(apply.dataset.viewQuery)
814
+ })
815
+ }
816
+
817
+ els.tabs.addEventListener('click', event => {
818
+ const tab = event.target.closest('[data-status]')
819
+ if (tab === null) return
820
+ state.status = tab.dataset.status
821
+ updateTabs()
822
+ loadList()
823
+ })
824
+
825
+ els.tagClear.addEventListener('click', clearTag)
826
+
827
+ els.list.addEventListener('click', event => {
828
+ const tag = event.target.closest('[data-tag]')
829
+ if (tag !== null) {
830
+ event.stopPropagation()
831
+ setTag(tag.dataset.tag)
832
+ return
833
+ }
834
+ const item = event.target.closest('.item')
835
+ if (item !== null) select(item.dataset.id)
836
+ })
837
+
838
+ els.list.addEventListener('keydown', event => {
839
+ if (event.key !== 'Enter' && event.key !== ' ') return
840
+ const item = event.target.closest('.item')
841
+ if (item === null) return
842
+ event.preventDefault()
843
+ select(item.dataset.id)
844
+ })
845
+
846
+ els.detail.addEventListener('click', async event => {
847
+ const tag = event.target.closest('[data-tag]')
848
+ if (tag !== null) {
849
+ setTag(tag.dataset.tag)
850
+ return
851
+ }
852
+ const mark = event.target.closest('mark[data-annotation-id]')
853
+ if (mark !== null) {
854
+ focusAnnotation(mark.dataset.annotationId)
855
+ return
856
+ }
857
+ const action = event.target.closest('[data-action]')?.dataset.action
858
+ if (action === undefined) return
859
+ const item = state.selected
860
+ if (item === null) return
861
+ const annotationItem = event.target.closest('.annotation-item')
862
+ const annotationId = annotationItem?.dataset.annotationId
863
+
864
+ if (action === 'back') {
865
+ els.layout.classList.remove('detail-open')
866
+ return
867
+ }
868
+ if (action === 'status') {
869
+ await updateItem(item.id, { status: item.status === 'read' ? 'unread' : 'read' })
870
+ return
871
+ }
872
+ if (action === 'archive') {
873
+ await updateItem(item.id, { status: item.status === 'archived' ? 'read' : 'archived' })
874
+ return
875
+ }
876
+ if (action === 'copy') {
877
+ try {
878
+ await navigator.clipboard.writeText(item.url)
879
+ toast('已复制链接')
880
+ } catch {
881
+ toast('复制失败,请手动复制地址栏', true)
882
+ }
883
+ return
884
+ }
885
+ if (action === 'save-tags') {
886
+ const input = $('#tag-edit')
887
+ const tags = (input?.value ?? '').split(/[,,]/).map(value => value.trim()).filter(Boolean)
888
+ await updateItem(item.id, { tags })
889
+ return
890
+ }
891
+ if (action === 'jump-annotation') {
892
+ if (annotationId !== undefined) scrollToAnnotation(annotationId)
893
+ return
894
+ }
895
+ if (action === 'delete-annotation') {
896
+ if (annotationId === undefined) return
897
+ try {
898
+ await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
899
+ method: 'DELETE',
900
+ })
901
+ toast('已删除批注')
902
+ await select(item.id)
903
+ await loadList()
904
+ } catch (error) {
905
+ toast(error.message, true)
906
+ }
907
+ return
908
+ }
909
+ if (action === 'save-annotation-note') {
910
+ if (annotationId === undefined) return
911
+ const note = annotationItem.querySelector('.annotation-note')?.value ?? ''
912
+ try {
913
+ await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
914
+ method: 'PATCH',
915
+ body: JSON.stringify({ note }),
916
+ })
917
+ toast('批注已保存')
918
+ await select(item.id)
919
+ await loadList()
920
+ } catch (error) {
921
+ toast(error.message, true)
922
+ }
923
+ return
924
+ }
925
+ if (action === 'annotation-color') {
926
+ if (annotationId === undefined) return
927
+ const color = event.target.closest('[data-color]')?.dataset.color
928
+ if (color === undefined) return
929
+ try {
930
+ await api(`/items/${encodeURIComponent(item.id)}/annotations/${encodeURIComponent(annotationId)}`, {
931
+ method: 'PATCH',
932
+ body: JSON.stringify({ color }),
933
+ })
934
+ toast('颜色已更新')
935
+ await select(item.id)
936
+ await loadList()
937
+ } catch (error) {
938
+ toast(error.message, true)
939
+ }
940
+ }
941
+ })
942
+
943
+ if (els.selectionToolbar !== null) {
944
+ els.selectionToolbar.addEventListener('mousedown', event => {
945
+ if (event.target.closest('button') !== null) event.preventDefault()
946
+ })
947
+ els.selectionToolbar.addEventListener('click', event => {
948
+ const color = event.target.closest('[data-color]')?.dataset.color
949
+ if (color !== undefined) {
950
+ state.selectionColor = color
951
+ for (const dot of els.selectionToolbar.querySelectorAll('[data-color]')) {
952
+ dot.classList.toggle('active', dot.dataset.color === color)
953
+ }
954
+ return
955
+ }
956
+ const action = event.target.closest('[data-action]')?.dataset.action
957
+ if (action === 'save-highlight') saveSelectionAnnotation()
958
+ })
959
+ }
960
+
961
+ let selectionTimer
962
+ els.detail.addEventListener('mouseup', () => {
963
+ clearTimeout(selectionTimer)
964
+ selectionTimer = setTimeout(updateSelectionToolbar, 0)
965
+ })
966
+ els.detail.addEventListener('keyup', event => {
967
+ if (!event.shiftKey) return
968
+ clearTimeout(selectionTimer)
969
+ selectionTimer = setTimeout(updateSelectionToolbar, 0)
970
+ })
971
+ els.detail.addEventListener('scroll', hideSelectionToolbar, { passive: true })
972
+ window.addEventListener('resize', hideSelectionToolbar)
973
+ els.detail.addEventListener('keydown', event => {
974
+ if (event.key !== 'Enter') return
975
+ const input = event.target.closest?.('.annotation-note')
976
+ if (input === null || input === undefined) return
977
+ event.preventDefault()
978
+ input.closest('.annotation-item')?.querySelector('[data-action="save-annotation-note"]')?.click()
979
+ })
980
+
981
+ document.addEventListener('keydown', event => {
982
+ const target = event.target
983
+ const typing = target instanceof HTMLElement && (target.matches('input, textarea, select') || target.isContentEditable)
984
+ if (event.key === '/' && !typing) {
985
+ event.preventDefault()
986
+ els.search.focus()
987
+ return
988
+ }
989
+ if (event.key === 'Escape') {
990
+ hideSelectionToolbar()
991
+ hideViewForm()
992
+ if (document.activeElement === els.search) {
993
+ els.search.value = ''
994
+ state.q = ''
995
+ loadList()
996
+ } else {
997
+ els.layout.classList.remove('detail-open')
998
+ }
999
+ return
1000
+ }
1001
+ if (typing) return
1002
+ if (event.key === 'j') {
1003
+ event.preventDefault()
1004
+ moveSelection(1)
1005
+ } else if (event.key === 'k') {
1006
+ event.preventDefault()
1007
+ moveSelection(-1)
1008
+ }
1009
+ })
1010
+
1011
+ updateTabs()
1012
+ loadStats()
1013
+ loadViews()
1014
+ loadList()