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