dsh-half-page 0.3.36 → 0.3.38

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/README.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - **读后感**:不必一章一条,每读五六章写一段就够,标题自动是「第 23–27 章」;面板里按书页签切换、可收藏、点开能看原文
21
21
  - **署名**:写读后感时带上 `by`,每条下面会标出是谁写的(多只智能体共用一个书房时有用)
22
22
  - **她的作品**:面板里能看它自己写的东西,带状态标签(在写 / 写完了 / 搁下了)
23
+ - **画**:作品目录与 `art/` 里的 png / jpg / webp 也会列出来(新→旧,缩略图 + 尺寸 + 时间,点开看大图);`archive/` 不列,单张超 10MB 跳过
23
24
  - **退一章**:点错了往后退,今天的计数也会跟着退
24
25
  - **导入书**:面板里直接选 `.txt` / `.md` 文件,不用手动拷目录
25
26
  - **下架**:从书架拿下来的书会移到 `books/.trash/`,不会真删;读后感也不会跟着消失
@@ -54,6 +55,7 @@ dsh plugin add dsh-half-page
54
55
  |---|---|
55
56
  | `reading_shelf` | 书架与进度 |
56
57
  | `reading_next` | 打开下一章(或指定章) |
58
+ | `reading_mark` | 只记进度、不返回正文:已读到第 N 章(自己切文件读完整章时用它补记) |
57
59
  | `reading_note` | 给这章写一两句读后感,可带 `by` |
58
60
  | `reading_search` | 在书里搜词,返回第几章、哪一行 |
59
61
  | `reading_recap` | 已读部分压成一页 |
package/client.js CHANGED
@@ -382,7 +382,7 @@ window.__ModuleLoader__.load({
382
382
  h('div', { style: S.card },
383
383
  h('div', { style: S.row },
384
384
  h('div', { style: { fontWeight: 600 } }, '她的作品'),
385
- h('div', { style: S.dim }, works ? (works.root + ' · ' + works.files.length + ' 个文件') : ''),
385
+ h('div', { style: S.dim }, works ? (works.root + ' · ' + works.files.length + ' 个文件' + ((works.images && works.images.length) ? (' · ' + works.images.length + ' 张图') : '')) : ''),
386
386
  h('div', { style: { flex: 1 } }),
387
387
  h('button', { style: S.btn, onClick: loadWorks }, '重新扫描'),
388
388
  ),
@@ -409,6 +409,36 @@ window.__ModuleLoader__.load({
409
409
  )) : h('div', { style: { ...S.dim, marginTop: 8 } }, '这里还是空的:把 .md 或 .txt 放进 ' + works.root + ',点「重新扫描」就会出现。')),
410
410
  opened ? h('div', { style: { ...S.text, marginTop: 10 } }, (opened.title || opened.rel || '') + '\n\n' + opened.text) : null,
411
411
  ),
412
+ (works && works.images && works.images.length) ? h('div', { style: S.card },
413
+ h('div', { style: S.row },
414
+ h('div', { style: { fontWeight: 600 } }, '画'),
415
+ h('div', { style: S.dim }, '作品目录与 art 里的图 · 新的在前 · 点一张看大图'),
416
+ ),
417
+ h('div', {
418
+ style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 10, marginTop: 10 },
419
+ },
420
+ works.images.map((m, i) => h('div', {
421
+ key: 'img' + i,
422
+ style: { border: '1px solid ' + C.line, borderRadius: 8, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: 'rgba(255,255,255,0.02)' },
423
+ },
424
+ h('div', {
425
+ style: { cursor: 'zoom-in', lineHeight: 0, background: 'rgba(0,0,0,0.15)' },
426
+ title: m.path,
427
+ onClick: () => window.open(m.url, '_blank'),
428
+ }, h('img', {
429
+ src: m.url,
430
+ alt: m.name,
431
+ loading: 'lazy',
432
+ style: { width: '100%', height: 120, objectFit: 'cover', display: 'block' },
433
+ })),
434
+ h('div', { style: { padding: '6px 8px', display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 } },
435
+ h('div', { style: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: m.rel }, m.name),
436
+ h('div', { style: { ...S.dim, fontSize: 11 } }, (m.width && m.height ? (m.width + '×' + m.height + ' · ') : '') + fmt(m.size)),
437
+ h('div', { style: { ...S.dim, fontSize: 11 } }, new Date(m.mtime).toLocaleString()),
438
+ ),
439
+ )),
440
+ ),
441
+ ) : null,
412
442
  )
413
443
 
414
444
  const setTabView = h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
package/index.js CHANGED
@@ -272,6 +272,27 @@ export async function listBooks(dir) {
272
272
  return out
273
273
  }
274
274
 
275
+ /** 只读章表,不存在就返回 null(不触发建表) */
276
+ async function readTocOnly(dir, id) {
277
+ const t = await readJson(tocPath(dir, id), null)
278
+ return t && t.version === TOC_VERSION && Array.isArray(t.chapters) ? t : null
279
+ }
280
+
281
+ /** 书名匹配:先精确 id,再书名精确,再片段(唯一命中才算认出) */
282
+ export function resolveBookId(st, shelf, query) {
283
+ const key = String(query || '').trim()
284
+ if (!key) throw new Error('没有这本书:')
285
+ const ids = shelf.map((b) => b.id)
286
+ if (ids.includes(key)) return key
287
+ const books = st.books || {}
288
+ const exact = ids.filter((id) => (books[id]?.title || id) === key)
289
+ if (exact.length === 1) return exact[0]
290
+ const hits = ids.filter((id) => id.includes(key) || String(books[id]?.title || '').includes(key))
291
+ if (hits.length === 1) return hits[0]
292
+ if (hits.length > 1) throw new Error(`书名不唯一:${key}(可能是 ${hits.join(' / ')})`)
293
+ throw new Error(`没有这本书:${key}`)
294
+ }
295
+
275
296
  /** 打开某本书:优先用章表(不整本 decode),没有章表才扫一遍并落盘 */
276
297
  export async function bookInfo(dir, id) {
277
298
  const toc = await tocFor(dir, id)
@@ -391,6 +412,113 @@ export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
391
412
  return p
392
413
  }
393
414
 
415
+ /* ---------------- 图片:作品与画 ------------------
416
+ * 只扫固定几个目录(作品目录、同级的 art),递归但跳过 archive / 缓存目录;
417
+ * 单张超 MAX_IMAGE_BYTES 直接跳过(不读、不加载)。
418
+ */
419
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024
420
+ const IMAGE_EXT_RE = /\.(png|jpe?g|webp)$/i
421
+ const IMAGE_SKIP_DIRS = new Set(['archive', '.trash', 'node_modules', '.git', 'tmp', 'cache'])
422
+
423
+ /** 只读文件头,认 PNG / JPEG / WebP 的像素尺寸;认不出返回 null */
424
+ export async function imageSizeOf(file) {
425
+ let buf
426
+ try {
427
+ const fh = await open(file, 'r')
428
+ try {
429
+ buf = Buffer.alloc(256 * 1024)
430
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0)
431
+ buf = buf.subarray(0, bytesRead)
432
+ } finally { await fh.close() }
433
+ } catch { return null }
434
+ try {
435
+ // PNG: 8 字节签名 + IHDR
436
+ if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
437
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) }
438
+ }
439
+ // WebP
440
+ if (buf.length > 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
441
+ const fourcc = buf.toString('ascii', 12, 16)
442
+ if (fourcc === 'VP8 ') return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff }
443
+ if (fourcc === 'VP8L') {
444
+ const b = buf.readUInt32LE(21)
445
+ return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 }
446
+ }
447
+ if (fourcc === 'VP8X') {
448
+ return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 }
449
+ }
450
+ }
451
+ // JPEG: 找 SOF 段
452
+ if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
453
+ let i = 2
454
+ while (i + 9 < buf.length) {
455
+ if (buf[i] !== 0xff) { i++; continue }
456
+ const m = buf[i + 1]
457
+ if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue }
458
+ const len = buf.readUInt16BE(i + 2)
459
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
460
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) }
461
+ }
462
+ i += 2 + len
463
+ }
464
+ }
465
+ } catch {}
466
+ return null
467
+ }
468
+
469
+ function imageMimeOf(name) {
470
+ const e = extname(name).toLowerCase()
471
+ if (e === '.png') return 'image/png'
472
+ if (e === '.webp') return 'image/webp'
473
+ return 'image/jpeg'
474
+ }
475
+
476
+ /** 在 root 下递归找图(跳过 archive 一类目录),按 mtime 倒序 */
477
+ export async function scanImages(root, kind) {
478
+ const out = []
479
+ const walk = async (p, rel) => {
480
+ let list = []
481
+ try { list = await readdir(p, { withFileTypes: true }) } catch { return }
482
+ for (const d of list) {
483
+ if (d.name.startsWith('.')) continue
484
+ const abs = join(p, d.name)
485
+ const r = rel ? rel + '/' + d.name : d.name
486
+ if (d.isDirectory()) {
487
+ if (IMAGE_SKIP_DIRS.has(d.name.toLowerCase())) continue
488
+ await walk(abs, r)
489
+ continue
490
+ }
491
+ if (!IMAGE_EXT_RE.test(d.name)) continue
492
+ let s
493
+ try { s = await stat(abs) } catch { continue }
494
+ if (!s.isFile() || s.size > MAX_IMAGE_BYTES) continue
495
+ const size = await imageSizeOf(abs)
496
+ out.push({
497
+ kind, root, rel: r, name: d.name, path: abs, size: s.size, mtime: s.mtime.toISOString(),
498
+ width: size ? size.width : 0, height: size ? size.height : 0,
499
+ url: '/dsh-reading.image?path=' + encodeURIComponent(abs),
500
+ })
501
+ }
502
+ }
503
+ await walk(root, '')
504
+ return out
505
+ }
506
+
507
+ /** 允许给浏览器读的图片根:作品目录 + 同级/配置里的 art */
508
+ export async function imageRoots(worksDir) {
509
+ const roots = [resolve(worksDir)]
510
+ const cfg = await config()
511
+ const cands = [cfg.artDir, join(dirname(dirname(resolve(worksDir))), 'art'), join(homedir(), 'dsh work', 'art')]
512
+ for (const p of cands) {
513
+ if (!p) continue
514
+ try {
515
+ const s = await stat(p)
516
+ if (s.isDirectory()) { roots.push(resolve(p)); break }
517
+ } catch {}
518
+ }
519
+ return roots
520
+ }
521
+
394
522
  /* ---------------- HTTP 与工具 ---------------- */
395
523
 
396
524
  export function apply(ctx) {
@@ -604,7 +732,40 @@ async function signWork(rel, who) {
604
732
  }
605
733
  await walk(root, '')
606
734
  out.sort((a, b) => b.mtime.localeCompare(a.mtime))
607
- res.end(JSON.stringify({ ok: true, root, files: out }))
735
+ // 图片另算一块:作品目录 + art,跳过 archive;超 10MB 的不列
736
+ const roots = await imageRoots(root)
737
+ let images = []
738
+ for (const r of roots) images = images.concat(await scanImages(r, r === resolve(root) ? 'works' : 'art'))
739
+ images.sort((a, b) => b.mtime.localeCompare(a.mtime))
740
+ res.end(JSON.stringify({ ok: true, root, roots, files: out, images }))
741
+ },
742
+ }),
743
+ )
744
+
745
+ // 给面板读一张图(限制在上面那几个根里)
746
+ ctx.effect(() =>
747
+ ctx.webServer.register({
748
+ kind: 'exact',
749
+ path: '/dsh-reading.image',
750
+ async handler(req, res) {
751
+ try {
752
+ const u = new URL(req.url, 'http://x')
753
+ const p = resolve(String(u.searchParams.get('path') || ''))
754
+ const root = await worksDir()
755
+ const roots = await imageRoots(root)
756
+ const n = (x) => x.replace(/\\/g, '/').toLowerCase()
757
+ const inside = roots.some((r) => n(p) === n(r) || n(p).startsWith(n(r) + '/'))
758
+ if (!inside) { res.statusCode = 403; return res.end('forbidden') }
759
+ if (!IMAGE_EXT_RE.test(p)) { res.statusCode = 400; return res.end('not an image') }
760
+ const s = await stat(p)
761
+ if (s.size > MAX_IMAGE_BYTES) { res.statusCode = 413; return res.end('too large') }
762
+ res.setHeader('content-type', imageMimeOf(p))
763
+ res.setHeader('cache-control', 'private, max-age=60')
764
+ res.end(await readFile(p))
765
+ } catch (e) {
766
+ res.statusCode = 404
767
+ res.end(String((e && e.message) || e))
768
+ }
608
769
  },
609
770
  }),
610
771
  )
@@ -1066,6 +1227,47 @@ async function signWork(rel, who) {
1066
1227
  }),
1067
1228
  )
1068
1229
 
1230
+ ctx.effect(() =>
1231
+ ctx.tools.register({
1232
+ name: 'reading_mark',
1233
+ description:
1234
+ '只记进度、不返回正文:把某本书记成「已读到第 N 章」。'
1235
+ + '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
1236
+ + '已读到只进不退(跳读可以,回退不会把进度改小)。',
1237
+ parameters: obj({
1238
+ book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主、古文观止' },
1239
+ chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
1240
+ todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
1241
+ }),
1242
+ output: textOut,
1243
+ async execute(args) {
1244
+ const { dir, st, shelf } = await stateOf()
1245
+ const id = resolveBookId(st, shelf, args?.book)
1246
+ // 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
1247
+ const toc = await readTocOnly(dir, id)
1248
+ const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
1249
+ const n = Math.floor(Number(args?.chapter))
1250
+ if (!(n >= 1)) throw new Error('章号要从 1 开始')
1251
+ if (chapters && n > chapters) throw new Error(`章号超出范围:1–${chapters}`)
1252
+ const incRaw = Math.floor(Number(args?.todayCount))
1253
+ const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
1254
+ const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
1255
+ const before = Number(rec.readThrough) || 0
1256
+ if (chapters) rec.chapters = chapters
1257
+ rec.readThrough = Math.max(before, n)
1258
+ rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
1259
+ rec.lastReadAt = new Date().toISOString()
1260
+ st.current = id
1261
+ const t = today()
1262
+ st.log = st.log || {}
1263
+ st.log[t] = st.log[t] || {}
1264
+ st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
1265
+ await saveState(dir, st)
1266
+ return `ok readThrough ${before} -> ${rec.readThrough} next ${rec.next} today ${st.log[t][id] || 0}`
1267
+ },
1268
+ }),
1269
+ )
1270
+
1069
1271
  ctx.effect(() =>
1070
1272
  ctx.tools.register({
1071
1273
  name: 'reading_note',
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "半页",
4
+ "description": "一间会自己读书的书房:一章一章地读,把读到哪儿记下来;读完想说什么,就写在那一章的边上;想写点自己的东西,也放在这儿。打开面板就能看见它今天翻了几页、这次写下了什么。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-half-page",
3
- "version": "0.3.36",
3
+ "version": "0.3.38",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",