@ggboy123/dsh-paper-reader 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -28,6 +28,29 @@
28
28
  * · 未回滚非空时**不得**声称「文献库未改变」(F-C:那句是服务端内层文案,只对失败那一篇成立);
29
29
  * · 没有回滚失败 ⇒ 只给简洁文案,不吓唬用户。
30
30
  */
31
+ /**
32
+ * 深色模式镜像(**纯函数**,与 reader/index.html 的键名字面一致):
33
+ * 阅读器是同源 iframe,但它的 <head> 首帧判定发生在网络请求之前 ⇒ 必须有一个**同步**可读的镜像。
34
+ * 配置的权威来源仍是服务端 /api/theme/config;这里只是镜像,写失败(隐私模式)不影响功能。
35
+ */
36
+ const DPR_THEME_PREF_KEY = 'dpr.pdfTheme'
37
+ const DPR_THEME_MIRROR_KEY = 'dpr.pdfThemeCfg'
38
+ function dprThemeMirror(cfg) {
39
+ if (!cfg || typeof cfg !== 'object') return null
40
+ const mode = ['follow', 'off', 'light', 'dark'].includes(cfg.pdfTheme) ? cfg.pdfTheme : 'follow'
41
+ const strength = Number.isInteger(cfg.pdfDarkStrength) ? cfg.pdfDarkStrength : 1
42
+ return { mode, strength, chrome: cfg.pdfDarkChrome !== false, curve: cfg.curve || null }
43
+ }
44
+ function writeThemeMirror(cfg) {
45
+ const mir = dprThemeMirror(cfg)
46
+ if (!mir) return null
47
+ try {
48
+ localStorage.setItem(DPR_THEME_PREF_KEY, mir.mode)
49
+ localStorage.setItem(DPR_THEME_MIRROR_KEY, JSON.stringify(mir))
50
+ } catch { /* 隐私模式:写不了镜像,阅读器仍可从服务端/宿主 postMessage 拿到 */ }
51
+ return mir
52
+ }
53
+
31
54
  function clearFailureText(err, t) {
32
55
  const files = Array.isArray(err && err.rollbackFailed) ? err.rollbackFailed.filter((x) => typeof x === 'string') : []
33
56
  const where = err && typeof err.trashRel === 'string' && err.trashRel ? err.trashRel : '.trash'
@@ -39,6 +62,107 @@ function clearFailureText(err, t) {
39
62
  }
40
63
  }
41
64
 
65
+ /* ═══════════════════════════════════════════════════════════════════════════
66
+ 嵌套专题(`A/B`)的**纯函数**层 —— 放在 load() 之外,Node 里可直接执行断言。
67
+
68
+ PR #8 维护者评审 A/H 的共同根因:客户端把「topic」当单段名,而新布局的 topic 是**路径**。
69
+ 这里集中几件事:
70
+ · `parseDprSession`:会话 id 里 topic/name 按**最后一个** `/` 切(论文名不含 `/`);
71
+ · `dprSessionStale`:ⓘ「对话还停在另一篇」的判定(子专题论文不再永远常亮);
72
+ · `dprReprefixTopic` / `dprRekeyTopicState`:专题改名后的**前缀感知**重写(cur / 折叠键 / dpr.last);
73
+ · `dprTopicPaperCount`:删除专题时 clear-vs-delete 的**子树**计数;
74
+ · `dprApiError` / `dprClearRetryNeeded`:把服务端 `clearEndpoint` 透传到 Error,让重试路径可达。
75
+ ═══════════════════════════════════════════════════════════════════════════ */
76
+
77
+ /**
78
+ * 伴读会话 id → `{topic, name, n}`;非伴读/畸形 id 返回 null。
79
+ * topic 是**路径**(可多级 `A/B`),只有论文名保证不含 `/` ⇒ 必须 `lastIndexOf('/')`。
80
+ * (用第一个 `/` 切会把 `A/B/P` 解成 topic=`A` / name=`B/P`,子专题论文的 ⓘ 按钮永远常亮。)
81
+ */
82
+ function parseDprSession(sid) {
83
+ if (typeof sid !== 'string' || !sid.startsWith('dpr-')) return null
84
+ try {
85
+ const body = sid.slice(4)
86
+ const m = body.match(/-(\d+)$/)
87
+ const n = m ? +m[1] : 1
88
+ const b64 = (m ? body.slice(0, -m[0].length) : body).replaceAll('-', '+').replaceAll('_', '/')
89
+ const bin = atob(b64)
90
+ const decoded = decodeURIComponent([...bin].map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''))
91
+ const sep = decoded.lastIndexOf('/')
92
+ if (sep <= 0 || sep === decoded.length - 1) return null
93
+ return { topic: decoded.slice(0, sep), name: decoded.slice(sep + 1), n }
94
+ } catch { return null }
95
+ }
96
+
97
+ /** 「对话还停在另一篇」判定(纯函数):会话绑定的论文与阅读器当前论文不一致才提示。 */
98
+ function dprSessionStale(chatPaper, viewed) {
99
+ if (!chatPaper || !viewed || !viewed.topic) return false
100
+ return chatPaper.topic !== viewed.topic || chatPaper.name !== viewed.name
101
+ }
102
+
103
+ /**
104
+ * 专题改名的**前缀感知**重写:`path === oldTopic` 或以 `oldTopic + '/'` 开头 ⇒ 换前缀;否则 null。
105
+ * 分隔符判定是必须的:`A` 改名成 `X/A` 时,同级同前缀名 `AB` 绝不能被误伤。
106
+ */
107
+ function dprReprefixTopic(path, oldTopic, newTopic) {
108
+ if (typeof path !== 'string' || typeof oldTopic !== 'string' || typeof newTopic !== 'string') return null
109
+ if (!oldTopic || path === '') return null
110
+ if (path === oldTopic) return newTopic
111
+ if (path.startsWith(oldTopic + '/')) return newTopic + path.slice(oldTopic.length)
112
+ return null
113
+ }
114
+
115
+ /**
116
+ * 专题改名后,客户端里所有「按专题路径记的身份」整体换前缀:
117
+ * `cur`(阅读器 iframe 的身份)/ `closed`(树折叠键)/ `last`(dpr.last 上次打开)。
118
+ * 返回新状态;调用方负责 setState / 派发 `dpr:paper` / 持久化折叠态。
119
+ */
120
+ function dprRekeyTopicState(oldTopic, newTopic, state) {
121
+ const st = state || {}
122
+ const out = { cur: st.cur ?? null, closed: {}, last: st.last ?? null }
123
+ if (st.cur && typeof st.cur === 'object') {
124
+ const t = dprReprefixTopic(st.cur.topic, oldTopic, newTopic)
125
+ if (t !== null) out.cur = { ...st.cur, topic: t }
126
+ }
127
+ for (const [k, v] of Object.entries(st.closed || {})) {
128
+ out.closed[dprReprefixTopic(k, oldTopic, newTopic) ?? k] = v
129
+ }
130
+ if (st.last && typeof st.last === 'object') {
131
+ const t = dprReprefixTopic(st.last.topic, oldTopic, newTopic)
132
+ if (t !== null) out.last = { ...st.last, topic: t }
133
+ }
134
+ return out
135
+ }
136
+
137
+ /**
138
+ * 专题子树内的论文数(`lib.papers` 是全量列表):删除专题时据此分流「清空」还是「直接删」。
139
+ * 只数**直接**论文会让「论文全在子专题里」的专题没有 UI 路径到 /topic/clear。
140
+ * 判定必须带分隔符:写 `startsWith(topic)` 会把 `AB` 算进 `A`。
141
+ */
142
+ function dprTopicPaperCount(papers, topic) {
143
+ if (typeof topic !== 'string' || !topic) return 0
144
+ return (papers || []).filter((p) => p && typeof p.topic === 'string' && (p.topic === topic || p.topic.startsWith(topic + '/'))).length
145
+ }
146
+
147
+ /** HTTP 失败响应 → 带机器码的 Error(`code`/`status`/`papers`/`entries` + `clearEndpoint` 透传)。 */
148
+ function dprApiError(status, body) {
149
+ const b = body && typeof body === 'object' ? body : {}
150
+ const err = new Error(b.error || b.reason || ('HTTP ' + status))
151
+ err.code = b.code
152
+ err.status = status
153
+ if (b.papers) err.papers = b.papers
154
+ if (b.entries) err.entries = b.entries
155
+ // 服务端 409 topic-not-empty 会带「下一步」端点;不挂到 Error 上,doDeleteTopic 的重试就是死代码
156
+ if (b.clearEndpoint) err.clearEndpoint = b.clearEndpoint
157
+ if (b.clearPlanEndpoint) err.clearPlanEndpoint = b.clearPlanEndpoint
158
+ return err
159
+ }
160
+
161
+ /** 删除专题撞上「非空」且服务端给了清空入口 ⇒ 改走批量清空中间态(其余错误不重试)。 */
162
+ function dprClearRetryNeeded(err) {
163
+ return !!(err && err.code === 'topic-not-empty' && err.clearEndpoint)
164
+ }
165
+
42
166
  /**
43
167
  * 分屏「同步滚动」偏好 —— **纯函数**(文件顶层:Node 里执行本文件即可取用,测试 harness 追加导出)。
44
168
  * 与 `reader/index.html` 里的同键读写必须保持同一套编码,所以两边都只认 `'1'` / `'0'`。
@@ -83,7 +207,7 @@ window.__ModuleLoader__.load({
83
207
  setEmbedTitle: '嵌入模型检索(可选)',
84
208
  setEmbedDesc: 'search_paper 的语义召回:分块文本会发送到该 OpenAI 兼容 /embeddings 端点,用向量把「关键词一个字都没命中」的语义相近片段也捞进候选(与关键词结果融合,不替代)。留空即关闭,检索行为与现在完全一致。注意:分块文本(论文正文)会发往该端点。',
85
209
  setTranslateTitle: '翻译端点',
86
- setTranslateDesc: '「生成中文版」(babeldoc)用的 OpenAI 兼容端点,三项必填。保存前会先测连接。',
210
+ setTranslateDesc: '「生成中文版」(babeldoc)与划词翻译共用的 OpenAI 兼容端点,三项必填。OpenCode Go 填 https://opencode.ai/inference/go/openai/v1(插件会自动带 x-opencode-session)。保存前会先测连接。',
87
211
  setBaseUrl: '端点 URL', setModel: '模型', setKey: 'API Key',
88
212
  setSave: '测试并保存', setSaving: '测试连接中…', setClear: '清除自填配置',
89
213
  setSaved: '已保存,立即生效', setCleared: '已清除,回落到部署方默认',
@@ -147,6 +271,27 @@ window.__ModuleLoader__.load({
147
271
  eqChip: '第 {page} 页 · 公式 {k}',
148
272
  eqTranslatedView: '译文视图没有公式位置信息,切回原文可点击',
149
273
  eqNoPosition: '无位置信息',
274
+ // 深色模式(方案 §A2.3):模式 / 强度 / 界面;文案里**如实写明图片会变负片**这一已知代价
275
+ setThemeTitle: 'PDF 深色模式',
276
+ setThemeDesc: 'dsh 切到深色时把 PDF 一起变深色(默认「跟随」)。实现是整页反色 + 色相回正:论文里的图片/照片会明显褪色偏色(实测纯红 [255,0,0] → 浅粉 [229,134,134],不是真负片)——这是已知代价(与 Sioyek #171 同源);「关闭」可一键绕过。下载/导出的 PDF 始终是原文,不受影响。',
277
+ setThemeMode: '模式',
278
+ setThemeModeFollow: '跟随 dsh 主题(默认)',
279
+ setThemeModeOff: '关闭(PDF 保持原色)',
280
+ setThemeModeLight: '强制浅色',
281
+ setThemeModeDark: '强制深色',
282
+ setThemeStrength: '强度(越往下越柔和)',
283
+ setThemeStrength0: '最黑',
284
+ setThemeStrength1: '近黑(默认)',
285
+ setThemeStrength2: '柔和',
286
+ setThemeStrength3: '纸感',
287
+ setThemeChrome: '阅读器界面也切深色(顶栏/面板)',
288
+ setThemeHint: '当前:{state}。设置面板与阅读器里的「A」按钮共用同一份配置,改一处另一处立即生效。',
289
+ setThemeStateDark: '深色生效中',
290
+ setThemeStateLight: '浅色(不变深)',
291
+ // 嵌套子专题(方案 §B2):目录即层级;论文按文件夹整理
292
+ newSubTopic: '新建子专题', moveTopic: '移动到…', moveTopicTitle: '移动到(目标父专题路径,留空=顶层):',
293
+ moveTopicHint: '整棵子树跟着移动;历史伴读会话不会删除,但会与树脱钩(确认框会给出数量)',
294
+ uploadHere: '上传 PDF 到此处',
150
295
  }
151
296
  const en = {
152
297
  library: 'Library',
@@ -165,7 +310,7 @@ window.__ModuleLoader__.load({
165
310
  setEmbedTitle: 'Embedding search (optional)',
166
311
  setEmbedDesc: 'Semantic recall for search_paper: chunk texts are sent to this OpenAI-compatible /embeddings endpoint so passages that share no keywords but are semantically close still enter the candidate set (fused with keyword hits, never replacing them). Leave empty to keep it off — search behaviour stays exactly as today. Note: chunk texts (paper body) are sent to this endpoint.',
167
312
  setTranslateTitle: 'Translate endpoint',
168
- setTranslateDesc: 'OpenAI-compatible endpoint for "Generate Chinese version" (babeldoc). All three fields required. Connection is tested before saving.',
313
+ setTranslateDesc: 'OpenAI-compatible endpoint shared by "Generate Chinese version" (babeldoc) and selection translation; all three fields required. For OpenCode Go use https://opencode.ai/inference/go/openai/v1 (the plugin adds x-opencode-session automatically). Connection is tested before saving.',
169
314
  setBaseUrl: 'Endpoint URL', setModel: 'Model', setKey: 'API Key',
170
315
  setSave: 'Test & save', setSaving: 'Testing…', setClear: 'Clear my config',
171
316
  setSaved: 'Saved, effective immediately', setCleared: 'Cleared, falling back to deployment defaults',
@@ -221,6 +366,25 @@ window.__ModuleLoader__.load({
221
366
  eqChip: 'p.{page} · formula {k}',
222
367
  eqTranslatedView: 'No positions in the translated view — switch back to the original',
223
368
  eqNoPosition: 'No position info',
369
+ setThemeTitle: 'PDF dark mode',
370
+ setThemeDesc: 'When dsh goes dark, make the PDF dark too (default: follow). It inverts the whole page and rotates hue back, so photos/figures visibly desaturate and shift colour (measured: pure red [255,0,0] becomes pink [229,134,134], not a true negative) — a known cost (same root cause as Sioyek #171); switch to "Off" to bypass. Downloaded/exported PDFs are always the original bytes.',
371
+ setThemeMode: 'Mode',
372
+ setThemeModeFollow: 'Follow dsh theme (default)',
373
+ setThemeModeOff: 'Off (keep the PDF as-is)',
374
+ setThemeModeLight: 'Force light',
375
+ setThemeModeDark: 'Force dark',
376
+ setThemeStrength: 'Strength (softer downwards)',
377
+ setThemeStrength0: 'Blackest',
378
+ setThemeStrength1: 'Near-black (default)',
379
+ setThemeStrength2: 'Soft',
380
+ setThemeStrength3: 'Paper-like',
381
+ setThemeChrome: 'Darken the reader UI too (toolbar/panels)',
382
+ setThemeHint: 'Currently: {state}. The settings panel and the reader "A" button share one server-side config - changing either applies immediately.',
383
+ setThemeStateDark: 'dark applied',
384
+ setThemeStateLight: 'light (unchanged)',
385
+ newSubTopic: 'New subtopic', moveTopic: 'Move to...', moveTopicTitle: 'Move to (target parent topic path, empty = top level):',
386
+ moveTopicHint: 'The whole subtree moves with it; past chats are kept but detach from the tree (the count is reported).',
387
+ uploadHere: 'Upload a PDF here',
224
388
  }
225
389
 
226
390
  let t = (k) => k
@@ -242,6 +406,20 @@ window.__ModuleLoader__.load({
242
406
  阅读器 bootstrap 直达目标页。 */
243
407
  let readerIframeEl = null
244
408
  let pendingJump = null // { page, q }:跨论文/iframe 未就绪时挂上 src,由阅读器 bootstrap 消费
409
+ /* 宿主(dsh)当前是否深色:来自官方 theme 服务(ctx.theme.getTheme().active.colorScheme),
410
+ 拿不到时保守判「亮色」(与阅读器的降级方向一致:宁可该黑没黑,绝不误黑)。 */
411
+ let dprHostDark = false
412
+ /** 把主题推给阅读器 iframe:postMessage(权威、无轮询)+ data 属性(排障/断言用)。 */
413
+ function pushThemeToReader() {
414
+ const payload = { type: 'dpr:theme' }
415
+ try {
416
+ const mir = JSON.parse(localStorage.getItem(DPR_THEME_MIRROR_KEY) || 'null')
417
+ if (mir) { payload.mode = mir.mode; payload.strength = mir.strength; payload.chrome = mir.chrome; payload.curve = mir.curve }
418
+ } catch { /* 镜像损坏:仍然推宿主亮暗 */ }
419
+ const effective = payload.mode === 'dark' || (payload.mode !== 'off' && payload.mode !== 'light' && dprHostDark) ? 'dark' : 'light'
420
+ try { if (readerIframeEl) readerIframeEl.setAttribute('data-dpr-theme', effective) } catch {}
421
+ try { readerIframeEl?.contentWindow?.postMessage({ type: 'dpr:theme', pdfTheme: payload.mode, pdfDarkStrength: payload.strength, pdfDarkChrome: payload.chrome, curve: payload.curve }, '*') } catch { /* 读文档还没起来:它自己会拉一次配置 */ }
422
+ }
245
423
  function jumpToPaperPage(topic, name, page, q) {
246
424
  // 阅读器页签若关着尽量展开(seat 未绑定时静默失败,跳转本身仍生效)
247
425
  try { clientApi?.sidebarRight?.openTab('dpr-reader', { revealIfOpened: true }) } catch {}
@@ -261,13 +439,9 @@ window.__ModuleLoader__.load({
261
439
  const r = await fetch('/paper-reader/api' + path, opts)
262
440
  if (!r.ok) {
263
441
  const body = await r.json().catch(() => ({}))
264
- const err = new Error(body.error || body.reason || ('HTTP ' + r.status))
265
- // 机器可读码挂到 Error 上:调用方按 code 分支(别去匹配中文文案)
266
- err.code = body.code
267
- err.status = r.status
268
- if (body.papers) err.papers = body.papers
269
- if (body.entries) err.entries = body.entries
270
- throw err
442
+ // 机器可读码/下一步端点统一挂到 Error 上(见顶层 dprApiError):调用方按 code 分支
443
+ // (别去匹配中文文案),并按 clearEndpoint 走「改批清空」的重试路径。
444
+ throw dprApiError(r.status, body)
271
445
  }
272
446
  return r.json()
273
447
  }
@@ -297,8 +471,18 @@ window.__ModuleLoader__.load({
297
471
  }
298
472
  }
299
473
  const last = JSON.parse(localStorage.getItem('dpr.last') || 'null')
300
- if (last && last.topic === oldTopic && (oldName == null || last.name === oldName)) {
301
- localStorage.setItem('dpr.last', JSON.stringify({ ...last, topic: newTopic, ...(oldName != null ? { name: newName } : {}) }))
474
+ // 前缀感知(评审 H1):dpr.last 里的 topic 也是**路径**——读 A/B 时改名 A→X/A,
475
+ // 它必须跟到 X/A/B,否则刷新后阅读器回落 papers[0](阅读位置丢)。
476
+ // 逻辑与文件顶层的 dprReprefixTopic 同义;这里**内联**是为了让本函数能单独被提取执行
477
+ // (既有测试只抠出这一个函数体跑,不能依赖别处定义)。
478
+ if (last && typeof last.topic === 'string') {
479
+ const moved = last.topic === oldTopic
480
+ ? newTopic
481
+ : (last.topic.startsWith(oldTopic + '/') ? newTopic + last.topic.slice(oldTopic.length) : null)
482
+ const sameName = oldName == null || last.name === oldName
483
+ if (moved !== null && sameName) {
484
+ localStorage.setItem('dpr.last', JSON.stringify({ ...last, topic: moved, ...(oldName != null ? { name: newName } : {}) }))
485
+ }
302
486
  }
303
487
  } catch { /* 隐私模式等写不了就算了 */ }
304
488
  }
@@ -515,21 +699,8 @@ window.__ModuleLoader__.load({
515
699
  官方 header.actions 是 session 作用域 slot,动态包(ModuleLoader)注册的条目
516
700
  不被渲染(实测:register 成功但零渲染)——退化为 fixed 浮动组,portal 到 body,
517
701
  200ms 轮询对齐对话列头部右侧原生按钮的左缘;仅当前会话是伴读会话(dpr-)时显示。
518
- 历史点开下拉:该论文全部会话(真实标题+日期),点哪条进哪条。 */
519
- function parseDprSession(sid) {
520
- if (typeof sid !== 'string' || !sid.startsWith('dpr-')) return null
521
- try {
522
- const body = sid.slice(4)
523
- const m = body.match(/-(\d+)$/)
524
- const n = m ? +m[1] : 1
525
- const b64 = (m ? body.slice(0, -m[0].length) : body).replaceAll('-', '+').replaceAll('_', '/')
526
- const bin = atob(b64)
527
- const decoded = decodeURIComponent([...bin].map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0')).join(''))
528
- const sep = decoded.indexOf('/')
529
- if (sep <= 0 || sep === decoded.length - 1) return null
530
- return { topic: decoded.slice(0, sep), name: decoded.slice(sep + 1), n }
531
- } catch { return null }
532
- }
702
+ 历史点开下拉:该论文全部会话(真实标题+日期),点哪条进哪条。
703
+ (`parseDprSession` 是文件顶层的纯函数:topic 是路径,按 lastIndexOf('/') 切。) */
533
704
 
534
705
  function SessionActions(props) {
535
706
  const { uiWorkspace } = props
@@ -599,7 +770,8 @@ window.__ModuleLoader__.load({
599
770
 
600
771
  const chatPaper = parseDprSession(curSid)
601
772
  const paper = viewed || chatPaper
602
- const mismatch = !!(chatPaper && viewed && viewed.topic && (chatPaper.topic !== viewed.topic || chatPaper.name !== viewed.name))
773
+ // 子专题论文(topic=A/B)必须解析出同样的 topic/name,否则 ⚠ 永远常亮(评审 A 第二条)
774
+ const mismatch = dprSessionStale(chatPaper, viewed)
603
775
  const activeN = chatPaper?.n ?? paper?.n
604
776
 
605
777
  // 下拉打开时拉该论文的会话列表;点外面关闭
@@ -796,6 +968,10 @@ window.__ModuleLoader__.load({
796
968
  const { layout, uiWorkspace, sidebarRight, wide, expandSidebar } = props
797
969
  const [lib, setLib] = useState(null)
798
970
  const [closed, setClosed] = useState(() => JSON.parse(localStorage.getItem('dpr.treeClosed') || '{}'))
971
+ /* 折叠态:键从「专题名」升级为「专题路径」(含 `/`,方案 §B2.3)。
972
+ 一级专题的历史键就是「专题名」=路径本身,所以旧数据天然兼容(无需额外映射)。
973
+ 默认:一级展开(现状不变)、子专题折叠(避免深层树一次铺开)。 */
974
+ const collapsedOf = (path, depth) => (Object.prototype.hasOwnProperty.call(closed, path) ? !!closed[path] : depth > 0)
799
975
  const [sessions, setSessions] = useState({}) // `${topic}/${name}` → [{n, sessionId, running}]
800
976
  const [cur, setCur] = useState(() => JSON.parse(localStorage.getItem('dpr.last') || 'null'))
801
977
  const fileInput = React.useRef(null)
@@ -958,6 +1134,21 @@ window.__ModuleLoader__.load({
958
1134
  // 新建专题:window.prompt 在 Electron 渲染进程不可用(抛 "prompt() is not
959
1135
  // supported",点击无任何反应),改为 AskText 页内弹窗(见 LibraryTree return)。
960
1136
  const newTopic = useCallback(() => setAskTopic(true), [])
1137
+ // 子专题:目标父路径('' = 顶层);目录即层级 ⇒ 后端 mkdir recursive + 父目录必须存在
1138
+ const [askSub, setAskSub] = useState(null) // { parent }
1139
+ const [moving, setMoving] = useState(null) // { topic }
1140
+ const createSubTopic = useCallback(async (parent, name) => {
1141
+ const path = parent ? `${parent}/${name}` : name
1142
+ try {
1143
+ await api('/library/topic', {
1144
+ method: 'POST', headers: { 'content-type': 'application/json' },
1145
+ body: JSON.stringify({ name: path }),
1146
+ })
1147
+ // 新建后展开父节点,用户能立刻看到结果
1148
+ setClosed((c) => { const n = { ...c, [parent || path]: false }; try { localStorage.setItem('dpr.treeClosed', JSON.stringify(n)) } catch {} return n })
1149
+ refresh()
1150
+ } catch (err) { toast(t('newTopicFail') + ': ' + err.message) }
1151
+ }, [refresh])
961
1152
 
962
1153
  /* ---------- 库管理:改名/删除(用户反馈补齐) ----------
963
1154
  已知代价(README 明示):sessionId 编码旧 topic/name,改名后历史伴读会话从树上
@@ -985,14 +1176,26 @@ window.__ModuleLoader__.load({
985
1176
  // 本地记忆(语言版本/会话序号/上次打开/折叠态)搬到新身份
986
1177
  migrateLsKeys(topic, newTopicName, kind === 'paper' ? name : null, kind === 'paper' ? newName : null)
987
1178
  setSessions((m) => { const c = { ...m }; delete c[`${topic}/${name}`]; return c })
988
- if (kind === 'topic') setClosed((c) => {
989
- if (!(topic in c)) return c
990
- const n = { ...c }; n[to] = c[topic]; delete n[topic]
991
- try { localStorage.setItem('dpr.treeClosed', JSON.stringify(n)) } catch {}
992
- return n
993
- })
994
- // 改的是当前论文(或其所在专题)→ 树与阅读器 iframe 跟到新身份
995
- if (cur && (kind === 'topic' ? cur.topic === topic : (cur.topic === topic && cur.name === name))) {
1179
+ if (kind === 'topic') {
1180
+ // 前缀感知(评审 H1):折叠键里可能是更深的子专题(`A/B`),按精确相等搬会漏;
1181
+ // `A` vs 同级同前缀名 `AB` 由 dprReprefixTopic 的分隔符判定区分,绝不误伤。
1182
+ setClosed((c) => {
1183
+ const rekeyed = dprRekeyTopicState(topic, to, { closed: c }).closed
1184
+ const changed = Object.keys(rekeyed).length !== Object.keys(c).length
1185
+ || Object.entries(c).some(([k, v]) => rekeyed[k] !== v)
1186
+ if (!changed) return c
1187
+ try { localStorage.setItem('dpr.treeClosed', JSON.stringify(rekeyed)) } catch { /* 隐私模式 */ }
1188
+ return rekeyed
1189
+ })
1190
+ // 正在读的论文若在改名的专题(含子专题)下 ⇒ cur / iframe 身份整体换前缀。
1191
+ // 否则 iframe 还持 `?topic=A/B`:提问、翻译全 404,刷新后回落 papers[0](阅读位置丢)。
1192
+ const rekeyed = dprRekeyTopicState(topic, to, { cur })
1193
+ if (rekeyed.cur && rekeyed.cur !== cur) {
1194
+ setCur(rekeyed.cur)
1195
+ window.dispatchEvent(new CustomEvent('dpr:paper', { detail: { topic: rekeyed.cur.topic, name: rekeyed.cur.name } }))
1196
+ }
1197
+ } else if (cur && cur.topic === topic && cur.name === name) {
1198
+ // 改的是当前论文 → 树与阅读器 iframe 跟到新身份
996
1199
  setCur((c) => ({ ...c, topic: newTopicName, name: newName }))
997
1200
  window.dispatchEvent(new CustomEvent('dpr:paper', { detail: { topic: newTopicName, name: newName } }))
998
1201
  }
@@ -1085,7 +1288,9 @@ window.__ModuleLoader__.load({
1085
1288
  const openDelete = useCallback(async (kind, topic, name) => {
1086
1289
  try {
1087
1290
  if (kind === 'topic') {
1088
- const n = (lib?.papers ?? []).filter((p) => p.topic === name).length
1291
+ // 按**子树**计数(评审 H2):只数直接论文时,「论文全在子专题里」的专题会被当成空专题
1292
+ // 走删除 → 服务端 409 topic-not-empty → 用户没有 UI 路径到 /topic/clear。
1293
+ const n = dprTopicPaperCount(lib?.papers, name)
1089
1294
  if (n > 0) {
1090
1295
  // 非空专题 → 「批量清空」中间态(上游评论第 10 条:逐篇列清单、一次确认)。
1091
1296
  // 清单来自服务端 dry-run(topic/clear-plan),前端不自己拼;拿不到就如实报错,不弹空壳。
@@ -1181,7 +1386,9 @@ window.__ModuleLoader__.load({
1181
1386
  toast(t('delFail') + ':' + f.text + (f.recovery ? ' ' + f.recovery : ''), f.recovery ? 15000 : 6000)
1182
1387
  // 竞态:确认框弹出后该专题又有了文献 → 服务端 409 topic-not-empty 且带 clearEndpoint,
1183
1388
  // 直接改走「批量清空」中间态(服务端同源清单),不让用户从头再来一次。
1184
- if (e?.code === 'topic-not-empty' && e?.clearEndpoint) await openDelete('topic', d.name, d.name)
1389
+ // 判据走顶层纯函数(dprApiError 已把 clearEndpoint 透传到 Error)——此前 api() 没挂这个字段,
1390
+ // 该分支永远不可达(评审 H3 的死代码)。
1391
+ if (dprClearRetryNeeded(e)) await openDelete('topic', d.name, d.name)
1185
1392
  refresh()
1186
1393
  }
1187
1394
  }, [delDlg, refresh, switchAfterDelete, openDelete])
@@ -1194,6 +1401,70 @@ window.__ModuleLoader__.load({
1194
1401
 
1195
1402
  // 收起态(rail):官方契约 —— sidebar.workspaces 在窄栏里只该给一个图标入口,点击请求
1196
1403
  // 宿主展开。整棵树不渲染:塞进 56px 会被挤成竖排文字(实测)。
1404
+ const papersOf = (path) => papers.filter((p) => p.topic === path)
1405
+ /**
1406
+ * 递归渲染一个专题节点(含子专题与论文)。
1407
+ * 折叠:一级默认展开、子专题默认折叠(避免深层树一次铺开,方案 §B2.3)。
1408
+ */
1409
+ const renderNode = (node, depth) => {
1410
+ const path = node.path || node.name
1411
+ const collapsed = collapsedOf(path, depth)
1412
+ const childPapers = papersOf(path)
1413
+ const children = node.children || []
1414
+ const hasKids = children.length > 0 || childPapers.length > 0
1415
+ return h('div', { key: path },
1416
+ h('div', {
1417
+ style: { ...S.topicHead, ...(depth > 0 ? { paddingLeft: 6 + depth * 10 } : {}) }, 'data-dpr-row': '', 'data-dpr-topic': path,
1418
+ onClick: () => {
1419
+ const next = { ...closed, [path]: !collapsed }
1420
+ setClosed(next)
1421
+ try { localStorage.setItem('dpr.treeClosed', JSON.stringify(next)) } catch {}
1422
+ },
1423
+ },
1424
+ h('span', { style: { ...S.caret, transform: collapsed ? 'rotate(-90deg)' : 'none' } }, '▾'),
1425
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' }, title: path }, node.name || path),
1426
+ h('button', { style: S.iconBtn, title: t('uploadHere'), onClick: (e) => { e.stopPropagation(); upload(path) } }, '⬆'),
1427
+ h('button', { style: S.iconBtn, title: t('newSubTopic'), onClick: (e) => { e.stopPropagation(); setAskSub({ parent: path }) } }, '+'),
1428
+ h('button', {
1429
+ 'data-dpr-act': 'rename', style: S.iconBtn, title: t('rename'),
1430
+ onClick: (e) => { e.stopPropagation(); setRenaming({ kind: 'topic', topic: path }) },
1431
+ }, '✎'),
1432
+ h('button', {
1433
+ 'data-dpr-act': 'move', style: S.iconBtn, title: t('moveTopic'),
1434
+ onClick: (e) => { e.stopPropagation(); setMoving({ topic: path }) },
1435
+ }, '→'),
1436
+ h('button', {
1437
+ 'data-dpr-act': 'del', style: S.iconBtn, title: t('delTopic'),
1438
+ onClick: (e) => { e.stopPropagation(); openDelete('topic', path, path) },
1439
+ }, '🗑'),
1440
+ ),
1441
+ !collapsed && h('div', { style: S.items },
1442
+ // 论文节点(叶子):路径 = 父专题路径 + 论文名
1443
+ childPapers.map((p) => {
1444
+ const isCurrentPaper = cur && cur.topic === p.topic && cur.name === p.name
1445
+ return h('div', {
1446
+ key: path + '/' + p.name,
1447
+ style: { ...S.item, ...(depth > 0 ? { paddingLeft: 6 + depth * 10 } : {}), ...(isCurrentPaper ? S.active : {}) },
1448
+ 'data-dpr-row': '', 'data-dpr-paper': path + '/' + p.name,
1449
+ title: p.pdfPath || p.name,
1450
+ onClick: () => enter(p.topic, p.name),
1451
+ }, '📄 ',
1452
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' } }, p.name),
1453
+ h('button', {
1454
+ 'data-dpr-act': 'rename', style: S.iconBtn, title: t('rename'),
1455
+ onClick: (e) => { e.stopPropagation(); setRenaming({ kind: 'paper', topic: p.topic, name: p.name }) },
1456
+ }, '✎'),
1457
+ h('button', {
1458
+ 'data-dpr-act': 'del', style: S.iconBtn, title: t('delPaper'),
1459
+ onClick: (e) => { e.stopPropagation(); openDelete('paper', p.topic, p.name) },
1460
+ }, '🗑'))
1461
+ }),
1462
+ // 子专题(递归)
1463
+ children.map((c) => renderNode(c, depth + 1)),
1464
+ ),
1465
+ )
1466
+ }
1467
+
1197
1468
  // 用 wide === false 而非 !wide:宿主万一没传这个 prop 时按展开态走,即改动前的行为。
1198
1469
  const tree = wide === false
1199
1470
  ? h('div', { style: S.rail },
@@ -1213,55 +1484,10 @@ window.__ModuleLoader__.load({
1213
1484
  h('div', { style: { display: 'flex', gap: '8px', margin: '8px 0 2px' } },
1214
1485
  h('button', { type: 'button', style: S.linkBtn, onClick: () => uploadSmart() }, '⬆ ', t('uploadBtn')),
1215
1486
  h('button', { type: 'button', style: S.linkBtn, onClick: newTopic }, '+ ', t('newTopic')))),
1216
- topics.map((topic) => {
1217
- const isClosed = !!closed[topic]
1218
- return h('div', { key: topic },
1219
- h('div', {
1220
- style: S.topicHead, 'data-dpr-row': '',
1221
- onClick: () => {
1222
- const next = { ...closed, [topic]: !isClosed }
1223
- setClosed(next)
1224
- localStorage.setItem('dpr.treeClosed', JSON.stringify(next))
1225
- },
1226
- },
1227
- h('span', { style: { ...S.caret, transform: isClosed ? 'rotate(-90deg)' : 'none' } }, '▾'),
1228
- h('span', { style: { flex: 1 } }, topic),
1229
- h('button', {
1230
- style: S.iconBtn, title: t('upload'),
1231
- onClick: (e) => { e.stopPropagation(); upload(topic) },
1232
- }, '⬆'),
1233
- h('button', {
1234
- 'data-dpr-act': 'rename', style: S.iconBtn, title: t('rename'),
1235
- onClick: (e) => { e.stopPropagation(); setRenaming({ kind: 'topic', topic }) },
1236
- }, '✎'),
1237
- h('button', {
1238
- 'data-dpr-act': 'del', style: S.iconBtn, title: t('delTopic'),
1239
- onClick: (e) => { e.stopPropagation(); openDelete('topic', topic, topic) },
1240
- }, '🗑'),
1241
- ),
1242
- !isClosed && h('div', { style: S.items },
1243
- papers.filter((p) => p.topic === topic).map((p) => {
1244
- const isCurrentPaper = cur && cur.topic === p.topic && cur.name === p.name
1245
- return h('div', {
1246
- key: p.name,
1247
- style: { ...S.item, ...(isCurrentPaper ? S.active : {}) },
1248
- 'data-dpr-row': '',
1249
- title: p.pdfPath || p.name,
1250
- onClick: () => enter(p.topic, p.name),
1251
- }, '📄 ',
1252
- h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis' } }, p.name),
1253
- h('button', {
1254
- 'data-dpr-act': 'rename', style: S.iconBtn, title: t('rename'),
1255
- onClick: (e) => { e.stopPropagation(); setRenaming({ kind: 'paper', topic: p.topic, name: p.name }) },
1256
- }, '✎'),
1257
- h('button', {
1258
- 'data-dpr-act': 'del', style: S.iconBtn, title: t('delPaper'),
1259
- onClick: (e) => { e.stopPropagation(); openDelete('paper', p.topic, p.name) },
1260
- }, '🗑'))
1261
- }),
1262
- ),
1263
- )
1264
- }),
1487
+ // 递归渲染专题树(方案 §B2.3):专题节点可折叠,论文节点是叶子。
1488
+ // 数据来自服务端 /api/library 的 `tree`(完整嵌套树);`papers` 里的 topic 是相对路径,
1489
+ // 逐节点用 path 精确匹配(**不用前缀匹配** —— `A` 会误伤兄弟 `A/B`,R10 的教训)。
1490
+ (lib?.tree ?? topics.map((t) => ({ name: t, path: t, papers: [], children: [] }))).map((node) => renderNode(node, 0)),
1265
1491
  )
1266
1492
 
1267
1493
  return h('div', {
@@ -1281,6 +1507,30 @@ window.__ModuleLoader__.load({
1281
1507
  onCancel: () => setAskTopic(false),
1282
1508
  }),
1283
1509
  document.body),
1510
+ // 新建子专题(方案 §B2.3):输入的是**相对父专题的名字**,服务端拼成路径后 mkdir
1511
+ askSub && createPortal(
1512
+ h(AskText, {
1513
+ title: `${t('newSubTopic')}:${askSub.parent}/`, confirmText: t('ok'), cancelText: t('cancel'),
1514
+ onConfirm: (name) => { const p = askSub.parent; setAskSub(null); createSubTopic(p, name) },
1515
+ onCancel: () => setAskSub(null),
1516
+ }),
1517
+ document.body),
1518
+ // 移动到…(方案 §B2.3:不引入 HTML5 拖拽,改用输入目标父路径;整棵子树跟着走)
1519
+ moving && createPortal(
1520
+ h(AskText, {
1521
+ title: t('moveTopicTitle'),
1522
+ initial: (() => { const parts = moving.topic.split('/'); parts.pop(); return parts.join('/') })(),
1523
+ confirmText: t('ok'), cancelText: t('cancel'),
1524
+ onConfirm: (parent) => {
1525
+ const mv = moving
1526
+ setMoving(null)
1527
+ const name = mv.topic.split('/').pop()
1528
+ const to = parent.trim() ? `${parent.trim().replace(/\/+$/, '')}/${name}` : name
1529
+ doRename('topic', mv.topic, null, to)
1530
+ },
1531
+ onCancel: () => setMoving(null),
1532
+ }),
1533
+ document.body),
1284
1534
  // 重命名:上游 v1.3.0 的页内输入弹窗(初始值 = 旧名,走 migrateLsKeys 迁移本地记忆)
1285
1535
  renaming && createPortal(
1286
1536
  h(AskText, {
@@ -1507,6 +1757,67 @@ window.__ModuleLoader__.load({
1507
1757
  )
1508
1758
  }
1509
1759
 
1760
+ /* ---------- 深色模式卡片(方案 §A2.3 入口 1)----------
1761
+ 与阅读器 ⚙ 浮层里的同一组控件读/写**同一个后端配置**(/api/theme/config),
1762
+ 并写一份 localStorage 镜像:阅读器 iframe 的 <head> 首帧判定要在网络请求之前同步读到它,
1763
+ 而 storage 事件会让已打开的阅读器立即跟着变(跨文档,无需轮询)。 */
1764
+ function ThemeCard() {
1765
+ const [cfg, setCfg] = useState(null)
1766
+ const [msg, setMsg] = useState(null)
1767
+ const [busy, setBusy] = useState(false)
1768
+ const load = useCallback(() => {
1769
+ api('/theme/config').then((d) => { setCfg(d); writeThemeMirror(d) })
1770
+ .catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
1771
+ }, [])
1772
+ useEffect(load, [load])
1773
+ const save = async (patch) => {
1774
+ setBusy(true); setMsg(null)
1775
+ try {
1776
+ const r = await api('/theme/config', {
1777
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch),
1778
+ })
1779
+ setCfg(r); writeThemeMirror(r); setMsg({ ok: true, text: t('setSaved') })
1780
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy(false) }
1781
+ }
1782
+ const modeOptions = [
1783
+ ['follow', t('setThemeModeFollow')], ['off', t('setThemeModeOff')],
1784
+ ['light', t('setThemeModeLight')], ['dark', t('setThemeModeDark')],
1785
+ ]
1786
+ const strengthOptions = [[0, t('setThemeStrength0')], [1, t('setThemeStrength1')], [2, t('setThemeStrength2')], [3, t('setThemeStrength3')]]
1787
+ const dark = cfg && (cfg.pdfTheme === 'dark' || (cfg.pdfTheme === 'follow' && dprHostDark))
1788
+ return h('div', { style: SET.card, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-part': 'settings-card', 'data-dpr-theme-card': '' },
1789
+ h('h3', { style: SET.title }, t('setThemeTitle')),
1790
+ h('p', { style: SET.desc }, t('setThemeDesc')),
1791
+ h('div', { style: SET.row },
1792
+ h('label', { style: SET.label }, t('setThemeMode')),
1793
+ h('select', {
1794
+ style: SET.input, disabled: busy, 'data-dpr-theme-mode': '', value: cfg?.pdfTheme || 'follow',
1795
+ onChange: (e) => save({ pdfTheme: e.target.value }),
1796
+ }, modeOptions.map(([v, label]) => h('option', { key: v, value: v }, label))),
1797
+ ),
1798
+ h('div', { style: SET.row },
1799
+ h('label', { style: SET.label }, t('setThemeStrength')),
1800
+ h('select', {
1801
+ style: SET.input, disabled: busy, 'data-dpr-theme-strength': '', value: String(cfg?.pdfDarkStrength ?? 1),
1802
+ onChange: (e) => save({ pdfDarkStrength: Number(e.target.value), pdfDarkAdvanced: null }),
1803
+ }, strengthOptions.map(([v, label]) => h('option', { key: v, value: String(v) }, label))),
1804
+ ),
1805
+ h('div', { style: SET.row },
1806
+ h('label', { style: { ...SET.label, display: 'flex', alignItems: 'center', gap: '8px', margin: '0' }, 'data-dpr-theme-chrome-label': '' },
1807
+ h('input', {
1808
+ type: 'checkbox', checked: cfg?.pdfDarkChrome !== false, disabled: busy, 'data-dpr-theme-chrome': '',
1809
+ style: { width: '16px', height: '16px', cursor: 'pointer', accentColor: 'var(--dsw-alias-button-primary-fill, #1f6feb)' },
1810
+ onChange: (e) => save({ pdfDarkChrome: e.target.checked }),
1811
+ }),
1812
+ t('setThemeChrome'),
1813
+ ),
1814
+ ),
1815
+ h('p', { style: SET.desc, 'data-dpr-theme-hint': '' },
1816
+ t('setThemeHint').replace('{state}', dark ? t('setThemeStateDark') : t('setThemeStateLight'))),
1817
+ msg ? h('span', { style: msg.ok ? SET.ok : SET.err }, msg.text) : null,
1818
+ )
1819
+ }
1820
+
1510
1821
  function SettingsPanel() {
1511
1822
  return h('div', { style: { maxWidth: '560px' }, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-surface': 'settings-modal' },
1512
1823
  h(EndpointCard, {
@@ -1523,6 +1834,7 @@ window.__ModuleLoader__.load({
1523
1834
  baseUrlPlaceholder: 'https://api.deepseek.com/v1', modelPlaceholder: 'deepseek-chat', keyPlaceholder: 'sk-...',
1524
1835
  }),
1525
1836
  h(MineruCard, null),
1837
+ h(ThemeCard, null),
1526
1838
  h(SyncScrollCard, null),
1527
1839
  )
1528
1840
  }
@@ -1633,7 +1945,9 @@ window.__ModuleLoader__.load({
1633
1945
  }
1634
1946
 
1635
1947
  return {
1636
- inject: ['slots', 'locale', 'layout', 'uiWorkspace', 'sidebarRight', 'sidebarRightTabs'],
1948
+ // 'theme' = 官方 dsh 主题服务(ctx.theme.getTheme() / ctx.on('theme/change'))。
1949
+ // 注入是可选的:拿不到时阅读器仍按「宿主属性 + prefers-color-scheme」自己判(方案 §A2.2 的降级链)。
1950
+ inject: ['slots', 'locale', 'layout', 'uiWorkspace', 'sidebarRight', 'sidebarRightTabs', 'theme'],
1637
1951
  apply(ctx) {
1638
1952
  try {
1639
1953
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-paper-reader: dicts')
@@ -1678,6 +1992,24 @@ window.__ModuleLoader__.load({
1678
1992
 
1679
1993
  clientApi = { slots: ctx.slots, layout: ctx.layout, uiWorkspace: ctx.uiWorkspace, sidebarRight: ctx.sidebarRight }
1680
1994
 
1995
+ /* 深色模式:把 dsh 的主题**权威地**推给阅读器(方案 §A2.2 实装方式 1)。
1996
+ 三处都包在 try 里:旧版 dsh 没有 theme 服务时,阅读器的四级降级链仍然工作,
1997
+ 深色能力不会因为宿主缺接口而整体失灵(也绝不因此让 apply() 抛错)。 */
1998
+ try {
1999
+ const readHostTheme = () => {
2000
+ try {
2001
+ const snap = ctx.theme?.getTheme?.()
2002
+ const scheme = snap?.active?.colorScheme
2003
+ if (scheme === 'dark' || scheme === 'light') dprHostDark = scheme === 'dark'
2004
+ } catch { /* 保守:保持上一个值 / 默认亮色 */ }
2005
+ }
2006
+ readHostTheme()
2007
+ ctx.effect(() => {
2008
+ const off = ctx.on?.('theme/change', () => { readHostTheme(); pushThemeToReader() })
2009
+ return () => { try { off?.() } catch { /* 已释放 */ } }
2010
+ }, 'dsh-paper-reader: theme bridge')
2011
+ } catch { /* 宿主无 theme 服务:降级链接管 */ }
2012
+
1681
2013
  // 阅读器跳转链接拦截(capture 阶段,一次绑定):渲染器给 http(s) 链接加了
1682
2014
  // target=_blank,不拦会新开浏览器标签页 —— 拦下后交给应用内跳转
1683
2015
  if (!window.__dprJumpLinkBound) {