dsh-half-page 0.3.53 → 0.4.48

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.
Files changed (5) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +15 -6
  3. package/client.js +1013 -689
  4. package/index.js +1100 -125
  5. package/package.json +3 -2
package/client.js CHANGED
@@ -1,689 +1,1013 @@
1
- /**
2
- * dsh-half-page — 半页(Client 半边)
3
- * 只做统计面板:读到哪、写了什么、她的作品;不显示正文(点「显示原文」才取)。
4
- */
5
- // 注意:下面的 id 必须等于 package.json 的 name(DSH 按入口名判重,不一致会白屏报 duplicate factory registration)
6
- window.__ModuleLoader__.load({
7
- id: 'dsh-half-page',
8
- factory(require) {
9
- const React = require('react')
10
- const h = React.createElement
11
- const { useState, useEffect, useMemo } = React
12
-
13
- // 浅色主题,跟 DSH 主界面一致(深底浅字会和白界面不和谐)
14
- const C = {
15
- text: '#1c2430', dim: '#5d6878', line: '#e1e6ee',
16
- bg: '#ffffff', card: '#f7f9fc', accent: '#2f6fed', ok: '#12876b', warn: '#b46a00',
17
- }
18
- const S = {
19
- tag: { fontSize: 11, padding: '1px 7px', borderRadius: 9, border: '1px solid ' + C.line, background: C.card, color: C.dim, cursor: 'pointer' },
20
- tagOn: { fontSize: 11, padding: '1px 7px', borderRadius: 9, border: '1px solid ' + C.accent, background: '#eaf1ff', color: C.accent, cursor: 'pointer' },
21
-
22
- wrap: { padding: '14px 16px', fontSize: 13, color: C.text, display: 'flex', flexDirection: 'column', gap: 12, height: '100%', boxSizing: 'border-box', overflow: 'auto', background: C.bg },
23
- row: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
24
- dim: { color: C.dim, fontSize: 12 },
25
- card: { border: '1px solid ' + C.line, borderRadius: 10, padding: '10px 12px', background: C.card },
26
- btn: { border: '1px solid ' + C.line, background: '#fff', color: C.text, borderRadius: 8, padding: '4px 10px', fontSize: 12, cursor: 'pointer' },
27
- btnOn: { border: '1px solid ' + C.accent, background: 'rgba(47,111,237,0.10)', color: C.accent, borderRadius: 8, padding: '4px 10px', fontSize: 12, cursor: 'pointer' },
28
- tab: (on) => ({ padding: '5px 14px', borderRadius: 8, cursor: 'pointer', fontSize: 13, color: on ? '#fff' : C.dim, background: on ? C.accent : '#fff', border: '1px solid ' + (on ? C.accent : C.line) }),
29
- bar: { height: 6, borderRadius: 99, background: '#e8edf5', overflow: 'hidden', flex: 1, minWidth: 100 },
30
- fill: { height: '100%', background: 'linear-gradient(90deg,#2f6fed,#12876b)' },
31
- note: { borderLeft: '2px solid rgba(18,135,107,0.45)', paddingLeft: 10, marginBottom: 8, lineHeight: 1.7, whiteSpace: 'pre-wrap' },
32
- text: { whiteSpace: 'pre-wrap', lineHeight: 1.75, fontSize: 13, maxHeight: 360, overflow: 'auto', background: '#fff', borderRadius: 8, padding: '10px 12px', border: '1px solid ' + C.line },
33
- item: { display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 8, border: '1px solid transparent' },
34
- input: { background: '#fff', color: C.text, border: '1px solid ' + C.line, borderRadius: 8, padding: '4px 8px', fontSize: 13, width: 72 },
35
- }
36
-
37
- const fmt = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + 'M' : n >= 1024 ? Math.round(n / 1024) + 'K' : String(n)
38
-
39
- function studyLine(s) {
40
- if (!s) return ''
41
- const last = s.lastAt ? new Date(s.lastAt).toLocaleString('zh-CN', { hour12: false }) : '还没有'
42
- const byDay = s.mode === 'day'
43
- const used = byDay ? (s.dayCount || 0) : (s.weekCount || 0)
44
- const cap = byDay ? (s.perDay || 1) : (s.perWeek || 3)
45
- return '上次提醒:' + last + ' · ' + (byDay ? '今天' : '本周') + '已叫 ' + used + '/' + cap + ' 次'
46
- }
47
- const copy = (t) => { try { navigator.clipboard.writeText(t) } catch {} }
48
-
49
- async function getJson(url, opt) {
50
- const r = await fetch(url, opt)
51
- return r.json()
52
- }
53
-
54
- // 把读后感 md 拆成 [{book, chapters:[{title, lines:[]}], raw}]
55
- function parseNotes(md) {
56
- const out = []
57
- let book = null, ch = null
58
- for (const line of String(md || '').split(/\r?\n/)) {
59
- if (/^##\s+/.test(line)) {
60
- book = { book: line.replace(/^##\s+/, '').trim(), chapters: [] }
61
- out.push(book); ch = null
62
- } else if (/^###\s+/.test(line)) {
63
- ch = { title: line.replace(/^###\s+/, '').trim(), lines: [] }
64
- if (book) book.chapters.push(ch)
65
- } else if (/^[-*]\s+/.test(line)) {
66
- if (ch) {
67
- const t = line.replace(/^[-*]\s+/, '')
68
- ch.lines.push(t)
69
- // 署名行里带着时间:- ↳ 来自:鹿野 · 2026-11-10 20:31
70
- if (/^↳/.test(t)) {
71
- const m = t.match(/(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})/)
72
- if (m) ch.at = m[1] + ' ' + m[2]
73
- const b = t.replace(/^\u21b3\s*\u6765\u81ea\uff1a/, '').split('\u00b7')[0].trim()
74
- if (b) ch.by = b
75
- }
76
- }
77
- }
78
- }
79
- return out
80
- }
81
-
82
- const CN_DIGIT = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }
83
- const cnNum = (s) => {
84
- const t = String(s || '').replace(/[0-9]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 65248))
85
- if (/^[0-9]+$/.test(t)) return Number(t)
86
- let n = 0
87
- let cur = 0
88
- for (const ch of t) {
89
- if (ch === '十') { n += (cur || 1) * 10; cur = 0 }
90
- else if (ch === '百') { n += (cur || 1) * 100; cur = 0 }
91
- else if (ch === '千') { n += (cur || 1) * 1000; cur = 0 }
92
- else if (CN_DIGIT[ch] !== undefined) cur = CN_DIGIT[ch]
93
- else return NaN
94
- }
95
- return n + cur
96
- }
97
- const chapterNo = (title) => {
98
- // 标题可能是「第 3–7 章」(带空格与范围),所以先去空格再取第一个数字
99
- const t = String(title || '').replace(/\s+/g, '')
100
- const m = t.match(/第([0-90-9零〇一二三四五六七八九十百千两]+)/)
101
- return m ? cnNum(m[1]) : NaN
102
- }
103
- // 有几章、从第几章到第几章(章名认不出数字就不显示范围)
104
- const chapterRange = (chapters) => {
105
- const nos = (chapters || []).map((c) => chapterNo(c && c.title)).filter((n) => Number.isFinite(n))
106
- if (!nos.length) return ''
107
- const a = Math.min.apply(null, nos)
108
- const b = Math.max.apply(null, nos)
109
- return a === b ? ('第 ' + a + ' 章') : ('第 ' + a + '–' + b + ' 章')
110
- }
111
-
112
- function Panel() {
113
- const [state, setState] = useState(null)
114
- const [confirmId, setConfirmId] = useState('')
115
- const [tab, setTab] = useState('read')
116
- const [raw, setRaw] = useState('')
117
- const [showRaw, setShowRaw] = useState(false)
118
- const [works, setWorks] = useState(null)
119
- const [opened, setOpened] = useState(null)
120
- const [cfg, setCfg] = useState(null)
121
- const [msg, setMsg] = useState('')
122
- const [busy, setBusy] = useState(false)
123
- const [recent, setRecent] = useState(null)
124
- const [noteView, setNoteView] = useState({})
125
- const [bookAct, setBookAct] = useState(0)
126
- // 大图查看器:面板跑在 iframe 里,window.open 会被拦,所以自己在面板内弹一层
127
- const [viewer, setViewer] = useState(null)
128
- useEffect(() => {
129
- if (!viewer) return undefined
130
- const onKey = (e) => { if (e.key === 'Escape') setViewer(null) }
131
- window.addEventListener('keydown', onKey)
132
- return () => window.removeEventListener('keydown', onKey)
133
- }, [viewer])
134
- const NOTE_PAGE = 10
135
- let importPath = ''
136
-
137
- const load = async () => {
138
- try {
139
- const st = await getJson('/dsh-reading.state')
140
- setState(st)
141
- if (st && st.notes) setRaw(st.notes)
142
- const c = await getJson('/dsh-reading.config')
143
- if (c && c.ok) setCfg(c.config || {})
144
- const rc = await getJson('/dsh-reading.recent')
145
- if (rc && rc.ok) setRecent(rc)
146
- } catch (e) { setMsg('读不到状态:' + String(e && e.message || e)) }
147
- }
148
- useEffect(() => { load() }, [])
149
-
150
- const notes = useMemo(() => parseNotes(raw), [raw])
151
- const cur = state && state.books && state.books.find((b) => b.id === state.current)
152
- const favs = (cfg && cfg.favorites) || []
153
-
154
- const advance = async () => {
155
- if (busy) return
156
- setBusy(true)
157
- try {
158
- const r = await getJson('/dsh-reading.advance', { method: 'POST' })
159
- if (r && r.ok) { setMsg('推进到第 ' + r.chapter + ' 章'); await load() }
160
- else setMsg('没推进:' + (r && r.error || '未知'))
161
- } finally { setBusy(false) }
162
- }
163
-
164
- const backOne = async () => {
165
- if (busy) return
166
- setBusy(true)
167
- try {
168
- const r = await getJson('/dsh-reading.back', { method: 'POST' })
169
- if (r && r.ok) { setMsg('退回第 ' + r.chapter + ' 章'); await load() }
170
- else setMsg('没退:' + (r && r.error || '未知'))
171
- } finally { setBusy(false) }
172
- }
173
-
174
-
175
- const STATES = ['在写', '写完了', '搁下了']
176
- const cycleStatus = async (f) => {
177
- const i = STATES.indexOf(f.status || '')
178
- const next = i < 0 ? STATES[0] : (i === STATES.length - 1 ? '' : STATES[i + 1])
179
- await fetch('/dsh-reading.workstatus', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ rel: f.rel, status: next }) })
180
- await loadWorks()
181
- }
182
-
183
- const BOOK_STATES = ['在读', '已读完', '弃坑']
184
- const removeBook = async (id) => {
185
- setConfirmId('')
186
- await getJson('/dsh-reading.removeBook', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }) })
187
- const j = await getJson('/dsh-reading.state')
188
- if (j && j.ok) setState(j)
189
- }
190
-
191
- const cycleBook = async (b) => {
192
- const i = BOOK_STATES.indexOf(b.status || '')
193
- const next = i < 0 ? BOOK_STATES[0] : (i === BOOK_STATES.length - 1 ? '' : BOOK_STATES[i + 1])
194
- await getJson('/dsh-reading.bookstatus', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: b.id, status: next }) })
195
- const j = await getJson('/dsh-reading.state')
196
- if (j && j.ok) setState(j)
197
- }
198
-
199
- const loadWorks = async () => {
200
- const r = await getJson('/dsh-reading.works')
201
- if (r && r.ok) setWorks(r) ; else setMsg('作品目录读不到:' + (r && r.error))
202
- }
203
- const openFile = async (f) => {
204
- if (opened && opened.path === f.path) return setOpened(null)
205
- if (f.kind !== 'text') return setOpened({ ...f, text: '(' + f.kind + ',路径:' + f.path + ')' })
206
- const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.path))
207
- setOpened({ ...f, text: r && r.ok ? r.text : '读不到:' + (r && r.error) })
208
- }
209
-
210
- const toggleFav = async (key) => {
211
- const next = favs.includes(key) ? favs.filter((x) => x !== key) : favs.concat(key)
212
- const r = await getJson('/dsh-reading.config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ favorites: next }) })
213
- if (r && r.ok) { setCfg(r.config); setMsg(favs.includes(key) ? '已取消收藏' : '已收藏') }
214
- }
215
-
216
- const copyFav = async (f) => {
217
- if (String(f).startsWith('file:')) {
218
- const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.slice(5)))
219
- if (r && r.ok) { copy(r.text); setMsg('已复制正文') } else setMsg('复制失败:' + (r && r.error))
220
- return
221
- }
222
- const [book, chapter] = String(f).split('|')
223
- const bk = notes.find((x) => x.book === book)
224
- const ch = bk && (bk.chapters || []).find((x) => x.title === chapter)
225
- if (ch) { copy(ch.lines.join('\n')); setMsg('已复制这条读后感') } else setMsg('这条读后感已经不在了')
226
- }
227
-
228
- // 收藏页点一下就地展开:作品看正文,读后感看那一条
229
- const openFav = async (f) => {
230
- const key = 'fav:' + f
231
- if (opened && opened.path === key) return setOpened(null)
232
- if (String(f).startsWith('file:')) {
233
- const p = f.slice(5)
234
- const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(p))
235
- return setOpened({ path: key, title: p, text: r && r.ok ? r.text : '读不到:' + (r && r.error) })
236
- }
237
- const parts = String(f).split('|')
238
- const bk = notes.find((x) => x.book === parts[0])
239
- const ch = bk && (bk.chapters || []).find((x) => x.title === parts[1])
240
- setOpened({ path: key, title: parts.join(' · '), text: ch ? ch.lines.join('\n') : '这条读后感已经不在了' })
241
- }
242
-
243
- const saveCfg = async (patch) => {
244
- const r = await getJson('/dsh-reading.config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch) })
245
- if (r && r.ok) { setCfg(r.config); setMsg('已保存') ; await load() } else setMsg('保存失败:' + (r && r.error))
246
- }
247
-
248
- const head = h('div', { style: S.card },
249
- h('div', { style: S.row },
250
- h('div', { style: { fontWeight: 600, fontSize: 14 } }, cur ? ('正在读《' + cur.id + '》') : '还没导入书'),
251
- h('div', { style: S.dim }, state ? ('今天 ' + state.readToday + '/' + state.perDay + ' 章') : ''),
252
- h('div', { style: { flex: 1 } }),
253
- h('button', { style: S.btn, onClick: load }, '刷新'),
254
- ),
255
- cur ? h('div', { style: { ...S.row, marginTop: 8 } },
256
- h('div', { style: S.bar }, h('div', { style: { ...S.fill, width: Math.min(100, ((cur.readThrough || 0) / (cur.chapters || 1)) * 100) + '%' } })),
257
- h('div', { style: S.dim }, '读到第 ' + (cur.readThrough || 0) + ' / ' + cur.chapters + ' 章'),
258
- ) : null,
259
- )
260
-
261
- const tabs = h('div', { style: S.row },
262
- ['read', 'works', 'fav', 'set'].map((k) => h('div', {
263
- key: k, style: S.tab(tab === k), onClick: () => { setTab(k); if ((k === 'works' || k === 'fav') && !works) loadWorks() },
264
- }, k === 'read' ? '读书' : k === 'works' ? '她的作品' : k === 'fav' ? '收藏' : '设置')),
265
- h('div', { style: { flex: 1 } }),
266
- msg ? h('div', { style: { ...S.dim, color: C.ok } }, msg) : null,
267
- )
268
-
269
- const readTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
270
- // 近况卡
271
- h('div', { style: S.card },
272
- h('div', { style: S.row },
273
- h('div', { style: { fontWeight: 600 } }, '近况'),
274
- h('div', { style: { flex: 1 } }),
275
- h('div', { style: S.dim }, recent ? (recent.today || '') : ''),
276
- ),
277
- h('div', { style: { marginTop: 6, marginBottom: 6 } }, recent && recent.status ? recent.status : '还没什么可报的。'),
278
- recent && recent.mood
279
- ? h('div', { style: { marginBottom: 6 } }, h('span', { style: S.tagOn }, recent.mood))
280
- : null,
281
- recent && recent.days && recent.days.length
282
- ? h('div', { style: { marginBottom: 4 } },
283
- h('div', { style: S.dim }, '这几天翻过的:'),
284
- recent.days.map((d, i) => h('div', { key: i, style: S.row },
285
- h('div', { style: S.dim }, d.day),
286
- h('div', { style: { flex: 1 } }, '《' + d.book + '》' + d.chapters + ' 章'),
287
- )),
288
- )
289
- : null,
290
- recent && recent.works && recent.works.length
291
- ? h('div', null,
292
- h('div', { style: S.dim }, '最近碰过的稿子:'),
293
- recent.works.map((w, i) => h('div', { key: i, style: S.row },
294
- h('div', { style: { flex: 1 } },
295
- h('div', null, w.rel),
296
- w.note ? h('div', { style: { ...S.dim, fontSize: 11 } }, w.note) : null,
297
- ),
298
- h('div', { style: S.dim }, w.days === 0 ? '今天' : w.days + ' 天前'),
299
- )),
300
- )
301
- : null,
302
- ),
303
-
304
- h('div', { style: S.card },
305
- h('div', { style: S.row },
306
- h('div', { style: { fontWeight: 600 } }, '这一本'),
307
- h('div', { style: { flex: 1 } }),
308
- h('button', { style: S.btn, onClick: backOne, disabled: busy }, busy ? '…' : '退一章'),
309
- h('button', { style: S.btn, onClick: advance, disabled: busy }, busy ? '…' : '推进一章'),
310
- h('button', { style: showRaw ? S.btnOn : S.btn, onClick: async () => {
311
- if (!showRaw && cur) {
312
- const r = await getJson('/dsh-reading.chapter?book=' + encodeURIComponent(cur.id) + '&n=' + (cur.readThrough || 1))
313
- if (r && r.ok) setOpened({ path: 'chapter', text: r.text, title: r.title })
314
- }
315
- setShowRaw(!showRaw)
316
- } }, showRaw ? '收起原文' : '显示原文'),
317
- ),
318
- showRaw && opened && opened.path === 'chapter'
319
- ? h('div', { style: { ...S.text, marginTop: 8 } }, (opened.title ? opened.title + '\n\n' : '') + opened.text)
320
- : null,
321
- ),
322
- h('div', { style: S.card },
323
- h('div', { style: { fontWeight: 600, marginBottom: 6 } }, '书架'),
324
- (state && state.books && state.books.length) ? state.books.map((b, i) => {
325
- const done = (b.readThrough || 0) >= (b.chapters || 1)
326
- return h('div', { key: i, style: S.row },
327
- h('div', { style: { flex: 1, color: b.id === (state && state.current) ? C.accent : C.text } }, b.id),
328
- h('div', { style: S.dim }, (b.readThrough || 0) + '/' + b.chapters),
329
- h('button', {
330
- style: b.status === '弃坑' ? { ...S.tag, color: C.warn } : (done || b.status === '已读完' ? { ...S.tag, color: C.ok } : S.tag),
331
- title: '点一下换状态:在读 → 已读完 → 弃坑 → 不标',
332
- onClick: () => cycleBook(b),
333
- }, b.status || (done ? '已读完' : '在读')),
334
- h('button', {
335
- style: { ...S.tag, color: confirmId === b.id ? C.warn : C.dim, marginLeft: 6 },
336
- title: confirmId === b.id
337
- ? '再点一下就从书架拿下来(文件会移到 books/.trash,读后感不动)'
338
- : '从书架拿下来(文件移到 books/.trash,可手工找回;读后感不动)',
339
- onClick: () => (confirmId === b.id ? removeBook(b.id) : setConfirmId(b.id)),
340
- }, confirmId === b.id ? '确认?' : '下架'),
341
- )
342
- }) : h('div', { style: S.dim }, '还没有书。'),
343
- ),
344
- h('div', { style: S.card },
345
- notes.length ? (() => {
346
- const act = Math.min(bookAct, notes.length - 1)
347
- const bk = notes[act]
348
- const bi = act
349
- const v = noteView[bi] || {}
350
- const all = !!v.all
351
- const total = bk.chapters.length
352
- const pages = Math.max(1, Math.ceil(total / NOTE_PAGE))
353
- const page = Math.min(v.page || 0, pages - 1)
354
- // 排序:章节升 / 章节降 / 时间新在前(没写时间的排在后面)
355
- const sortLabels = ['章节 \u2191', '章节 \u2193', '时间 \u2193']
356
- const sortMode = (v.sort === undefined ? ((state && state.noteSort) || 0) : v.sort) % 3
357
- const sorted = bk.chapters.slice()
358
- if (sortMode === 1) sorted.sort((a, b) => (chapterNo(b.title) || -1) - (chapterNo(a.title) || -1))
359
- else if (sortMode === 2) sorted.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')))
360
- else sorted.sort((a, b) => (chapterNo(a.title) || 1e9) - (chapterNo(b.title) || 1e9))
361
- const list = all ? sorted : sorted.slice(page * NOTE_PAGE, page * NOTE_PAGE + NOTE_PAGE)
362
- const setView = (patch) => setNoteView(Object.assign({}, noteView, { [bi]: Object.assign({}, v, patch) }))
363
- const saveSort = (n) => { try { getJson('/dsh-reading.notesort', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sort: n }) }) } catch (e) {} }
364
- const paged = total > NOTE_PAGE
365
- const tabs = h('div', { style: { ...S.row, gap: 6, marginBottom: 8, flexWrap: 'wrap' } },
366
- notes.map((n, ni) => h('button', {
367
- key: ni,
368
- style: ni === act ? S.btnOn : S.btn,
369
- onClick: () => setBookAct(ni),
370
- }, n.book)),
371
- )
372
- return [tabs, h('div', { key: bi, style: { marginBottom: 10 } },
373
- h('div', { style: { ...S.row, marginBottom: 4 } },
374
- h('div', { style: { fontWeight: 600 } }, bk.book),
375
- h('div', { style: S.dim }, total + ' 段'),
376
- h('div', { style: { flex: 1 } }),
377
- paged ? h('button', { style: S.btn, disabled: page <= 0, onClick: () => setView({ page: page - 1 }) }, '‹') : null,
378
- paged ? h('div', { style: { ...S.dim, minWidth: 46, textAlign: 'center' } }, all ? '全部' : ((page + 1) + ' / ' + pages)) : null,
379
- paged ? h('button', { style: S.btn, disabled: all || page >= pages - 1, onClick: () => setView({ page: page + 1 }) }, '›') : null,
380
- paged ? h('button', { style: all ? S.btnOn : S.btn, onClick: () => setView({ all: !all, page: 0 }) }, all ? '分页' : '全部') : null,
381
- h('button', { style: S.btnOn, onClick: () => { const next = (sortMode + 1) % 3; setView({ sort: next, page: 0 }); saveSort(next) } }, sortLabels[sortMode]),
382
- h('button', { style: S.btn, onClick: () => copy(bk.chapters.map((c) => '## ' + c.title + '\n' + c.lines.join('\n')).join('\n\n')) }, '复制这本'),
383
- ),
384
- (sortMode === 2 && bk.chapters.filter((c) => !c.at).length) ? h('div', { style: { ...S.dim, marginBottom: 6 } }, '有 ' + bk.chapters.filter((c) => !c.at).length + ' 段早期笔记当时没记时间,排在最后。') : null,
385
- list.map((c, ci) => h('div', { key: ci, style: { marginBottom: 6 } },
386
- h('div', { style: S.row },
387
- h('div', { style: { ...S.dim, color: C.warn } }, c.title),
388
- h('button', { style: S.btn, onClick: () => toggleFav(bk.book + '|' + c.title) }, favs.includes(bk.book + '|' + c.title) ? '★' : '☆'),
389
- h('button', { style: S.btn, onClick: () => copy(c.lines.join('\n')) }, '复制'),
390
- ),
391
- c.lines.map((l, li) => h('div', { key: li, style: /^↳/.test(l) ? { ...S.dim, marginTop: 4 } : S.note }, l)),
392
- )),
393
- )]
394
- })() : h('div', { style: S.dim }, '还没写过。读完一段记两句,这里就有了。'),
395
- ),
396
- )
397
-
398
- const worksTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
399
- h('div', { style: S.card },
400
- h('div', { style: S.row },
401
- h('div', { style: { fontWeight: 600 } }, '她的作品'),
402
- h('div', { style: S.dim }, works ? (works.root + ' · ' + works.files.length + ' 个文件' + ((works.images && works.images.length) ? (' · ' + works.images.length + ' 张图') : '')) : ''),
403
- h('div', { style: { flex: 1 } }),
404
- h('button', { style: S.btn, onClick: loadWorks }, '重新扫描'),
405
- ),
406
- !works ? h('div', { style: { ...S.dim, marginTop: 8 } }, '点「重新扫描」列出作品目录。') :
407
- (works.files.length ? works.files.map((f, i) => h('div', { key: i, style: { ...S.item, borderTop: '1px solid ' + C.line } },
408
- h('div', { style: { flex: '0 1 auto', cursor: 'pointer' }, onClick: () => openFile(f) }, f.rel),
409
- h('div', { style: { ...S.dim, marginLeft: 10 } }, (() => {
410
- const d = Math.floor((Date.now() - new Date(f.mtime).getTime()) / 86400000)
411
- return d <= 0 ? '今天改过' : (d === 1 ? '昨天改过' : d + ' 天前改过')
412
- })()),
413
- h('div', { style: f.author ? S.dim : { ...S.dim, color: C.warn } }, f.author ? ('署名 · ' + f.author) : '未署名'),
414
- h('div', { style: { flex: 1 } }),
415
- h('button', {
416
- style: f.status === '在写' ? S.tagOn : S.tag,
417
- title: '点一下换状态:在写 → 写完了 → 搁下了 → 不标',
418
- onClick: () => cycleStatus(f),
419
- }, f.status || '—'),
420
- h('div', { style: S.dim }, f.kind + ' · ' + fmt(f.size)),
421
- h('button', { style: S.btn, onClick: () => toggleFav('file:' + f.path) }, favs.includes('file:' + f.path) ? '★' : '☆'),
422
- f.kind === 'text' ? h('button', { style: S.btn, onClick: async () => {
423
- const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.path))
424
- if (r && r.ok) { copy(r.text); setMsg('已复制全文') }
425
- } }, '复制') : h('button', { style: S.btn, onClick: () => { copy(f.path); setMsg('已复制路径') } }, '复制路径'),
426
- )) : h('div', { style: { ...S.dim, marginTop: 8 } }, '这里还是空的:把 .md 或 .txt 放进 ' + works.root + ',点「重新扫描」就会出现。')),
427
- opened ? h('div', { style: { ...S.text, marginTop: 10 } }, (opened.title || opened.rel || '') + '\n\n' + opened.text) : null,
428
- ),
429
- (works && works.images && works.images.length) ? h('div', { style: S.card },
430
- h('div', { style: S.row },
431
- h('div', { style: { fontWeight: 600 } }, '画'),
432
- h('div', { style: S.dim }, '作品目录与 art 里的图 · 新的在前 · 点一张看大图'),
433
- ),
434
- h('div', {
435
- style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 10, marginTop: 10 },
436
- },
437
- works.images.map((m, i) => h('div', {
438
- key: 'img' + i,
439
- style: { border: '1px solid ' + C.line, borderRadius: 8, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: 'rgba(255,255,255,0.02)' },
440
- },
441
- h('div', {
442
- style: { cursor: 'zoom-in', lineHeight: 0, background: 'rgba(0,0,0,0.15)' },
443
- title: m.path,
444
- onClick: () => setViewer(m),
445
- }, h('img', {
446
- src: m.url,
447
- alt: m.name,
448
- loading: 'lazy',
449
- style: { width: '100%', height: 120, objectFit: 'cover', display: 'block' },
450
- })),
451
- h('div', { style: { padding: '6px 8px', display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 } },
452
- h('div', { style: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: m.rel }, m.name),
453
- h('div', { style: { ...S.dim, fontSize: 11 } }, (m.width && m.height ? (m.width + '×' + m.height + ' · ') : '') + fmt(m.size)),
454
- h('div', { style: { ...S.dim, fontSize: 11 } }, new Date(m.mtime).toLocaleString()),
455
- ),
456
- )),
457
- ),
458
- ) : null,
459
- )
460
-
461
- const setTabView = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
462
- h('div', { style: S.card },
463
- h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '阅读'),
464
- h('div', { style: { ...S.row, marginBottom: 6 } },
465
- h('div', null, '每日章节上限'), h('input', { style: S.input, type: 'number', defaultValue: (cfg && cfg.perDay) || 20, onBlur: (e) => saveCfg({ perDay: Number(e.target.value) || 0 }) }),
466
- ),
467
- h('div', { style: { ...S.row, marginBottom: 6 } },
468
- h('div', null, '每几章写一次读后感'), h('input', { style: S.input, type: 'number', defaultValue: (cfg && cfg.notesEvery) || 1, onBlur: (e) => saveCfg({ notesEvery: Number(e.target.value) || 1 }) }),
469
- ),
470
- h('div', { style: S.row },
471
- h('label', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
472
- h('input', {
473
- type: 'checkbox',
474
- defaultChecked: (cfg ? cfg.quietEnabled !== false : true),
475
- onChange: (e) => saveCfg({ quietEnabled: e.target.checked }),
476
- }),
477
- h('span', null, '启用静音'),
478
- ),
479
- h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.quietFrom) || '', placeholder: '03:00', onBlur: (e) => saveCfg({ quietFrom: e.target.value }) }),
480
- h('div', { style: S.dim }, '至'),
481
- h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.quietTo) || '', placeholder: '08:00', onBlur: (e) => saveCfg({ quietTo: e.target.value }) }),
482
- h('div', { style: S.dim }, '拦 reading_next,手动读需传 force: true'),
483
- ),
484
- h('div', { style: { ...S.row, marginBottom: 6, marginTop: 10, paddingTop: 10, borderTop: '1px solid ' + C.line } },
485
- h('label', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
486
- h('input', {
487
- type: 'checkbox',
488
- defaultChecked: !!(cfg && cfg.studyEnabled),
489
- onChange: (e) => saveCfg({ studyEnabled: e.target.checked }),
490
- }),
491
- h('span', null, '书房时间'),
492
- ),
493
- h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.studyFrom) || '', placeholder: '例 22:00', onBlur: (e) => saveCfg({ studyFrom: e.target.value }) }),
494
- h('div', { style: S.dim }, '至'),
495
- h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.studyTo) || '', placeholder: '例 23:00', onBlur: (e) => saveCfg({ studyTo: e.target.value }) }),
496
- h('button', {
497
- style: S.btn,
498
- title: '点一下在「每周 / 每天」之间切换',
499
- onClick: () => saveCfg({ studyMode: ((cfg && cfg.studyMode) === 'day' ? 'week' : 'day') }),
500
- }, ((cfg && cfg.studyMode) === 'day') ? '每天' : '每周'),
501
- h('input', {
502
- key: 'study-per-' + (((cfg && cfg.studyMode) === 'day') ? 'day' : 'week'),
503
- style: { ...S.input, width: 56 },
504
- type: 'number', min: 1, max: 7,
505
- defaultValue: ((cfg && cfg.studyMode) === 'day')
506
- ? ((cfg && cfg.studyPerDay) || 1)
507
- : ((cfg && cfg.studyPerWeek) || 3),
508
- onBlur: (e) => {
509
- const v = Math.min(7, Math.max(1, Number(e.target.value) || 1))
510
- saveCfg(((cfg && cfg.studyMode) === 'day') ? { studyPerDay: v } : { studyPerWeek: v })
511
- },
512
- }),
513
- h('div', { style: S.dim }, '次'),
514
- ),
515
- h('div', { style: S.row },
516
- h('div', { style: S.dim }, '在'),
517
- h('select', {
518
- style: { ...S.input, width: 170 },
519
- defaultValue: (cfg && cfg.studySession) || '',
520
- onChange: (e) => saveCfg({ studySession: e.target.value }),
521
- },
522
- h('option', { key: '', value: '' }, '最近活跃的会话'),
523
- ((state && state.study && state.study.sessions) || [])
524
- .map((s) => h('option', { key: s.id, value: s.id }, s.title || ('会话 ' + String(s.id).slice(-8)))),
525
- ((cfg && cfg.studySession)
526
- && !((state && state.study && state.study.sessions) || []).some((s) => s.id === cfg.studySession))
527
- ? h('option', { key: 'cur', value: cfg.studySession }, '已选(这条会话现在没开着)')
528
- : null,
529
- ),
530
- h('div', { style: S.dim }, '里叫'),
531
- ),
532
- h('div', { style: { ...S.dim, marginBottom: 6 } }, '到点只在上面那条会话里说一句,读不读由它自己决定;默认关闭'),
533
- h('div', { style: { ...S.dim, marginBottom: 6 } }, '同时装着「鱼的心跳」的话,建议这条别勾——两边各叫各的,不会互相避让'),
534
- h('div', { style: S.dim }, studyLine(state && state.study)),
535
- ),
536
- h('div', { style: S.card },
537
- h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '导入一本书'),
538
- h('div', { style: S.row },
539
- h('button', {
540
- style: S.btnOn,
541
- onClick: () => {
542
- const el = document.getElementById('dsh-read-pick')
543
- if (el) el.click()
544
- },
545
- }, '选择文件…'),
546
- h('input', {
547
- id: 'dsh-read-pick',
548
- type: 'file',
549
- accept: '.txt,.md,text/plain',
550
- style: { display: 'none' },
551
- onChange: (e) => {
552
- const f = e.target.files && e.target.files[0]
553
- if (!f) return
554
- setMsg('读取 ' + f.name + '…')
555
- const rd2 = new FileReader()
556
- rd2.onload = async () => {
557
- try {
558
- const buf = new Uint8Array(rd2.result)
559
- let bin = ''
560
- const CH = 0x8000
561
- for (let i = 0; i < buf.length; i += CH) {
562
- bin += String.fromCharCode.apply(null, buf.subarray(i, i + CH))
563
- }
564
- const data = btoa(bin)
565
- setMsg('导入中…')
566
- const r = await fetch('/dsh-reading.importText', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: f.name, data }) })
567
- const j = await r.json()
568
- if (!j.ok) { setMsg('失败:' + (j.error || '未知')); return }
569
- setMsg('已导入 ' + (j.id || '') + '(' + (j.chapters || 0) + ' 章)')
570
- await load()
571
- } catch (err) { setMsg('失败:' + String(err)) }
572
- }
573
- rd2.readAsArrayBuffer(f)
574
- e.target.value = ''
575
- },
576
- }),
577
- h('div', { style: S.dim }, '点左边选文件,或把完整路径粘在下面'),
578
- ),
579
- h('div', { style: S.row },
580
- h('input', {
581
- style: { ...S.input, width: 300 },
582
- placeholder: 'D:\\...\\书名.txt 或 .md',
583
- onChange: (e) => { importPath = e.target.value },
584
- }),
585
- h('button', {
586
- style: S.btnOn,
587
- onClick: async () => {
588
- const p = String(importPath || '').trim()
589
- if (!p) { setMsg('先填文件路径'); return }
590
- setMsg('导入中…')
591
- try {
592
- const r = await fetch('/dsh-reading.import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: p }) })
593
- const j = await r.json()
594
- if (!j.ok) { setMsg('失败:' + (j.error || '未知')); return }
595
- setMsg('已导入 ' + (j.id || '') + '(' + (j.chapters || 0) + ' 章)')
596
- importPath = ''
597
- await load()
598
- } catch (e) { setMsg('失败:' + String(e)) }
599
- },
600
- }, '导入'),
601
- ),
602
- h('div', { style: S.dim }, '只认 .txt / .md,会复制到书架并统计章数。'),
603
- ),
604
- h('div', { style: S.card },
605
- h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '写作'),
606
- h('div', { style: S.row },
607
- h('div', null, '开启写作功能'),
608
- h('button', { style: (cfg && cfg.writing) ? S.btnOn : S.btn, onClick: () => saveCfg({ writing: !(cfg && cfg.writing) }) }, (cfg && cfg.writing) ? '已开启' : '已关闭'),
609
- h('div', { style: S.dim }, '关掉后我只读书,不写东西'),
610
- ),
611
- ),
612
- h('div', { style: S.card },
613
- h('div', { style: { fontWeight: 600, marginBottom: 6 } }, '导出'),
614
- h('div', { style: S.row },
615
- h('button', { style: S.btn, onClick: () => { copy(raw); setMsg('读后感已复制') } }, '复制读后感全文'),
616
- h('button', { style: S.btn, onClick: () => { copy(JSON.stringify(state, null, 2)); setMsg('进度已复制') } }, '复制阅读进度 JSON'),
617
- ),
618
- h('div', { style: { ...S.dim, marginTop: 6 } }, cfg && cfg.favorites ? '' : ''),
619
- ),
620
- )
621
-
622
- const favTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
623
- h('div', { style: S.card },
624
- h('div', { style: { fontWeight: 600, marginBottom: 6 } }, '收藏'),
625
- favs.length ? favs.map((f, i) => {
626
- const isFile = String(f).startsWith('file:')
627
- const fpath = isFile ? f.slice(5) : ''
628
- const w = isFile && works && (works.files || []).find((x) => x.path === fpath)
629
- const who = w ? w.author : ''
630
- return h('div', { key: i, style: S.item },
631
- h('div', {
632
- style: { flex: 1, cursor: 'pointer', borderTop: i ? '1px solid ' + C.line : 'none', paddingTop: i ? 8 : 0 },
633
- onClick: () => openFav(f),
634
- }, String(f).startsWith('file:') ? f.slice(5) : f.replace('|', ' · ')),
635
- isFile ? h('div', { style: who ? S.dim : { ...S.dim, color: C.warn } }, who ? ('署名 · ' + who) : '未署名') : null,
636
- h('button', { style: S.btn, onClick: () => copyFav(f) }, '复制'),
637
- h('button', { style: S.btn, onClick: () => toggleFav(f) }, '取消收藏'),
638
- )
639
- }) : h('div', { style: S.dim }, '在读后感或作品上点 ☆,收藏的东西会出现在这儿。'),
640
- ),
641
- opened && String(opened.path || '').startsWith('fav:')
642
- ? h('div', { style: { ...S.text, marginTop: 0 } }, (opened.title ? opened.title + '\n\n' : '') + opened.text)
643
- : null,
644
- )
645
-
646
- const viewerLayer = viewer ? h('div', {
647
- style: {
648
- position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,14,22,0.86)',
649
- display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
650
- gap: 10, padding: 20, cursor: 'zoom-out',
651
- },
652
- onClick: () => setViewer(null),
653
- },
654
- h('img', {
655
- src: viewer.url,
656
- alt: viewer.name,
657
- onClick: (e) => e.stopPropagation(),
658
- style: { maxWidth: '94vw', maxHeight: '84vh', objectFit: 'contain', borderRadius: 6, boxShadow: '0 12px 48px rgba(0,0,0,0.55)', background: '#fff', minWidth: 120, cursor: 'default' },
659
- }),
660
- h('div', { style: { color: '#e8eef8', fontSize: 12, textAlign: 'center', maxWidth: '90vw', wordBreak: 'break-all' } },
661
- viewer.name + (viewer.width && viewer.height ? ' · ' + viewer.width + '×' + viewer.height : '') + ' · ' + fmt(viewer.size) + ' (点空白或按 Esc 关闭)'),
662
- h('div', { style: { color: 'rgba(232,238,248,0.55)', fontSize: 11, maxWidth: '90vw', wordBreak: 'break-all' } }, viewer.rel || ''),
663
- ) : null
664
-
665
- return h('div', { style: S.wrap },
666
- head,
667
- tabs,
668
- tab === 'read' ? readTab : tab === 'works' ? worksTab : tab === 'fav' ? favTab : setTabView,
669
- viewerLayer,
670
- )
671
- }
672
-
673
- function Boundary(props) {
674
- try { return h(Panel, props) } catch (e) {
675
- return h('div', { style: { padding: 14, color: '#ff8080', fontSize: 12 } }, '半页出错了:' + String((e && e.message) || e))
676
- }
677
- }
678
-
679
- return {
680
- inject: ['slots'],
681
- apply(ctx) {
682
- const slots = (typeof ctx.get === 'function' ? ctx.get('slots') : undefined) || ctx.slots
683
- if (!slots) return
684
- slots.inject('conversation.view', () => slots.register({ name: 'conversation.view', id: 'reading', order: 42, label: '半页' }, (props) => h(Boundary, props)))
685
- slots.inject('settings.section', () => slots.register({ name: 'settings.section', id: 'dsh-half-page', order: 66, label: '半页' }, () => h(Boundary)))
686
- },
687
- }
688
- },
689
- })
1
+ /**
2
+ * dsh-half-page — 半页(Client 半边)
3
+ * 只做统计面板:读到哪、写了什么、她的作品;不显示正文(点「显示原文」才取)。
4
+ */
5
+ // 注意:下面的 id 必须等于 package.json 的 name(DSH 按入口名判重,不一致会白屏报 duplicate factory registration)
6
+ window.__ModuleLoader__.load({
7
+ id: 'dsh-half-page',
8
+ factory(require) {
9
+ const React = require('react')
10
+ const h = React.createElement
11
+ const { useState, useEffect, useMemo } = React
12
+ // 书名自带《》时别再套一层
13
+ const showTitle = (t) => { const s = String(t || ''); return /^《/.test(s) ? s : '《' + s + '》' }
14
+
15
+ // 浅色主题,跟 DSH 主界面一致(深底浅字会和白界面不和谐)
16
+ const C = {
17
+ text: '#1c2430', dim: '#5d6878', line: '#e1e6ee',
18
+ bg: '#ffffff', card: '#f7f9fc', accent: '#2f6fed', ok: '#12876b', warn: '#b46a00',
19
+ }
20
+ const S = {
21
+ tag: { fontSize: 11, padding: '1px 7px', borderRadius: 9, border: '1px solid ' + C.line, background: C.card, color: C.dim, cursor: 'pointer' },
22
+ tagOn: { fontSize: 11, padding: '1px 7px', borderRadius: 9, border: '1px solid ' + C.accent, background: '#eaf1ff', color: C.accent, cursor: 'pointer' },
23
+
24
+ wrap: { padding: '14px 16px', fontSize: 13, color: C.text, display: 'flex', flexDirection: 'column', gap: 12, height: '100%', boxSizing: 'border-box', overflow: 'auto', background: C.bg },
25
+ row: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
26
+ dim: { color: C.dim, fontSize: 12 },
27
+ card: { border: '1px solid ' + C.line, borderRadius: 10, padding: '10px 12px', background: C.card },
28
+ btn: { border: '1px solid ' + C.line, background: '#fff', color: C.text, borderRadius: 8, padding: '4px 10px', fontSize: 12, cursor: 'pointer' },
29
+ btnOn: { border: '1px solid ' + C.accent, background: 'rgba(47,111,237,0.10)', color: C.accent, borderRadius: 8, padding: '4px 10px', fontSize: 12, cursor: 'pointer' },
30
+ tab: (on) => ({ padding: '5px 14px', borderRadius: 8, cursor: 'pointer', fontSize: 13, color: on ? '#fff' : C.dim, background: on ? C.accent : '#fff', border: '1px solid ' + (on ? C.accent : C.line) }),
31
+ bar: { height: 6, borderRadius: 99, background: '#e8edf5', overflow: 'hidden', flex: 1, minWidth: 100 },
32
+ fill: { height: '100%', background: 'linear-gradient(90deg,#2f6fed,#12876b)' },
33
+ note: { borderLeft: '2px solid rgba(18,135,107,0.45)', paddingLeft: 10, marginBottom: 8, lineHeight: 1.7, whiteSpace: 'pre-wrap' },
34
+ text: { whiteSpace: 'pre-wrap', lineHeight: 1.75, fontSize: 13, maxHeight: 360, overflow: 'auto', background: '#fff', borderRadius: 8, padding: '10px 12px', border: '1px solid ' + C.line },
35
+ item: { display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 8, border: '1px solid transparent' },
36
+ input: { background: '#fff', color: C.text, border: '1px solid ' + C.line, borderRadius: 8, padding: '4px 8px', fontSize: 13, width: 72 },
37
+ }
38
+
39
+ const fmt = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + 'M' : n >= 1024 ? Math.round(n / 1024) + 'K' : String(n)
40
+
41
+ function studyLine(s) {
42
+ if (!s) return ''
43
+ const last = s.lastAt ? new Date(s.lastAt).toLocaleString('zh-CN', { hour12: false }) : '还没有'
44
+ const byDay = s.mode === 'day'
45
+ const used = byDay ? (s.dayCount || 0) : (s.weekCount || 0)
46
+ const cap = byDay ? (s.perDay || 1) : (s.perWeek || 3)
47
+ return '上次提醒:' + last + ' · ' + (byDay ? '今天' : '本周') + '已叫 ' + used + '/' + cap + ' 次'
48
+ }
49
+ const copy = (t) => { try { navigator.clipboard.writeText(t) } catch {} }
50
+
51
+ // 面板在 iframe 里,浏览器不让直接下载/选文件;备份交给宿主写盘,恢复给一个路径让宿主读
52
+ // 备份:由宿主弹「另存为」,用户自己选位置
53
+ async function backupAll() {
54
+ setBusy(true)
55
+ setMsg('正在打包…', 'bak')
56
+ try {
57
+ const r = await getJson('/dsh-reading.backupFile', { method: 'POST' })
58
+ if (r && r.ok) {
59
+ setLastBackup(r.path)
60
+ setMsg('已备份到 ' + r.path, 'bak')
61
+ try {
62
+ await getJson('/dsh-reading.reveal', {
63
+ method: 'POST',
64
+ headers: { 'content-type': 'application/json' },
65
+ body: JSON.stringify({ path: r.path }),
66
+ })
67
+ } catch {}
68
+ } else setMsg('备份失败:' + ((r && r.error) || '未知'), 'bak')
69
+ } catch (e) {
70
+ setMsg('备份失败:' + String(e), 'bak')
71
+ } finally { setBusy(false) }
72
+ }
73
+ async function reveal(p) {
74
+ try {
75
+ const r = await getJson('/dsh-reading.reveal', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: p }) })
76
+ if (!r || !r.ok) setMsg('打不开文件夹:' + ((r && r.error) || '未知'), 'bak')
77
+ } catch (e) { setMsg('打不开文件夹:' + String((e && e.message) || e), 'bak') }
78
+ }
79
+
80
+ async function checkUpd() {
81
+ setBusy(true)
82
+ try {
83
+ const r = await getJson('/dsh-reading.update')
84
+ if (r && r.ok) {
85
+ const d = new Date()
86
+ const pad = (n) => String(n).padStart(2, '0')
87
+ setUpd({ ...r, at: pad(d.getHours()) + ':' + pad(d.getMinutes()) })
88
+ setMsg(r.outdated ? ('发现新版本 ' + r.latest + ':可以点「复制更新命令」,在终端里跑') : (r.latest ? ('已是最新版 ' + r.current + ',不用更新') : '查不到 npm(可能离线),稍后再试'), 'upd')
89
+ } else setMsg('检测失败:' + ((r && r.error) || '未知'), 'upd')
90
+ } catch (e) { setMsg('检测失败:' + String((e && e.message) || e), 'upd') } finally { setBusy(false) }
91
+ }
92
+
93
+ // 恢复:由宿主弹「打开」,选完直接恢复
94
+ async function restoreFromPath() {
95
+ setBusy(true)
96
+ setMsg('正在读取备份…', 'bak')
97
+ try {
98
+ let path = (restorePath || '').trim()
99
+ if (!path) {
100
+ const pick = await getJson('/dsh-reading.pickFile', { method: 'POST' })
101
+ if (!pick || !pick.ok) {
102
+ setMsg((pick && pick.cancelled) ? '取消了,没恢复' : ('没选到文件:' + ((pick && pick.error) || '窗口没起来,可以直接把路径填在下面')), 'bak')
103
+ return
104
+ }
105
+ path = pick.path
106
+ setRestorePath(path)
107
+ }
108
+ const f = await getJson('/dsh-reading.readFile?path=' + encodeURIComponent(path))
109
+ if (!f || !f.ok) { setMsg('读不到那个文件:' + ((f && f.error) || '未知'), 'bak'); return }
110
+ const r = await getJson('/dsh-reading.restore', {
111
+ method: 'POST',
112
+ headers: { 'content-type': 'application/json' },
113
+ body: JSON.stringify({ json: f.text }),
114
+ })
115
+ if (r && r.ok) { setMsg('已恢复:' + (r.books || 0) + ' 本 · ' + (r.chapters || 0) + ' 段读后感', 'bak'); await load() }
116
+ else setMsg('恢复失败:' + ((r && r.error) || '未知'), 'bak')
117
+ } catch (e) {
118
+ setMsg('恢复失败:' + String(e), 'bak')
119
+ } finally { setBusy(false) }
120
+ }
121
+ async function getJson(url, opt) {
122
+ const r = await fetch(url, opt)
123
+ return r.json()
124
+ }
125
+
126
+ // 把读后感 md 拆成 [{book, chapters:[{title, lines:[]}], raw}]
127
+ function parseNotes(md) {
128
+ const out = []
129
+ let book = null, ch = null
130
+ for (const line of String(md || '').split(/\r?\n/)) {
131
+ if (/^##\s+/.test(line)) {
132
+ book = { book: line.replace(/^##\s+/, '').trim(), chapters: [] }
133
+ out.push(book); ch = null
134
+ } else if (/^###\s+/.test(line)) {
135
+ ch = { title: line.replace(/^###\s+/, '').trim(), lines: [] }
136
+ if (book) book.chapters.push(ch)
137
+ } else if (/^[-*]\s+/.test(line)) {
138
+ if (ch) {
139
+ const t = line.replace(/^[-*]\s+/, '')
140
+ ch.lines.push(t)
141
+ // 署名行里带着时间:- ↳ 来自:鹿野 · 2026-11-10 20:31
142
+ if (/^↳/.test(t)) {
143
+ const m = t.match(/(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2})/)
144
+ if (m) ch.at = m[1] + ' ' + m[2]
145
+ const b = t.replace(/^\u21b3\s*\u6765\u81ea\uff1a/, '').split('\u00b7')[0].trim()
146
+ if (b) ch.by = b
147
+ }
148
+ }
149
+ }
150
+ }
151
+ return out
152
+ }
153
+
154
+ const CN_DIGIT = { 零: 0, 〇: 0, 一: 1, 二: 2, 两: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 }
155
+ const cnNum = (s) => {
156
+ const t = String(s || '').replace(/[0-9]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 65248))
157
+ if (/^[0-9]+$/.test(t)) return Number(t)
158
+ let n = 0
159
+ let cur = 0
160
+ for (const ch of t) {
161
+ if (ch === '十') { n += (cur || 1) * 10; cur = 0 }
162
+ else if (ch === '百') { n += (cur || 1) * 100; cur = 0 }
163
+ else if (ch === '千') { n += (cur || 1) * 1000; cur = 0 }
164
+ else if (CN_DIGIT[ch] !== undefined) cur = CN_DIGIT[ch]
165
+ else return NaN
166
+ }
167
+ return n + cur
168
+ }
169
+ const chapterNo = (title) => {
170
+ // 标题可能是「第 3–7 章」(带空格与范围),所以先去空格再取第一个数字
171
+ const t = String(title || '').replace(/\s+/g, '')
172
+ const m = t.match(/第([0-90-9零〇一二三四五六七八九十百千两]+)/)
173
+ return m ? cnNum(m[1]) : NaN
174
+ }
175
+ // 有几章、从第几章到第几章(章名认不出数字就不显示范围)
176
+ const chapterRange = (chapters) => {
177
+ const nos = (chapters || []).map((c) => chapterNo(c && c.title)).filter((n) => Number.isFinite(n))
178
+ if (!nos.length) return ''
179
+ const a = Math.min.apply(null, nos)
180
+ const b = Math.max.apply(null, nos)
181
+ return a === b ? ('第 ' + a + ' 章') : ('第 ' + a + '–' + b + ' 章')
182
+ }
183
+
184
+ function Panel() {
185
+ const [state, setState] = useState(null)
186
+ const [confirmId, setConfirmId] = useState('')
187
+ const [pendingAdopt, setPendingAdopt] = useState('')
188
+ const [tab, setTab] = useState('read')
189
+ const [raw, setRaw] = useState('')
190
+ const [showRaw, setShowRaw] = useState(false)
191
+ const [works, setWorks] = useState(null)
192
+ const [opened, setOpened] = useState(null)
193
+ const [cfg, setCfg] = useState(null)
194
+ const [msg, setMsgRaw] = useState('')
195
+ const [msgAt, setMsgAt] = useState('')
196
+ const [restorePath, setRestorePath] = useState('')
197
+ const [lastBackup, setLastBackup] = useState('')
198
+ const [upd, setUpd] = useState(null)
199
+ const setMsg = (text, at = '') => { setMsgRaw(text); setMsgAt(at || '') }
200
+ const [busy, setBusy] = useState(false)
201
+ const [recent, setRecent] = useState(null)
202
+ const [noteView, setNoteView] = useState({})
203
+ const [bookAct, setBookAct] = useState(0)
204
+ const [shownBook, setShownBook] = useState('')
205
+ const [picking, setPicking] = useState(false)
206
+ const [picked, setPicked] = useState([])
207
+ // 读者:'' = 还没选;'__legacy__' = 总进度(全机),其余是会话 id
208
+ const TOTAL_READER = '__legacy__'
209
+ const [readerId, setReaderId] = useState('')
210
+ const [authorFilter, setAuthorFilter] = useState('')
211
+ // 大图查看器:面板跑在 iframe 里,window.open 会被拦,所以自己在面板内弹一层
212
+ const [viewer, setViewer] = useState(null)
213
+ useEffect(() => {
214
+ if (!viewer) return undefined
215
+ const onKey = (e) => { if (e.key === 'Escape') setViewer(null) }
216
+ window.addEventListener('keydown', onKey)
217
+ return () => window.removeEventListener('keydown', onKey)
218
+ }, [viewer])
219
+ const NOTE_PAGE = 10
220
+ let importPath = ''
221
+
222
+ const load = async (rid) => {
223
+ try {
224
+ const st = await getJson('/dsh-reading.state' + (rid ? '?reader=' + encodeURIComponent(rid) : ''))
225
+ setState(st)
226
+ if (st && st.notes) setRaw(st.notes)
227
+ const c = await getJson('/dsh-reading.config')
228
+ if (c && c.ok) setCfg(c.config || {})
229
+ } catch (e) { setMsg('读不到状态:' + String(e && e.message || e)) }
230
+ }
231
+ useEffect(() => { load(); fetch('/dsh-reading.update').then((r) => r.json()).then((r) => { if (r && r.ok) setUpd(r) }).catch(() => {}) }, [])
232
+
233
+ const notes = useMemo(() => parseNotes(raw), [raw])
234
+ // 打开面板默认显示「最近读过的那本」;手点书名只在本页临时切换(不写盘、不动进度)
235
+ const recentId = (state && state.books && state.books.filter((b) => b.lastReadAt).sort((a, b) => String(b.lastReadAt).localeCompare(String(a.lastReadAt)))[0] || {}).id || ''
236
+ const shownId = shownBook || recentId || (state && state.current) || ''
237
+ const cur = state && state.books && state.books.find((b) => b.id === shownId)
238
+ const favs = (cfg && cfg.favorites) || []
239
+ const readers = (state && state.readers) || []
240
+ // 下拉里只列真读者;「总进度」是下拉旁边那个按钮,不占选项
241
+ const realReaders = readers.filter((r) => r.id !== TOTAL_READER)
242
+ // 默认跟着「最近读过的那位读者」;要点总进度才切过去
243
+ const recentReader = realReaders.slice().sort((a, b) => (Number(b.lastAt) || 0) - (Number(a.lastAt) || 0))[0]
244
+ const activeRid = readerId || (recentReader && recentReader.id) || TOTAL_READER
245
+ const isTotal = activeRid === TOTAL_READER
246
+ // 读者换了就按那位读者重拉一次:书级的「我读到第几章 / 那章叫什么」是按读者算的
247
+ useEffect(() => { if (activeRid) load(activeRid === TOTAL_READER ? '__legacy__' : activeRid) }, [activeRid])
248
+ const me = readers.find((r) => r.id === activeRid) || null
249
+
250
+ // 近况跟着当前读者走:切读者就重拉一次(服务端只报这位读者翻过的)
251
+ useEffect(() => {
252
+ let alive = true
253
+ ;(async () => {
254
+ try {
255
+ const rc = await getJson('/dsh-reading.recent?reader=' + encodeURIComponent(activeRid))
256
+ if (alive && rc && rc.ok) setRecent(rc)
257
+ } catch {}
258
+ })()
259
+ return () => { alive = false }
260
+ }, [activeRid, state])
261
+
262
+ const mineOf = (bid) => {
263
+ if (isTotal) {
264
+ const b = state && state.books && state.books.find((x) => x.id === bid)
265
+ return b ? (Number(b.readThrough) || 0) : 0
266
+ }
267
+ const r = readers.find((x) => x.id === activeRid)
268
+ const b = r && r.books && r.books[bid]
269
+ return b ? (Number(b.readThrough) || 0) : 0
270
+ }
271
+ const withReader = (p) => p + (p.indexOf('?') >= 0 ? '&' : '?') + 'reader=' + encodeURIComponent(activeRid)
272
+
273
+ // 进度只由鱼读书时写(reading_next / reading_mark);面板不提供"推进/退回/从头读"按钮,
274
+ // 免得用户点一下就替某位读者记了一章。这里只保留 reading 的入口。
275
+
276
+
277
+ const STATES = ['在写', '写完了', '搁下了']
278
+ const cycleStatus = async (f) => {
279
+ const i = STATES.indexOf(f.status || '')
280
+ const next = i < 0 ? STATES[0] : (i === STATES.length - 1 ? '' : STATES[i + 1])
281
+ await fetch('/dsh-reading.workstatus', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ rel: f.rel, status: next }) })
282
+ await loadWorks()
283
+ }
284
+
285
+ const removeBook = async (id) => {
286
+ setConfirmId('')
287
+ await getJson('/dsh-reading.removeBook', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }) })
288
+ const j = await getJson('/dsh-reading.state')
289
+ if (j && j.ok) setState(j)
290
+ }
291
+
292
+ const loadWorks = async () => {
293
+ const r = await getJson('/dsh-reading.works')
294
+ if (r && r.ok) setWorks(r) ; else setMsg('作品目录读不到:' + (r && r.error))
295
+ }
296
+ const openFile = async (f) => {
297
+ if (opened && opened.path === f.path) return setOpened(null)
298
+ if (f.kind !== 'text') return setOpened({ ...f, text: '(' + f.kind + ',路径:' + f.path + ')' })
299
+ const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.path))
300
+ setOpened({ ...f, text: r && r.ok ? r.text : '读不到:' + (r && r.error) })
301
+ }
302
+
303
+ const toggleFav = async (key) => {
304
+ const next = favs.includes(key) ? favs.filter((x) => x !== key) : favs.concat(key)
305
+ const r = await getJson('/dsh-reading.config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ favorites: next }) })
306
+ if (r && r.ok) { setCfg(r.config); setMsg(favs.includes(key) ? '已取消收藏' : '已收藏') }
307
+ }
308
+
309
+ const copyFav = async (f) => {
310
+ if (String(f).startsWith('file:')) {
311
+ const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.slice(5)))
312
+ if (r && r.ok) { copy(r.text); setMsg('已复制正文') } else setMsg('复制失败:' + (r && r.error))
313
+ return
314
+ }
315
+ const [book, chapter] = String(f).split('|')
316
+ const bk = notes.find((x) => x.book === book)
317
+ const ch = bk && (bk.chapters || []).find((x) => x.title === chapter)
318
+ if (ch) { copy(ch.lines.join('\n')); setMsg('已复制这条读后感') } else setMsg('这条读后感已经不在了')
319
+ }
320
+
321
+ // 收藏页点一下就地展开:作品看正文,读后感看那一条
322
+ const openFav = async (f) => {
323
+ const key = 'fav:' + f
324
+ if (opened && opened.path === key) return setOpened(null)
325
+ if (String(f).startsWith('file:')) {
326
+ const p = f.slice(5)
327
+ const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(p))
328
+ return setOpened({ path: key, title: p, text: r && r.ok ? r.text : '读不到:' + (r && r.error) })
329
+ }
330
+ const parts = String(f).split('|')
331
+ const bk = notes.find((x) => x.book === parts[0])
332
+ const ch = bk && (bk.chapters || []).find((x) => x.title === parts[1])
333
+ setOpened({ path: key, title: parts.join(' · '), text: ch ? ch.lines.join('\n') : '这条读后感已经不在了' })
334
+ }
335
+
336
+ // 换「面板上正在显示的那本」,只改展示,不动任何人的阅读进度
337
+ const setCurrentBook = async (id) => {
338
+ const r = await getJson('/dsh-reading.setCurrent?id=' + encodeURIComponent(id))
339
+ if (r && r.ok) { await load(); setMsg('面板切到' + showTitle(id)) } else setMsg('切换失败')
340
+ }
341
+
342
+ const [slots, setSlots] = useState([])
343
+ useEffect(() => {
344
+ const s = (state && state.study && state.study.slots) || []
345
+ setSlots(s.map((x) => ({ ...x })))
346
+ }, [state])
347
+ // 整条列表一起存:新增/删/改时段都走这里
348
+ const saveSlots = async (next) => {
349
+ const body = { slots: (next || []).map((s) => ({ id: s.id, enabled: s.enabled === true, from: s.from, to: s.to, mode: s.mode, per: s.per, everyMinutes: s.everyMinutes, dailyBudget: s.dailyBudget, session: s.session })) }
350
+ const r = await fetch('/dsh-reading.study', {
351
+ method: 'POST',
352
+ headers: { 'content-type': 'application/json' },
353
+ body: JSON.stringify(body),
354
+ }).then((x) => x.json()).catch(() => null)
355
+ if (r && r.ok) await load()
356
+ else setMsg('书房时间存不下:' + (r && r.error || '未知'), 'study')
357
+ }
358
+
359
+ const saveCfg = async (patch) => {
360
+ const r = await getJson('/dsh-reading.config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch) })
361
+ if (r && r.ok) { setCfg(r.config); setMsg('已保存', 'set') ; await load() } else setMsg('保存失败:' + (r && r.error), 'set')
362
+ }
363
+
364
+ // 读书总进度:全机共用的那条书签——跟着当前这本书走,并标出是谁读到的
365
+ const furthestChip = (cur && cur.furthest > 0)
366
+ ? h('div', {
367
+ style: { fontSize: 11, padding: '1px 7px', borderRadius: 999, background: '#eef3fb', color: '#456', whiteSpace: 'nowrap' },
368
+ title: '这本书全机读到最远的地方(所有会话共用,只增不减)',
369
+ }, '最远:第 ' + cur.furthest + ' 章' + (cur.furthestReader ? (' · ' + cur.furthestReader.name) : ''))
370
+ : null
371
+
372
+ const head = h('div', { style: S.card },
373
+ h('div', { style: S.row },
374
+ h('div', { style: { fontWeight: 600, fontSize: 14 } }, cur
375
+ ? ((recentId && shownId && shownId !== recentId) ? ('当前显示' + showTitle(cur.id)) : (((recentReader && recentReader.name) ? (recentReader.name + ' ') : '') + '正在读' + showTitle(cur.id)))
376
+ : '还没导入书'),
377
+ furthestChip,
378
+
379
+ h('div', {
380
+ style: S.dim,
381
+ title: state ? ('今天已读 ' + (me && typeof me.today === 'number' ? me.today : state.readToday) + ' 章,上限 ' + state.perDay + ' 章') : '',
382
+ }, state ? ('今天还能读 ' + Math.max(0, state.perDay - (me && typeof me.today === 'number' ? me.today : state.readToday)) + ' 章') : ''),
383
+ h('div', { style: { flex: 1 } }),
384
+ readers.length > 1
385
+ ? h('div', { style: S.row },
386
+ cur && Number(cur.furthest) > mineOf(cur.id)
387
+ ? h('button', {
388
+ style: { ...S.btn, marginRight: 6, ...(pendingAdopt === cur.id ? { color: C.warn, borderColor: C.warn } : {}) },
389
+ title: '把我在这一本书的书签接到全机读到最远的地方(只动我这份,不影响别人);点一次变红,再点一次才生效',
390
+ onClick: async () => {
391
+ if (pendingAdopt !== cur.id) {
392
+ setPendingAdopt(cur.id)
393
+ window.setTimeout(() => setPendingAdopt((x) => (x === cur.id ? '' : x)), 4000)
394
+ return
395
+ }
396
+ setPendingAdopt('')
397
+ const r = await getJson('/dsh-reading.adopt?book=' + encodeURIComponent(cur.id) + (readerId ? '&reader=' + encodeURIComponent(readerId) : ''), { method: 'POST' })
398
+ if (r && r.ok) { setMsg('已接到第 ' + r.readThrough + ' 章'); await load() }
399
+ else setMsg('接不上:' + (r && r.error || '未知'))
400
+ },
401
+ }, pendingAdopt === cur.id ? ('再点一次,接到第 ' + cur.furthest + ' 章') : ('接到第 ' + cur.furthest + ' 章'))
402
+ : null,
403
+ h('div', { style: { ...S.dim, fontSize: 11 } }, '读者'),
404
+ h('select', {
405
+ style: { fontSize: 12, padding: '2px 4px' },
406
+ value: activeRid,
407
+ onChange: (e) => { setReaderId(e.target.value); setBookAct(0) },
408
+ },
409
+ realReaders.map((r) => h('option', { key: r.id, value: r.id }, r.name || r.id)),
410
+
411
+ ),
412
+ )
413
+ : null,
414
+ h('button', { style: S.btn, onClick: load }, '刷新'),
415
+ ),
416
+ cur ? h('div', { style: { ...S.row, marginTop: 8 } },
417
+ h('div', { style: S.bar }, h('div', { style: { ...S.fill, width: Math.min(100, ((mineOf(cur.id) || 0) / (cur.chapters || 1)) * 100) + '%' } })),
418
+ h('div', { style: S.dim },
419
+ (Number(mineOf(cur.id)) > 0
420
+ ? ('我读到第 ' + mineOf(cur.id) + ' 章,全书 ' + cur.chapters + ' 章')
421
+ : ('这本我还没读过,全书 ' + cur.chapters + ' 章'))
422
+ + (cur.furthest && cur.furthest > (mineOf(cur.id) || 0) ? ('(最远是第 ' + cur.furthest + ' 章)') : '')),
423
+ ) : null,
424
+ )
425
+
426
+ const tabs = h('div', { style: S.row },
427
+ ['read', 'note', 'works', 'fav', 'set'].map((k) => h('div', {
428
+ key: k, style: S.tab(tab === k), onClick: () => { setTab(k); if ((k === 'works' || k === 'fav') && !works) loadWorks() },
429
+ }, k === 'read' ? '读书' : k === 'note' ? '读后感' : k === 'works' ? '她的作品' : k === 'fav' ? '收藏' : '设置')),
430
+ h('div', { style: { flex: 1 } }),
431
+ (msg && !msgAt) ? h('div', { style: { ...S.dim, color: C.ok } }, msg) : null,
432
+ )
433
+
434
+ const readTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
435
+ // 近况卡
436
+ h('div', { style: S.card },
437
+ h('div', { style: S.row },
438
+ h('div', { style: { fontWeight: 600 } }, '近况'),
439
+ h('div', { style: { flex: 1 } }),
440
+ h('div', { style: S.dim }, recent ? (recent.today || '') : ''),
441
+ ),
442
+ h('div', { style: { marginTop: 6, marginBottom: 6 } }, recent && recent.status ? recent.status : '还没什么可报的。'),
443
+ recent && recent.mood
444
+ ? h('div', { style: { marginBottom: 6 } }, h('span', { style: S.tagOn }, recent.mood))
445
+ : null,
446
+ recent && recent.days && recent.days.length
447
+ ? h('div', { style: { marginBottom: 4 } },
448
+ h('div', { style: S.dim }, '这几天翻过的:'),
449
+ recent.days.map((d, i) => h('div', { key: i, style: S.row },
450
+ h('div', { style: S.dim }, d.day),
451
+ h('div', { style: { flex: 1 } }, showTitle(d.book) + d.chapters + ' 章'),
452
+ )),
453
+ )
454
+ : null,
455
+ recent && recent.perReader && recent.perReader.length
456
+ ? h('div', { style: { marginTop: 6 } },
457
+ isTotal
458
+ ? h('div', { style: S.dim }, '这本谁读到哪(按读到最远排):')
459
+ : null,
460
+ recent.perReader.slice(0, 8).map((r, i) => h('div', { key: i, style: S.row },
461
+ h('div', { style: { flex: 1 } }, showTitle(r.name)),
462
+ h('div', { style: S.dim }, '读到第 ' + r.readThrough + (r.chapters ? (' / ' + r.chapters) : '') + ' 章'),
463
+ )),
464
+ )
465
+ : null,
466
+
467
+ recent && recent.works && recent.works.length
468
+ ? h('div', null,
469
+ h('div', { style: S.dim }, '最近碰过的稿子:'),
470
+ recent.works.map((w, i) => h('div', { key: i, style: S.row },
471
+ h('div', { style: { flex: 1 } },
472
+ h('div', null, w.rel),
473
+ w.note ? h('div', { style: { ...S.dim, fontSize: 11 } }, w.note) : null,
474
+ ),
475
+ h('div', { style: S.dim }, w.days === 0 ? '今天' : w.days + ' 天前'),
476
+ )),
477
+ )
478
+ : null,
479
+ ),
480
+
481
+ h('div', { style: S.card },
482
+ h('div', { style: S.row },
483
+ h('div', { style: { fontWeight: 600 } }, '读到哪'),
484
+ h('div', { style: { flex: 1 } }),
485
+
486
+ // 只讲「鱼会说的话」;内部怎么选章(第一章还是接总进度)不上界面。
487
+ h('button', { style: showRaw ? S.btnOn : S.btn, onClick: async () => {
488
+ if (!showRaw && cur) {
489
+ const mineN = mineOf(cur.id)
490
+ if (!mineN) return
491
+ const r = await getJson('/dsh-reading.chapter?book=' + encodeURIComponent(cur.id) + '&n=' + mineN)
492
+ if (r && r.ok) setOpened({ path: 'chapter', text: r.text, title: r.title })
493
+ else setMsg('取不到原文:' + (r && r.error || '未知'))
494
+ }
495
+ setShowRaw(!showRaw)
496
+ } }, showRaw ? '收起原文' : '显示原文'),
497
+ ),
498
+ cur && Number(cur.mineReadThrough) > 0
499
+ ? h('div', { style: { ...S.dim, marginTop: 6 } },
500
+ '我读到第 ' + cur.mineReadThrough + ' 章'
501
+ + (cur.mineChapterTitle ? (' · ' + cur.mineChapterTitle) : ''))
502
+ : (cur
503
+ ? h('div', { style: { ...S.dim, marginTop: 6 } },
504
+ (Number(cur.furthest) > 1 ? ('这本书别人读到第 ' + cur.furthest + ' 章了,我还没读过。') : '这本书我还没读过。'))
505
+ : null),
506
+ showRaw && opened && opened.path === 'chapter'
507
+ ? h('div', { style: { ...S.text, marginTop: 8 } }, (opened.title ? opened.title + '\n\n' : '') + opened.text)
508
+ : null,
509
+ ),
510
+ h('div', { style: S.card },
511
+ h('div', { style: { ...S.row, marginBottom: 6 } },
512
+ h('div', { style: { fontWeight: 600 } }, '书架'),
513
+ h('div', { style: { ...S.dim, marginLeft: 8 } }, '点书名,看各人的进度'),
514
+ h('div', { style: { flex: 1 } }),
515
+ picking && picked.length
516
+ ? h('button', {
517
+ style: { ...S.btn, color: C.warn, borderColor: C.warn },
518
+ onClick: async () => {
519
+ for (const id of picked) await removeBook(id)
520
+ setPicking(false); setPicked([]); setMsg('下架了 ' + picked.length + ' 本')
521
+ },
522
+ }, '确认下架 ' + picked.length + ' 本')
523
+ : null,
524
+ h('button', {
525
+ style: picking ? S.btnOn : S.btn,
526
+ title: '批量从书架拿下来(文件移到 books/.trash,可手工找回;读后感不动)',
527
+ onClick: () => { setPicking(!picking); setPicked([]) },
528
+ }, picking ? '取消' : '下架'),
529
+ ),
530
+ (state && state.books && state.books.length) ? state.books.map((b, i) => {
531
+ const mineNo = mineOf(b.id)
532
+ const done = (b.readThrough || 0) >= (b.chapters || 1)
533
+ return h('div', { key: i, style: S.row },
534
+ picking
535
+ ? h('input', {
536
+ type: 'checkbox',
537
+ checked: picked.includes(b.id),
538
+ onChange: (e) => setPicked(e.target.checked ? picked.concat([b.id]) : picked.filter((x) => x !== b.id)),
539
+ })
540
+ : null,
541
+ // 点书名 = 把面板切到这本(只改显示,不动任何人的进度);当前那本前面带个圆点
542
+ h('div', {
543
+ style: { flex: 1, cursor: 'pointer', color: b.id === shownId ? C.accent : C.text, fontWeight: b.id === shownId ? 600 : 400 },
544
+ title: b.id === shownId
545
+ ? '面板顶部显示的就是这本(默认是最近读过的那本)'
546
+ : '点书名把面板临时切到这本(只改显示,不动任何人的阅读进度)',
547
+ onClick: () => setShownBook(b.id),
548
+ }, (b.id === shownId ? '● ' : '') + b.id),
549
+ h('div', { style: S.dim },
550
+ (mineNo || 0) + '/' + b.chapters
551
+ + (b.furthest && b.furthest > mineNo ? ('(最远 ' + b.furthest + ')') : '')),
552
+ h('div', {
553
+ style: b.status === '弃坑' ? { ...S.tag, color: C.warn } : (done || b.status === '已读完' ? { ...S.tag, color: C.ok } : S.tag),
554
+ title: '这本书的状态由鱼自己写(reading_* 工具),面板只显示',
555
+ }, b.status || (done ? '已读完' : (mineNo ? '在读' : '未读'))),
556
+
557
+ )
558
+ }) : h('div', { style: S.dim }, '还没有书。'),
559
+ ),
560
+ )
561
+
562
+ // 读后感单独一页:不和书架挤在一起
563
+ const noteTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
564
+ h('div', { style: S.card },
565
+ notes.length ? (() => {
566
+ const act = Math.min(bookAct, notes.length - 1)
567
+ const bk = notes[act]
568
+ const bi = act
569
+ const v = noteView[bi] || {}
570
+ const all = !!v.all
571
+ const total = bk.chapters.length
572
+ const pages = Math.max(1, Math.ceil(total / NOTE_PAGE))
573
+ const page = Math.min(v.page || 0, pages - 1)
574
+ // 排序:章节升 / 章节降 / 时间新在前(没写时间的排在后面)
575
+ const sortLabels = ['章节 \u2191', '章节 \u2193', '时间 \u2193']
576
+ const sortMode = (v.sort === undefined ? ((state && state.noteSort) || 0) : v.sort) % 3
577
+ const sorted = bk.chapters.slice()
578
+ if (sortMode === 1) sorted.sort((a, b) => (chapterNo(b.title) || -1) - (chapterNo(a.title) || -1))
579
+ else if (sortMode === 2) sorted.sort((a, b) => String(b.at || '').localeCompare(String(a.at || '')))
580
+ else sorted.sort((a, b) => (chapterNo(a.title) || 1e9) - (chapterNo(b.title) || 1e9))
581
+ // 按署名筛:同一台机器上有好几个读者,读后记在一个文件里靠 by 分
582
+ const af = authorFilter
583
+ const authors = Array.from(new Set(notes.reduce((acc, n) => acc.concat(n.chapters.map((c) => c.by).filter(Boolean)), [])))
584
+ const seen = af ? sorted.filter((c) => (c.by || '') === af) : sorted
585
+ const list = all ? seen : seen.slice(page * NOTE_PAGE, page * NOTE_PAGE + NOTE_PAGE)
586
+ const setView = (patch) => setNoteView(Object.assign({}, noteView, { [bi]: Object.assign({}, v, patch) }))
587
+ const saveSort = (n) => { try { getJson('/dsh-reading.notesort', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sort: n }) }) } catch (e) {} }
588
+ const paged = total > NOTE_PAGE
589
+ const tabs = h('div', { style: { ...S.row, gap: 6, marginBottom: 8, flexWrap: 'wrap' } },
590
+ notes.map((n, ni) => h('button', {
591
+ key: ni,
592
+ style: ni === act ? S.btnOn : S.btn,
593
+ onClick: () => setBookAct(ni),
594
+ }, n.book)),
595
+ )
596
+ return [tabs, h('div', { key: bi, style: { marginBottom: 10 } },
597
+ h('div', { style: { ...S.row, marginBottom: 4 } },
598
+ h('div', { style: { fontWeight: 600 } }, bk.book),
599
+ h('div', { style: S.dim }, total + ' 段'),
600
+ h('div', { style: { flex: 1 } }),
601
+ paged ? h('button', { style: S.btn, disabled: page <= 0, onClick: () => setView({ page: page - 1 }) }, '‹') : null,
602
+ paged ? h('div', { style: { ...S.dim, minWidth: 46, textAlign: 'center' } }, all ? '全部' : ((page + 1) + ' / ' + pages)) : null,
603
+ paged ? h('button', { style: S.btn, disabled: all || page >= pages - 1, onClick: () => setView({ page: page + 1 }) }, '›') : null,
604
+ paged ? h('button', { style: all ? S.btnOn : S.btn, onClick: () => setView({ all: !all, page: 0 }) }, all ? '分页' : '全部') : null,
605
+ h('button', { style: S.btnOn, onClick: () => { const next = (sortMode + 1) % 3; setView({ sort: next, page: 0 }); saveSort(next) } }, sortLabels[sortMode]),
606
+ authors.length > 1
607
+ ? h('select', {
608
+ style: { fontSize: 12, padding: '2px 4px' },
609
+ value: af,
610
+ onChange: (e) => { setAuthorFilter(e.target.value); setView({ page: 0 }) },
611
+ },
612
+ h('option', { value: '' }, '全部署名'),
613
+ authors.map((a) => h('option', { key: a, value: a }, a)),
614
+ )
615
+ : null,
616
+ h('button', { style: S.btn, onClick: () => copy(bk.chapters.map((c) => '## ' + c.title + '\n' + c.lines.join('\n')).join('\n\n')) }, '复制这本读后感'),
617
+ ),
618
+ (sortMode === 2 && bk.chapters.filter((c) => !c.at).length) ? h('div', { style: { ...S.dim, marginBottom: 6 } }, '有 ' + bk.chapters.filter((c) => !c.at).length + ' 段早期笔记当时没记时间,排在最后。') : null,
619
+ list.map((c, ci) => h('div', { key: ci, style: { marginBottom: 6 } },
620
+ h('div', { style: S.row },
621
+ h('div', { style: { ...S.dim, color: C.warn } }, c.title),
622
+ h('button', { style: S.btn, onClick: () => toggleFav(bk.book + '|' + c.title) }, favs.includes(bk.book + '|' + c.title) ? '★' : '☆'),
623
+ h('button', { style: S.btn, onClick: () => copy(c.lines.join('\n')) }, '复制'),
624
+ ),
625
+ c.lines.map((l, li) => h('div', { key: li, style: /^↳/.test(l) ? { ...S.dim, marginTop: 4 } : S.note }, l)),
626
+ )),
627
+ )]
628
+ })() : h('div', { style: S.dim }, '还没写过。读完一段记两句,这里就有了。'),
629
+ ),
630
+ )
631
+
632
+ const worksTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
633
+ h('div', { style: S.card },
634
+ h('div', { style: S.row },
635
+ h('div', { style: { fontWeight: 600 } }, '她的作品'),
636
+ h('div', { style: S.dim }, works ? (works.root + ' · ' + works.files.length + ' 个文件' + ((works.images && works.images.length) ? (' · ' + works.images.length + ' 张图') : '')) : ''),
637
+ h('div', { style: { flex: 1 } }),
638
+ h('button', { style: S.btn, onClick: loadWorks }, '重新扫描'),
639
+ ),
640
+ !works ? h('div', { style: { ...S.dim, marginTop: 8 } }, '点「重新扫描」列出作品目录。') :
641
+ (works.files.length ? works.files.map((f, i) => h('div', { key: i, style: { ...S.item, borderTop: '1px solid ' + C.line } },
642
+ h('div', { style: { flex: '0 1 auto', cursor: 'pointer' }, onClick: () => openFile(f) }, f.rel),
643
+ h('div', { style: { ...S.dim, marginLeft: 10 } }, (() => {
644
+ const d = Math.floor((Date.now() - new Date(f.mtime).getTime()) / 86400000)
645
+ return d <= 0 ? '今天改过' : (d === 1 ? '昨天改过' : d + ' 天前改过')
646
+ })()),
647
+ h('div', { style: f.author ? S.dim : { ...S.dim, color: C.warn } }, f.author ? ('署名 · ' + f.author) : '未署名'),
648
+ h('div', { style: { flex: 1 } }),
649
+ h('button', {
650
+ style: f.status === '在写' ? S.tagOn : S.tag,
651
+ title: '点一下换状态:在写 → 写完了 → 搁下了 → 不标',
652
+ onClick: () => cycleStatus(f),
653
+ }, f.status || '—'),
654
+ h('div', { style: S.dim }, f.kind + ' · ' + fmt(f.size)),
655
+ h('button', { style: S.btn, onClick: () => toggleFav('file:' + f.path) }, favs.includes('file:' + f.path) ? '★' : '☆'),
656
+ f.kind === 'text' ? h('button', { style: S.btn, onClick: async () => {
657
+ const r = await getJson('/dsh-reading.file?path=' + encodeURIComponent(f.path))
658
+ if (r && r.ok) { copy(r.text); setMsg('已复制全文') }
659
+ } }, '复制') : h('button', { style: S.btn, onClick: () => { copy(f.path); setMsg('已复制路径') } }, '复制路径'),
660
+ )) : h('div', { style: { ...S.dim, marginTop: 8 } }, '这里还是空的:把 .md 或 .txt 放进 ' + works.root + ',点「重新扫描」就会出现。')),
661
+ opened ? h('div', { style: { ...S.text, marginTop: 10 } }, (opened.title || opened.rel || '') + '\n\n' + opened.text) : null,
662
+ ),
663
+ (works && works.images && works.images.length) ? h('div', { style: S.card },
664
+ h('div', { style: S.row },
665
+ h('div', { style: { fontWeight: 600 } }, '画'),
666
+ h('div', { style: S.dim }, '作品目录与 art 里的图 · 新的在前 · 点一张看大图'),
667
+ ),
668
+ h('div', {
669
+ style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 10, marginTop: 10 },
670
+ },
671
+ works.images.map((m, i) => h('div', {
672
+ key: 'img' + i,
673
+ style: { border: '1px solid ' + C.line, borderRadius: 8, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: 'rgba(255,255,255,0.02)' },
674
+ },
675
+ h('div', {
676
+ style: { cursor: 'zoom-in', lineHeight: 0, background: 'rgba(0,0,0,0.15)' },
677
+ title: m.path,
678
+ onClick: () => setViewer(m),
679
+ }, h('img', {
680
+ src: m.url,
681
+ alt: m.name,
682
+ loading: 'lazy',
683
+ style: { width: '100%', height: 120, objectFit: 'cover', display: 'block' },
684
+ })),
685
+ h('div', { style: { padding: '6px 8px', display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 } },
686
+ h('div', { style: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: m.rel }, m.name),
687
+ h('div', { style: { ...S.dim, fontSize: 11 } }, (m.width && m.height ? (m.width + '×' + m.height + ' · ') : '') + fmt(m.size)),
688
+ h('div', { style: { ...S.dim, fontSize: 11 } }, new Date(m.mtime).toLocaleString()),
689
+ ),
690
+ )),
691
+ ),
692
+ ) : null,
693
+ )
694
+
695
+ const setTabView = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
696
+ h('div', { style: S.card },
697
+ h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '阅读'),
698
+ h('div', { style: { ...S.row, marginBottom: 6 } },
699
+ h('div', null, '每日章节上限'), h('input', { style: S.input, type: 'number', defaultValue: (cfg && cfg.perDay) || 20, onBlur: (e) => saveCfg({ perDay: Number(e.target.value) || 0 }) }),
700
+ ),
701
+ h('div', { style: { ...S.row, marginBottom: 6 } },
702
+ h('div', null, '每几章写一次读后感'), h('input', { style: S.input, type: 'number', defaultValue: (cfg && cfg.notesEvery) || 1, onBlur: (e) => saveCfg({ notesEvery: Number(e.target.value) || 1 }) }),
703
+ ),
704
+ h('div', { style: S.row },
705
+ h('label', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
706
+ h('input', {
707
+ type: 'checkbox',
708
+ defaultChecked: (cfg ? cfg.quietEnabled !== false : true),
709
+ onChange: (e) => saveCfg({ quietEnabled: e.target.checked }),
710
+ }),
711
+ h('span', null, '启用静音'),
712
+ ),
713
+ h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.quietFrom) || '', placeholder: '03:00', onBlur: (e) => saveCfg({ quietFrom: e.target.value }) }),
714
+ h('div', { style: S.dim }, '至'),
715
+ h('input', { style: { ...S.input, width: 64 }, defaultValue: (cfg && cfg.quietTo) || '', placeholder: '08:00', onBlur: (e) => saveCfg({ quietTo: e.target.value }) }),
716
+ h('div', { style: S.dim }, '静音时段内不会自动读'),
717
+ ),
718
+ msgAt === 'set' ? h('div', { style: { ...S.dim, color: C.ok, marginTop: 6 } }, msg) : null,
719
+ h('div', { style: { ...S.row, marginBottom: 6, marginTop: 10, paddingTop: 10, borderTop: '1px solid ' + C.line } },
720
+ h('div', { style: { fontWeight: 600, marginRight: 10 } }, '书房时间'),
721
+ h('button', {
722
+ style: { ...S.btn, fontSize: 11, padding: '2px 8px' },
723
+ title: '可以有多条:不同时段、不同频率、叫进不同会话',
724
+ onClick: () => {
725
+ const next = slots.concat([{ id: 'slot-' + Date.now().toString(36), enabled: false, from: '22:00', to: '23:00', everyMinutes: 30, dailyBudget: 2, session: '' }])
726
+ setSlots(next); saveSlots(next)
727
+ },
728
+ }, '新增书房时间'),
729
+ ),
730
+ msgAt === 'study' ? h('div', { style: { ...S.dim, color: C.ok, marginTop: 4 } }, msg) : null,
731
+ (slots.length ? slots : []).map((s, i) =>
732
+ h('div', { key: s.id || i, style: { ...S.row, marginBottom: 6, flexWrap: 'wrap' } },
733
+ h('input', {
734
+ type: 'checkbox',
735
+ checked: s.enabled === true,
736
+ title: '这条开不开',
737
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, enabled: e.target.checked }; setSlots(next); saveSlots(next) },
738
+ }),
739
+ h('input', {
740
+ style: { ...S.input, width: 64 },
741
+ value: s.from || '',
742
+ placeholder: '例 22:00',
743
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, from: e.target.value }; setSlots(next) },
744
+ onBlur: () => saveSlots(slots),
745
+ }),
746
+ h('div', { style: S.dim }, '至'),
747
+ h('input', {
748
+ style: { ...S.input, width: 64 },
749
+ value: s.to || '',
750
+ placeholder: '例 23:00',
751
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, to: e.target.value }; setSlots(next) },
752
+ onBlur: () => saveSlots(slots),
753
+ }),
754
+ h('div', { style: S.dim }, '这段时间内每'),
755
+ h('select', {
756
+ style: { ...S.input, width: 80 },
757
+ value: s.everyMinutes || 30,
758
+ title: '隔多久叫一次(最小间隔)',
759
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, everyMinutes: Number(e.target.value) || 30 }; setSlots(next); saveSlots(next) },
760
+ },
761
+ [15, 30, 60, 120].map((m) => h('option', { key: m, value: m }, m + ' 分')),
762
+ ),
763
+ h('div', { style: S.dim }, '叫一次,最多'),
764
+ h('input', {
765
+ style: { ...S.input, width: 56 },
766
+ type: 'number', min: 1, max: 24,
767
+ value: s.dailyBudget || 2,
768
+ title: '这段里一天最多叫几次',
769
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, dailyBudget: Math.min(24, Math.max(1, Number(e.target.value) || 1)) }; setSlots(next) },
770
+ onBlur: () => saveSlots(slots),
771
+ }),
772
+ h('div', { style: S.dim }, '次/天'),
773
+ h('select', {
774
+ style: { ...S.input, width: 160 },
775
+ value: s.session || '',
776
+ onChange: (e) => { const next = slots.slice(); next[i] = { ...s, session: e.target.value }; setSlots(next); saveSlots(next) },
777
+ },
778
+ h('option', { key: '', value: '' }, '最近活跃的会话'),
779
+ ((state && state.study && state.study.sessions) || [])
780
+ .map((x) => h('option', { key: x.id, value: x.id }, x.title || ('会话 ' + String(x.id).slice(-8)))),
781
+ (s.session && !((state && state.study && state.study.sessions) || []).some((x) => x.id === s.session))
782
+ ? h('option', { key: 'cur', value: s.session }, '已选(这条会话现在没开着)')
783
+ : null,
784
+ ),
785
+ h('button', {
786
+ style: { ...S.btn, color: C.warn },
787
+ title: '删掉这一条(计数一起删)',
788
+ onClick: () => { const next = slots.filter((x, k) => k !== i); setSlots(next); saveSlots(next) },
789
+ }, '删'),
790
+ ),
791
+ ),
792
+ h('div', { style: { ...S.dim, marginBottom: 6 } }, '到点只在选中的那条会话里说一句,读不读由它自己决定;默认关闭'),
793
+ h('div', { style: { ...S.dim, marginBottom: 6 } }, '同时装着「鱼的心跳」的话,建议这条别勾——两边各叫各的,不会互相避让'),
794
+ h('div', { style: S.dim }, studyLine(state && state.study)),
795
+ ),
796
+ h('div', { style: S.card },
797
+ h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '导入一本书'),
798
+ h('div', { style: S.row },
799
+ h('button', {
800
+ style: S.btnOn,
801
+ onClick: () => {
802
+ const el = document.getElementById('dsh-read-pick')
803
+ if (el) el.click()
804
+ },
805
+ }, '选择文件…'),
806
+ h('input', {
807
+ id: 'dsh-read-pick',
808
+ type: 'file',
809
+ accept: '.txt,.md,text/plain',
810
+ style: { display: 'none' },
811
+ onChange: (e) => {
812
+ const f = e.target.files && e.target.files[0]
813
+ if (!f) return
814
+ setMsg('读取 ' + f.name + '…')
815
+ const rd2 = new FileReader()
816
+ rd2.onload = async () => {
817
+ try {
818
+ const buf = new Uint8Array(rd2.result)
819
+ let bin = ''
820
+ const CH = 0x8000
821
+ for (let i = 0; i < buf.length; i += CH) {
822
+ bin += String.fromCharCode.apply(null, buf.subarray(i, i + CH))
823
+ }
824
+ const data = btoa(bin)
825
+ setMsg('导入中…', 'imp')
826
+ const r = await fetch('/dsh-reading.importText', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: f.name, data }) })
827
+ const j = await r.json()
828
+ if (!j.ok) { setMsg('失败:' + (j.error || '未知'), 'imp'); return }
829
+ setMsg('已导入 ' + (j.id || '') + '(' + (j.chapters || 0) + ' 章)', 'imp')
830
+ await load()
831
+ } catch (err) { setMsg('失败:' + String(err)) }
832
+ }
833
+ rd2.readAsArrayBuffer(f)
834
+ e.target.value = ''
835
+ },
836
+ }),
837
+ h('div', { style: S.dim }, '点左边选文件,或把完整路径粘在下面'),
838
+ ),
839
+ h('div', { style: S.row },
840
+ h('input', {
841
+ style: { ...S.input, width: 300 },
842
+ placeholder: 'D:\\...\\书名.txt 或 .md',
843
+ onChange: (e) => { importPath = e.target.value },
844
+ }),
845
+ h('button', {
846
+ style: S.btnOn,
847
+ onClick: async () => {
848
+ const p = String(importPath || '').trim()
849
+ if (!p) { setMsg('先填文件路径', 'imp'); return }
850
+ setMsg('导入中…', 'imp')
851
+ try {
852
+ const r = await fetch('/dsh-reading.import', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: p }) })
853
+ const j = await r.json()
854
+ if (!j.ok) { setMsg('失败:' + (j.error || '未知'), 'imp'); return }
855
+ setMsg('已导入 ' + (j.id || '') + '(' + (j.chapters || 0) + ' 章)', 'imp')
856
+ importPath = ''
857
+ await load()
858
+ } catch (e) { setMsg('失败:' + String(e), 'imp') }
859
+ },
860
+ }, '导入'),
861
+ ),
862
+ msgAt === 'imp' ? h('div', { style: { ...S.dim, color: C.ok, marginTop: 4 } }, msg) : null,
863
+ h('div', { style: S.dim }, '只认 .txt / .md,会复制到书架并统计章数。'),
864
+ ),
865
+ h('div', { style: S.card },
866
+ h('div', { style: { fontWeight: 600, marginBottom: 8 } }, '写作'),
867
+ h('div', { style: S.row },
868
+ h('div', null, '开启写作功能'),
869
+ h('button', { style: (cfg && cfg.writing) ? S.btnOn : S.btn, onClick: () => saveCfg({ writing: !(cfg && cfg.writing) }) }, (cfg && cfg.writing) ? '已开启' : '已关闭'),
870
+ h('div', { style: S.dim }, '关掉后我只读书,不写东西'),
871
+ ),
872
+ ),
873
+ h('div', { style: S.card },
874
+ h('div', { style: { fontWeight: 600, marginBottom: 6 } }, '备份 / 恢复'),
875
+ h('div', { style: S.row },
876
+ h('button', { style: S.btn, onClick: async () => {
877
+ setBusy(true)
878
+ setMsg('正在打包…', 'bak')
879
+ try {
880
+ const r = await fetch('/dsh-reading.backupFile', { method: 'POST' }).then((x) => x.json())
881
+ if (r && r.ok) {
882
+ setLastBackup(r.path)
883
+ setMsg('已备份到 ' + r.path, 'bak')
884
+ fetch('/dsh-reading.reveal', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ path: r.path }) }).catch(() => {})
885
+ } else setMsg('备份失败:' + ((r && r.error) || '未知'), 'bak')
886
+ } catch (e) {
887
+ setMsg('备份失败:' + String(e), 'bak')
888
+ } finally { setBusy(false) }
889
+ } }, '备份全部数据'),
890
+ h('button', { style: S.btn, onClick: () => { if (!lastBackup) { setMsg('先点一次备份', 'bak'); return } reveal(lastBackup) } }, '在文件夹里打开'),
891
+ ),
892
+ h('div', { style: { ...S.row, marginTop: 6 } },
893
+ h('button', { style: S.btn, onClick: async () => {
894
+ setBusy(true)
895
+ setMsg('正在读取备份…', 'bak')
896
+ try {
897
+ let path = (restorePath || '').trim()
898
+ if (!path) {
899
+ const pick = await fetch('/dsh-reading.pickFile', { method: 'POST' }).then((x) => x.json()).catch(() => null)
900
+ if (pick && pick.ok && pick.path) { path = pick.path; setRestorePath(path) }
901
+ }
902
+ if (!path) { setMsg('先点「选择备份文件」,或把完整路径填在下面的框里', 'bak'); return }
903
+ const f = await fetch('/dsh-reading.readFile?path=' + encodeURIComponent(path)).then((x) => x.json())
904
+ if (!f || !f.ok) { setMsg('读不到那个文件:' + ((f && f.error) || '未知'), 'bak'); return }
905
+ const r = await fetch('/dsh-reading.restore', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ json: f.text }) }).then((x) => x.json())
906
+ if (r && r.ok) { setMsg('已恢复:' + (r.books || 0) + ' 本 · ' + (r.chapters || 0) + ' 段读后感', 'bak'); await load() }
907
+ else setMsg('恢复失败:' + ((r && r.error) || '未知'), 'bak')
908
+ } catch (e) {
909
+ setMsg('恢复失败:' + String(e), 'bak')
910
+ } finally { setBusy(false) }
911
+ } }, '恢复全部数据'),
912
+ ), msgAt === 'bak' ? h('div', { style: { ...S.dim, color: C.ok, marginTop: 4 } }, msg) : null,
913
+ h('div', { style: { ...S.dim, marginTop: 6 } }, '备份 = 读后感全文 + 阅读进度,存成一个 .json 文件;恢复时在弹出的窗口里选那个文件。恢复前旧文件会存成 *bak-restore-*。'),
914
+ h('div', { style: { ...S.dim, marginTop: 4 } }, '单独想拿文字的话:' , h('span', { style: { cursor: 'pointer', textDecoration: 'underline' }, onClick: () => { copy(raw); setMsg('读后感全文已复制') } }, '复制读后感'), ' · ', h('span', { style: { cursor: 'pointer', textDecoration: 'underline' }, onClick: () => { copy(JSON.stringify(state, null, 2)); setMsg('进度 JSON 已复制') } }, '复制进度')),
915
+ ),
916
+ h('div', { style: S.card },
917
+ h('div', { style: { display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 } },
918
+ h('div', { style: { fontWeight: 600 } }, '更新'),
919
+ h('div', { style: { ...S.dim, fontSize: 12 } }, 'v' + ((upd && upd.current) || (state && state.version) || '')),
920
+ (upd && upd.latest) ? h('div', { style: { fontSize: 12, color: upd.outdated ? C.warn : C.ok } }, 'npm 最新 ' + upd.latest) : null,
921
+ ),
922
+ h('div', { style: S.row },
923
+ h('button', { style: S.btn, onClick: async () => {
924
+ setBusy(true)
925
+ try {
926
+ const r = await fetch('/dsh-reading.update').then((x) => x.json())
927
+ if (r && r.ok) {
928
+ const d = new Date()
929
+ const pad = (n) => String(n).padStart(2, '0')
930
+ setUpd({ ...r, at: pad(d.getHours()) + ':' + pad(d.getMinutes()) })
931
+ setMsg(r.outdated
932
+ ? ('发现新版本 ' + r.latest + ':可以点「复制更新命令」,在终端里跑')
933
+ : (r.latest ? ('已是最新版 ' + r.current + ',不用更新') : '查不到 npm(可能离线),稍后再试'), 'upd')
934
+ } else setMsg('检测失败:' + ((r && r.error) || '未知'), 'upd')
935
+ } catch (e) {
936
+ setMsg('检测失败:' + String((e && e.message) || e), 'upd')
937
+ } finally { setBusy(false) }
938
+ } }, '检测更新'),
939
+ h('button', { style: S.btn, onClick: () => { copy('dsh plugin add dsh-half-page@latest'); setMsg('更新命令已复制', 'upd') } }, '复制更新命令'),
940
+ ),
941
+ msgAt === 'upd' ? h('div', { style: { ...S.dim, color: (upd && upd.outdated) ? C.warn : C.ok, marginTop: 4 } }, msg) : null,
942
+ h('div', { style: { ...S.dim, marginTop: 4 } }, '更新就是把 npm 上的最新版装一遍;命令可以复制出去,在终端里跑。'),
943
+ ),
944
+ )
945
+
946
+ const favTab = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
947
+ h('div', { style: S.card },
948
+ h('div', { style: { fontWeight: 600, marginBottom: 6 } }, '收藏'),
949
+ favs.length ? favs.map((f, i) => {
950
+ const isFile = String(f).startsWith('file:')
951
+ const fpath = isFile ? f.slice(5) : ''
952
+ const w = isFile && works && (works.files || []).find((x) => x.path === fpath)
953
+ const who = w ? w.author : ''
954
+ return h('div', { key: i, style: S.item },
955
+ h('div', {
956
+ style: { flex: 1, cursor: 'pointer', borderTop: i ? '1px solid ' + C.line : 'none', paddingTop: i ? 8 : 0 },
957
+ onClick: () => openFav(f),
958
+ }, String(f).startsWith('file:') ? f.slice(5) : f.replace('|', ' · ')),
959
+ isFile ? h('div', { style: who ? S.dim : { ...S.dim, color: C.warn } }, who ? ('署名 · ' + who) : '未署名') : null,
960
+ h('button', { style: S.btn, onClick: () => copyFav(f) }, '复制'),
961
+ h('button', { style: S.btn, onClick: () => toggleFav(f) }, '取消收藏'),
962
+ )
963
+ }) : h('div', { style: S.dim }, '在读后感或作品上点 ☆,收藏的东西会出现在这儿。'),
964
+ ),
965
+ opened && String(opened.path || '').startsWith('fav:')
966
+ ? h('div', { style: { ...S.text, marginTop: 0 } }, (opened.title ? opened.title + '\n\n' : '') + opened.text)
967
+ : null,
968
+ )
969
+
970
+ const viewerLayer = viewer ? h('div', {
971
+ style: {
972
+ position: 'fixed', inset: 0, zIndex: 9999, background: 'rgba(10,14,22,0.86)',
973
+ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
974
+ gap: 10, padding: 20, cursor: 'zoom-out',
975
+ },
976
+ onClick: () => setViewer(null),
977
+ },
978
+ h('img', {
979
+ src: viewer.url,
980
+ alt: viewer.name,
981
+ onClick: (e) => e.stopPropagation(),
982
+ style: { maxWidth: '94vw', maxHeight: '84vh', objectFit: 'contain', borderRadius: 6, boxShadow: '0 12px 48px rgba(0,0,0,0.55)', background: '#fff', minWidth: 120, cursor: 'default' },
983
+ }),
984
+ h('div', { style: { color: '#e8eef8', fontSize: 12, textAlign: 'center', maxWidth: '90vw', wordBreak: 'break-all' } },
985
+ viewer.name + (viewer.width && viewer.height ? ' · ' + viewer.width + '×' + viewer.height : '') + ' · ' + fmt(viewer.size) + ' (点空白或按 Esc 关闭)'),
986
+ h('div', { style: { color: 'rgba(232,238,248,0.55)', fontSize: 11, maxWidth: '90vw', wordBreak: 'break-all' } }, viewer.rel || ''),
987
+ ) : null
988
+
989
+ return h('div', { style: S.wrap },
990
+ head,
991
+ tabs,
992
+ tab === 'read' ? readTab : tab === 'note' ? noteTab : tab === 'works' ? worksTab : tab === 'fav' ? favTab : setTabView,
993
+ viewerLayer,
994
+ )
995
+ }
996
+
997
+ function Boundary(props) {
998
+ try { return h(Panel, props) } catch (e) {
999
+ return h('div', { style: { padding: 14, color: '#ff8080', fontSize: 12 } }, '半页出错了:' + String((e && e.message) || e))
1000
+ }
1001
+ }
1002
+
1003
+ return {
1004
+ inject: ['slots'],
1005
+ apply(ctx) {
1006
+ const slots = (typeof ctx.get === 'function' ? ctx.get('slots') : undefined) || ctx.slots
1007
+ if (!slots) return
1008
+ slots.inject('conversation.view', () => slots.register({ name: 'conversation.view', id: 'reading', order: 42, label: '半页' }, (props) => h(Boundary, props)))
1009
+ slots.inject('settings.section', () => slots.register({ name: 'settings.section', id: 'dsh-half-page', order: 66, label: '半页' }, () => h(Boundary)))
1010
+ },
1011
+ }
1012
+ },
1013
+ })