@li-canghai/dsh-paper 0.8.1 → 0.8.3

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 (43) hide show
  1. package/README.md +42 -93
  2. package/THIRD_PARTY_NOTICES.md +69 -0
  3. package/lib/annotate-tool.js +58 -10
  4. package/lib/block-cache.js +45 -26
  5. package/lib/blocks-reconcile.js +56 -17
  6. package/lib/client-parts/01-pure-helpers.js +410 -7
  7. package/lib/client-parts/02-author-year.js +111 -24
  8. package/lib/client-parts/03-pdf-stack.js +97 -0
  9. package/lib/client.js +1022 -112
  10. package/lib/code-source.js +8 -8
  11. package/lib/discussion.js +2 -101
  12. package/lib/export.js +228 -14
  13. package/lib/file-lock.js +128 -16
  14. package/lib/gloss.js +1030 -12
  15. package/lib/index.js +193 -68
  16. package/lib/inline-html.js +1 -1
  17. package/lib/item-ops.js +14 -2
  18. package/lib/library-service.js +32 -8
  19. package/lib/library-tool.js +6 -0
  20. package/lib/metadata-enrichment.js +8 -1
  21. package/lib/pdf-analysis-tool.js +72 -0
  22. package/lib/pdf-page.js +609 -13
  23. package/lib/picker.js +19 -5
  24. package/lib/reader-store.js +14 -10
  25. package/lib/rename-document.js +25 -3
  26. package/lib/search-index.js +0 -9
  27. package/lib/selection-message.js +2 -3
  28. package/lib/storage.js +122 -10
  29. package/lib/store-paths.js +0 -13
  30. package/lib/table-gfm.js +42 -14
  31. package/lib/tex-fetch.js +0 -1
  32. package/lib/tex-merge.js +0 -1
  33. package/lib/tex-prepare.js +74 -13
  34. package/lib/text-similarity.js +0 -9
  35. package/lib/tool-host.js +4 -1
  36. package/lib/translate-prompts.js +11 -1
  37. package/lib/translate-queue.js +1 -34
  38. package/lib/translate-task.js +1 -1
  39. package/lib/translate.js +57 -26
  40. package/lib/update-contracts.js +5 -5
  41. package/locale/en.json +6 -0
  42. package/locale/zh.json +6 -0
  43. package/package.json +7 -2
package/lib/client.js CHANGED
@@ -196,6 +196,22 @@ function createLibraryModel() {
196
196
  return jobKindOf(job) === JOB_KINDS.translate ? '翻译' : '解析'
197
197
  }
198
198
 
199
+ // 卡片副标题:失败/中断时给原因,在跑时给「后台处理中」,并在有任务编号时把它露出来。
200
+ //
201
+ // 🔴 为什么要把编号显示给用户:模型回执里给的是**任务编号**,用户拿着它去问
202
+ // 「那批解析到哪了」时,得有个地方能看见同一个编号 —— 否则那个编号只存在于
203
+ // 聊天记录里,和面板对不上。翻译任务没有编号(不进任务清单),所以只加在解析卡片上。
204
+ function jobMetaText(job) {
205
+ const reason = typeof job?.error === 'string' && job.error !== ''
206
+ ? job.error
207
+ : (jobKindOf(job) === JOB_KINDS.translate ? '后台翻译中' : '后台处理中')
208
+ // 只有解析任务进任务清单,翻译任务的编号即使被塞进来也不显示 —— 那个编号查不到东西。
209
+ const taskId = jobKindOf(job) === JOB_KINDS.parse && typeof job?.taskId === 'string' && job.taskId !== ''
210
+ ? job.taskId
211
+ : ''
212
+ return taskId === '' ? reason : reason + ' · 编号 ' + taskId
213
+ }
214
+
199
215
  // 一条翻译任务当前能做什么。纯函数,单测直接断言。
200
216
  //
201
217
  // 翻译是远程模型调用、有成本,所以按钮比解析那边收敛:
@@ -549,9 +565,19 @@ function createLibraryModel() {
549
565
  }
550
566
  const payload = readerPayloadOf(block, sourceText, id)
551
567
  // 参考文献块自己**就是**跳转目标:它的 [7] 指向自己,标出来只会让人点了个原地不动。
552
- const parts = payload.markdown === true && row.kind !== 'references'
553
- ? inlineRefs(sourceText, numbers).map((part, at) => inlinePart(part, index, at))
554
- : []
568
+ //
569
+ // 🔴 **编号制没认出任何标记时才走作者-年份制**,判据是「有没有非 text 片段」而不是
570
+ // 「数组是不是空的」:没有编号的段落,inlineRefs 返回的是 `[{type:'text', …}]` ——
571
+ // 数组非空,但一个标记都没有。早先按长度判,于是作者-年份那一路在生产路径上**永远
572
+ // 不执行**:测试直接调 inlineAuthors 所以一直是绿的,界面上却怎么点都没反应。
573
+ let parts = []
574
+ if (payload.markdown === true && row.kind !== 'references') {
575
+ const numbered = inlineRefs(sourceText, numbers)
576
+ const cited = numbered.some(part => part.type !== 'text')
577
+ ? numbered
578
+ : inlineAuthors(sourceText, numbers?.authorYears)
579
+ parts = cited.map((part, at) => inlinePart(part, index, at))
580
+ }
555
581
  row.inline = { parts, source: parts.length > 0 ? sourceText : '' }
556
582
  row.zhText = translated.text
557
583
  row.zhRaw = translated.raw
@@ -591,9 +617,14 @@ function createLibraryModel() {
591
617
  value: part.value ?? '',
592
618
  text: part.text ?? '',
593
619
  }
594
- // 单编号不带这两项时**不补空值**:既有断言按字段全等,多一个 raw: undefined 也会红。
620
+ // 不带的字段**不补空值**:既有断言按字段全等,多一个 raw: undefined 也会红。
595
621
  if (part.raw !== undefined) shape.raw = part.raw
596
622
  if (part.items !== undefined) shape.items = part.items
623
+ // 🔴 作者-年份制靠这两项才能落到 DOM 上:paintCiteSpans 把它们写成 data-cite-surname /
624
+ // data-cite-year,showCite 再用这对键查浮层。丢了就只有标记没有内容 —— 悬停毫无反应,
625
+ // 而且不报错。与 raw/items 被丢是同一类问题,只是那一次丢的是编号制。
626
+ if (part.surname !== undefined) shape.surname = part.surname
627
+ if (part.year !== undefined) shape.year = part.year
597
628
  return shape
598
629
  }
599
630
 
@@ -794,6 +825,19 @@ function createLibraryModel() {
794
825
  }
795
826
  }
796
827
 
828
+ /**
829
+ * 一个块在某一页上的**完整正文**(所有 part 合起来)。
830
+ *
831
+ * 🔴 块可能被拆成多段 DOM(见宿主 pdf-page.js 的 splitRuns),但划线校验、
832
+ * 高亮定位、引用识别都按**整块**做 —— 只取第一段会漏掉被图或公式隔开的另一半。
833
+ * 与宿主 pdfBlockText 同口径:有 fullText 就用它,否则把各段拼起来。
834
+ */
835
+ function pdfBlockTextOf(groups, blockId) {
836
+ const parts = (Array.isArray(groups) ? groups : []).filter(group => group?.id === blockId)
837
+ if (parts.length === 0) return ''
838
+ return parts[0].fullText ?? parts.map(part => part.text).join(' ')
839
+ }
840
+
797
841
  /**
798
842
  * 将 PDFium 原生字符的每个起点转换成浏览器可渲染的字符推进宽度。
799
843
  * 单词字体、字重、连字均不可假定等于浏览器 serif,所以不能再让
@@ -1157,6 +1201,218 @@ function createLibraryModel() {
1157
1201
  * 相反,译文上划的线(offset = -1)照样能在 zhText 里精确定位。围栏内容整段跳过 ——
1158
1202
  * 高亮 Range 落进代码块没有视觉语义,还会把行号 / 高亮会话搅乱。
1159
1203
  */
1204
+ /** 空白字符集:行接缝的补空格、软连字符、零宽字符。与宿主 pdfQuoteInText 同口径。 */
1205
+ const spaceRun = () => /[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu
1206
+ /** 单个字符是不是空白(含软连字符、零宽字符)。逐字符判断,不碰正则状态。 */
1207
+ const isSpaceChar = ch => ch === undefined || /[\s\u00ad\u200b\u200c\u200d\ufeff]/.test(ch)
1208
+
1209
+ /**
1210
+ * 忽略空白地在一段文本里定位原话,返回在**原文本**里的起止下标。
1211
+ *
1212
+ * 🔴 为什么绘制侧也需要它:PDF 档的文字层是逐词、逐字符的 span 拼出来的,行与行之间
1213
+ * **一个分隔符都没有**(每行是 display:block 的绝对定位元素),而 mark.quote 来自服务端
1214
+ * 的 group.text —— 那份在**行接缝补一个空格**。于是同一次拖选在两侧差着几个空格:
1215
+ * 实测 ResNet 第 2 页 `…problem by introducing…`(702 字)对 `…problem byintroducing…`
1216
+ * (693 字),`display.indexOf(quote)` 必然落空,划线画不出来。
1217
+ *
1218
+ * 做法:把两侧的空白都去掉再找,然后用一张「去空白后的下标 → 原文本下标」的表把结果
1219
+ * 换算回去。区间两端向外吸附到完整词元,避免高亮停在半个词上。
1220
+ *
1221
+ * @param {string} text 屏上显示文本(原样,含它自己的空白)
1222
+ * @param {string} quote 原话(可能带另一种空白)
1223
+ * @returns {{start: number, end: number}|null} 原文本里的区间;对不上返回 null
1224
+ */
1225
+ function locateQuoteIgnoringSpace(text, quote) {
1226
+ if (text === '' || quote === '') return null
1227
+ // squeezed 去掉空白,index 记录每个保留字符在原文本里的下标。
1228
+ let squeezed = ''
1229
+ const index = []
1230
+ for (let at = 0; at < text.length; at++) {
1231
+ if (isSpaceChar(text[at])) continue
1232
+ squeezed += text[at]
1233
+ index.push(at)
1234
+ }
1235
+ const target = quote.replace(spaceRun(), '')
1236
+ if (target === '' || squeezed === '') return null
1237
+ const hit = squeezed.indexOf(target)
1238
+ if (hit < 0) return null
1239
+ const start = index[hit]
1240
+ const end = index[hit + target.length - 1] + 1
1241
+ return { start, end }
1242
+ }
1243
+
1244
+ /** 行内公式的源码形态:`$…$`(不跨行)。两端锚定量词,避免跨段乱匹配。 */
1245
+ const formulaSource = () => /(\$[^$\n]+\$)/g
1246
+
1247
+ /**
1248
+ * 把原话按**行内公式**切成「文字段 / 公式段」,再把公式当**通配**去匹配显示文本。
1249
+ *
1250
+ * 🔴 为什么要这样:同一条划线在两侧的文字形态不同,公式是其中唯一的硬分界。
1251
+ * · 原文栏的显示文本里,公式是 KaTeX 渲染物被 {@link formulaSelectionText} 换回的
1252
+ * **LaTeX 源码**(`$\mathcal{H}(\mathbf{x})$`);
1253
+ * · PDF 档的显示文本里,公式是**渲染后的字形**(`H(x)`);
1254
+ * · 两边的**普通文字**逐字相同(只差空白)。
1255
+ *
1256
+ * 实测 ResNet 第 2 页 `p2-p2`:原话来自 PDF 字形,含 `H(x)`;原文栏那份是
1257
+ * `$\mathcal{H}(\mathbf{x})$`。整串逐字对不上,但公式**之间**的文字段四段全中
1258
+ * (0 / 254 / 316 / 353)。所以只要认定「这一段是公式」,两侧就能对齐 ——
1259
+ * 不必去猜公式该渲染成什么。
1260
+ *
1261
+ * 用户裁定:公式是**原子单位**——选区碰到公式的任何一部分,整个公式一起高亮。
1262
+ * 通配区间的两端就落在公式边界上,天然满足这条。
1263
+ *
1264
+ * @param {string} text 屏上显示文本(原样)
1265
+ * @param {string} quote 原话(公式是 `$…$` 源码形态)
1266
+ * @returns {{start: number, end: number}|null} 显示文本里的区间;对不上返回 null
1267
+ */
1268
+ /** 去掉空白,同时留一张「压缩下标 → 原文下标」的表。 */
1269
+ function squeezeWithIndex(text) {
1270
+ let squeezed = ''
1271
+ const index = []
1272
+ for (let at = 0; at < text.length; at++) {
1273
+ if (isSpaceChar(text[at])) continue
1274
+ squeezed += text[at]
1275
+ index.push(at)
1276
+ }
1277
+ return { squeezed, index }
1278
+ }
1279
+
1280
+ /**
1281
+ * 按 `$…$` 把一段文字切成「文字段 / 公式段」,返回**文字段**(公式段为 null)。
1282
+ * 奇数下标是公式。没有公式时返回 null —— 调用方据此判断这一侧能不能当模板。
1283
+ */
1284
+ function formulaSplit(text) {
1285
+ const pattern = formulaSource()
1286
+ if (!pattern.test(text)) return null
1287
+ // 🔴 正则**必须带捕获组**:String.split 在没有捕获组时会把分隔符整个丢掉,
1288
+ // 返回的只是文字段(['A ', ' B ', ' C']),公式位置根本没占位。
1289
+ // 旧实现用 map((p, i) => i % 2 === 0 ? p : null) 于是把下标 1 的**真文字**判成公式、
1290
+ // 三处公式全部丢失 —— 实测把 7 段切成 4 段,所有跨公式的划线定位失败。
1291
+ // 带捕获组后 split 返回 [文字, 公式, 文字, 公式, …],奇数位才是公式。
1292
+ return text.split(formulaSource()).map((piece, at) => at % 2 === 1 ? null : piece)
1293
+ }
1294
+
1295
+ /**
1296
+ * 一侧含行内公式、另一侧不含时,把**含公式的那侧**当模板切段,另一侧逐段定位。
1297
+ *
1298
+ * 🔴 方向是**双向**的,实测两种都真实存在:
1299
+ * · 划线取自 PDF 档 —— quote 是字形 `H(x)`(无 `$…$`),原文栏的 display 是
1300
+ * LaTeX 源码(3 处 `$…$`)。此时模板是 display。
1301
+ * · 划线取自原文栏 —— quote 带 `$…$` 源码,PDF 档的 display 是字形。此时模板是 quote。
1302
+ *
1303
+ * 先把模板的公式段换成通配,再用公式**之间**的文字段去另一侧依次定位;两侧都在
1304
+ * 压缩坐标(去空白)里走,最后换算回**目标文本**的原下标。
1305
+ *
1306
+ * 公式是原子单位(用户裁定):通配区间横跨整个公式,选区碰到哪一部分都整块高亮。
1307
+ *
1308
+ * @param {string} text 屏上显示文本(定位目标)
1309
+ * @param {string} quote 原话
1310
+ * @returns {{start: number, end: number}|null} 目标文本里的区间;对不上返回 null
1311
+ */
1312
+ function locateQuoteAcrossFormulas(text, quote) {
1313
+ if (text === '' || quote === '') return null
1314
+ const target = squeezeWithIndex(text)
1315
+ if (target.squeezed === '') return null
1316
+ // 两侧是否含 $…$。含公式的那一侧当**模板**切段,另一侧当**定位目标**。
1317
+ const quoteParts = formulaSplit(quote)
1318
+ const textParts = formulaSplit(text)
1319
+ if (quoteParts === null && textParts === null) return null
1320
+ const isText = piece => typeof piece === 'string' && piece !== ''
1321
+ const textPiecesOf = parts => parts.map(piece => piece === null ? null : piece.replace(spaceRun(), ''))
1322
+
1323
+ /**
1324
+ * 在 needle 里依次找 template 的各个文字段,返回覆盖到的**压缩坐标**区间。
1325
+ * 公式位不推进 —— 它只表示"这里跳过任意内容"。
1326
+ */
1327
+ const align = (needle, template) => {
1328
+ const wanted = textPiecesOf(template)
1329
+ const first = wanted.findIndex(isText)
1330
+ const last = wanted.length - 1 - [...wanted].reverse().findIndex(isText)
1331
+ if (first < 0) return null
1332
+ let cursor = needle.squeezed.indexOf(wanted[first])
1333
+ if (cursor < 0) return null
1334
+ const startAt = cursor
1335
+ cursor += wanted[first].length
1336
+ let endAt = cursor
1337
+ for (let at = first + 1; at <= last; at += 1) {
1338
+ const piece = wanted[at]
1339
+ if (piece === null) continue
1340
+ const found = needle.squeezed.indexOf(piece, cursor)
1341
+ if (found < 0) return null
1342
+ cursor = found + piece.length
1343
+ endAt = cursor
1344
+ }
1345
+ return { startAt, endAt }
1346
+ }
1347
+
1348
+ // 🔴 两种情形方向相反,必须分开写 —— 混用会让区间落在错误的坐标系上。
1349
+ let from
1350
+ let to
1351
+ if (textParts !== null && quoteParts === null) {
1352
+ // ① display 含公式、quote 不含(划线取自 PDF 档)。
1353
+ // quote 那侧的文字就是 display 文字段压缩后来的一份,先在 quote 里确认
1354
+ // 「这条划线覆盖到 display 的第几段」——对不上就说明不是同一段文字。
1355
+ const quoteTarget = squeezeWithIndex(quote)
1356
+ if (align(quoteTarget, textParts) === null) return null
1357
+ // 🔴 区间取 **display 自己**的范围:从第一段文字的开头到最后一段文字的结尾。
1358
+ // 中间那些公式段原样落在区间里,天然被整块包住 —— 这正是「公式是原子」
1359
+ // 要的效果,也不需要任何坐标换算(换算过一次,两次都算错)。
1360
+ // 带捕获组的 split 直接给出 [文字, 公式源码, 文字, …],按真实长度累加即可 ——
1361
+ // 不需要再猜公式段有多长。
1362
+ const shape = text.split(formulaSource())
1363
+ const isTextSeg = (piece, at) => at % 2 === 0 && piece !== ''
1364
+ const firstIdx = shape.findIndex(isTextSeg)
1365
+ const lastIdx = shape.length - 1 - [...shape].reverse().findIndex(isTextSeg)
1366
+ if (firstIdx < 0 || lastIdx < firstIdx) return null
1367
+ let cursorAt = 0
1368
+ let startPx = -1
1369
+ let endPx = -1
1370
+ for (let at = 0; at < shape.length; at += 1) {
1371
+ if (at === firstIdx) startPx = cursorAt
1372
+ cursorAt += shape[at].length
1373
+ if (at === lastIdx) { endPx = cursorAt; break }
1374
+ }
1375
+ if (startPx < 0 || endPx <= startPx) return null
1376
+ from = startPx
1377
+ to = endPx
1378
+ } else if (quoteParts !== null && textParts === null) {
1379
+ // ② quote 含公式、display 不含(划线取自原文栏)。
1380
+ // 用 quote 的文字段去 **display** 里定位,直接得到 display 区间。
1381
+ const hit = align(target, quoteParts)
1382
+ if (hit === null) return null
1383
+ from = target.index[hit.startAt]
1384
+ to = target.index[hit.endAt - 1] + 1
1385
+ // 🔴 划线**以公式开头/结尾**时,那个公式在 display 里是 KaTeX 渲染后的纯文本
1386
+ // (没有 `$…$`),所以 align 只能从公式**之后**的那段文字起算 —— 起点于是落在
1387
+ // 公式右边,公式本身永远进不了区间。实测 ResNet p2-p3:整段划线以
1388
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 开头,区间被算成 `[40,228)`,公式被排除在外。
1389
+ // 判据是模板的**首/尾段为空串**:空 = 划线是从那个公式开始的(结束的)。
1390
+ // 把区间扩到 display 的对应端点 —— 不猜长度,只是把「公式被当成光标位置」补回来。
1391
+ if (quoteParts[0] === '') from = 0
1392
+ if (quoteParts[quoteParts.length - 1] === '') to = text.length
1393
+ } else {
1394
+ return null
1395
+ }
1396
+ if (!(to > from)) return null
1397
+ // 🔴 **公式原子化**(用户裁定):选区碰到公式的任何一部分,整个公式一起高亮。
1398
+ for (let guard = 0; guard < 32; guard += 1) {
1399
+ let grown = false
1400
+ // 🔴 正则**必须在循环外建一次**:每次 new 一个带 g 的正则,lastIndex 永远从 0 起,
1401
+ // exec 每次都返回第一个匹配 —— 这是死循环(实测把测试跑成超时、日志 0 字节)。
1402
+ const pattern = formulaSource()
1403
+ let hit
1404
+ while ((hit = pattern.exec(text)) !== null) {
1405
+ const formulaFrom = hit.index
1406
+ const formulaTo = hit.index + hit[0].length
1407
+ if (!(formulaFrom < to && formulaTo > from)) continue
1408
+ if (formulaFrom < from) { from = formulaFrom; grown = true }
1409
+ if (formulaTo > to) { to = formulaTo; grown = true }
1410
+ }
1411
+ if (!grown) break
1412
+ }
1413
+ return { start: from, end: to }
1414
+ }
1415
+
1160
1416
  function quoteSpanPlan(mark, text) {
1161
1417
  if (mark === null || typeof mark !== 'object' || mark.anchor !== 'exact') return null
1162
1418
  const display = typeof text === 'string' ? text : ''
@@ -1169,7 +1425,22 @@ function createLibraryModel() {
1169
1425
  const at = locateQuoteInText(display, candidate, prefix, suffix)
1170
1426
  if (at >= 0) return { quote: candidate, start: at, end: at + candidate.length }
1171
1427
  }
1172
- // 🔴 逐字都对不上再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1428
+ // 🔴 逐字对不上先试**忽略空白**:PDF 文字层的行接缝没有分隔符,而原话那份有空格,
1429
+ // 同一次拖选两侧差着几个空格。这一步只放宽空白,别的字仍然要逐字对上。
1430
+ for (const candidate of quoteCandidates(quote)) {
1431
+ const span = locateQuoteIgnoringSpace(display, candidate)
1432
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1433
+ }
1434
+ // 🔴 再试**公式通配**:同一条划线在两侧的文字形态不同 —— 原文栏把公式还原成 LaTeX
1435
+ // 源码($\mathcal{H}(\mathbf{x})$),PDF 档是渲染后的字形(H(x))。公式之间的普通文字
1436
+ // 逐字相同,所以只认「这一段是公式」、把它当通配,两侧就能对齐(见
1437
+ // {@link locateQuoteAcrossFormulas})。用户裁定公式是**原子单位**:选区碰到哪一部分,
1438
+ // 整个公式一起高亮。
1439
+ for (const candidate of quoteCandidates(quote)) {
1440
+ const span = locateQuoteAcrossFormulas(display, candidate)
1441
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1442
+ }
1443
+ // 🔴 再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1173
1444
  // 只有**长原话**才走这一步 —— 短原话的首尾两截谁都能对上,夹出来的区间没有意义。
1174
1445
  for (const candidate of quoteCandidates(quote)) {
1175
1446
  const span = bracketSpan(display, candidate)
@@ -1575,13 +1846,46 @@ function createLibraryModel() {
1575
1846
  const range = new Range()
1576
1847
  if (!locate(row.node, target.start, false, range) || !locate(row.node, target.end, true, range)) continue
1577
1848
  const got = range.toString()
1578
- if (!got || (direct ? got !== direct.quote : got.trim() !== got)) continue
1849
+ // 🔴 终验:**普通文字逐字相等**;含公式时按 {@link formulaSelectionText} 的口径比。
1850
+ //
1851
+ // KaTeX 把公式摊成「TeX 源码 + 渲染字形」留在 textContent 里(实测
1852
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 是 34 字源码 + 5 字字形),与 `$…$` 形态的
1853
+ // quote 永远不可能逐字相等。用严格相等的话,凡覆盖公式的划线都被这道终验拒掉 ——
1854
+ // 实测区间已算对(`[0,228)` 覆盖公式)却 `painted = 0`,整条划线一个字都不画。
1855
+ // 折符号也**不行**(实测折完 190 vs 184:`\mathcal`/`\mathbf` 的命令名留在 DOM 里,
1856
+ // 而 quote 那侧只有符号)—— 唯一正确的口径是把公式还原成 `$…$` 再比。
1857
+ const matches = () => {
1858
+ if (!got) return false
1859
+ if (!direct) return got.trim() === got
1860
+ if (got === direct.quote) return true
1861
+ if (!formulaSource().test(direct.quote) && !formulaSource().test(got)) return false
1862
+ const contents = range.cloneContents?.()
1863
+ if (!contents) return false
1864
+ return formulaSelectionText(contents).trim() === direct.quote.trim()
1865
+ }
1866
+ if (!matches()) continue
1579
1867
  const name = 'dsh-paper-mark-' + color
1580
1868
  let entry = names.get(name)
1581
1869
  if (!entry) { entry = { ranges: [], hits: [] }; names.set(name, entry) }
1582
1870
  entry.ranges.push(range)
1583
1871
  entry.hits ??= []
1584
1872
  entry.hits.push({ range, markId: mark.id })
1873
+ // 🔴 **公式整块上色**(用户裁定:公式是原子单位,选区碰到哪一部分都整块亮)。
1874
+ //
1875
+ // KaTeX 把一个公式渲染成两条臂:`.katex-mathml`(`annotation` 里的 TeX 源码,
1876
+ // 被 clip 成 1×1 摆在屏幕外)与 `.katex-html`(真正看得见的字形)。实测
1877
+ // ResNet p2-p3 的 `$\mathcal{F}(\mathbf{x})+\mathbf{x}$`:mathml 臂占 34 个字符、
1878
+ // html 臂只有 5 个(`F(x)+x`)。划线的区间按 DOM 字符算,**整段都落在 mathml 臂上**,
1879
+ // 于是浏览器把颜色涂在那 1×1 的不可见区域 —— 用户看到的就是「公式没高亮」。
1880
+ //
1881
+ // 补法:凡区间碰到的 `.katex`,另给它的 `.katex-html` 加一条整块 Range。
1882
+ // 与 PDF 档 `pdfQuoteInText` 的口径一致,也不动定位逻辑一个字。
1883
+ for (const formula of katexArmsIn(row.node, range)) {
1884
+ const arm = new Range()
1885
+ arm.selectNodeContents(formula)
1886
+ entry.ranges.push(arm)
1887
+ entry.hits.push({ range: arm, markId: mark.id })
1888
+ }
1585
1889
  painted += 1
1586
1890
  completed.set(row.node, completed.get(row.node) + 1)
1587
1891
  }
@@ -1595,6 +1899,31 @@ function createLibraryModel() {
1595
1899
  return painted
1596
1900
  }
1597
1901
 
1902
+ /**
1903
+ * 一段 Range 碰到的所有 KaTeX 公式,返回各自**可见臂**(`.katex-html`)的根节点。
1904
+ *
1905
+ * 🔴 KaTeX 的 `.katex` 里有两条臂:`.katex-mathml`(无障碍树,TeX 源码,被 clip 成
1906
+ * 1×1 摆在屏幕外)与 `.katex-html`(可见字形)。划线的区间按 DOM 字符算,落在
1907
+ * mathml 臂上时浏览器会把颜色涂在那不可见的 1×1 区域 —— 用户看到「公式没高亮」。
1908
+ * 这里把碰到的公式找出来,交给调用方补一条覆盖可见臂的 Range(公式整块上色)。
1909
+ *
1910
+ * @param {unknown} node 块节点
1911
+ * @param {Range} range 已定位好的区间
1912
+ * @returns {Element[]} 可见臂节点(不可用的公式跳过)
1913
+ */
1914
+ function katexArmsIn(node, range) {
1915
+ const formulas = typeof node?.querySelectorAll === 'function' ? node.querySelectorAll('.katex') : []
1916
+ const arms = []
1917
+ for (const formula of formulas) {
1918
+ const arm = typeof formula?.querySelector === 'function' ? formula.querySelector('.katex-html') : null
1919
+ if (!arm) continue
1920
+ // 只要区间**碰到**这个公式就整块亮(用户裁定:公式是原子单位)。
1921
+ let touches = true
1922
+ try { touches = typeof range?.intersectsNode === 'function' ? range.intersectsNode(formula) : true } catch { touches = true }
1923
+ if (touches) arms.push(arm)
1924
+ }
1925
+ return arms
1926
+ }
1598
1927
  // KaTeX 同时包含无障碍树与可视树。克隆后用公式源码替换,避免把两份文字一起引用。
1599
1928
  function formulaSelectionText(node) {
1600
1929
  const clone = node.cloneNode(true)
@@ -1761,6 +2090,33 @@ function createLibraryModel() {
1761
2090
  }
1762
2091
  }
1763
2092
 
2093
+ /**
2094
+ * 图注这类**纯文本块**里出现的行内公式:只把 `$…$` 那几段交给渲染器,其余照旧字面显示。
2095
+ *
2096
+ * 🔴 为什么图注不走整段 Markdown(见 readerBlockNode):图注不成文,整段过 Markdown 会让
2097
+ * 下划线变斜体、星号变强调("Figure 3 * p<0.05" 会被吃掉一半)。但**同时**图注里确实
2098
+ * 夹着公式 —— 实测 STITCH 的 Figure 2 图注是
2099
+ * `Thematic Scope $( \sigma _ { t } ) .$`,纯文本渲染的结果就是满屏的 `$(\sigma_{t})$`。
2100
+ * 所以按**公式边界**切开:公式段原样送进 MarkdownText(KaTeX 会渲染它),文字段照旧
2101
+ * 按纯文本显示。既保住了「图注不做强调解析」,也让公式真的排出来。
2102
+ *
2103
+ * @param {unknown} value 图注原文
2104
+ * @returns {Array<{text: string, math: boolean}>} 按顺序切出的片段;没有公式时只有一片
2105
+ */
2106
+ function captionPieces(value) {
2107
+ const text = String(value ?? '')
2108
+ const formula = /\$\$[\s\S]+?\$\$|\$(?!\s)[^$\n]+?\$/g
2109
+ const pieces = []
2110
+ let at = 0
2111
+ for (const match of text.matchAll(formula)) {
2112
+ if (match.index > at) pieces.push({ text: text.slice(at, match.index), math: false })
2113
+ pieces.push({ text: match[0], math: true })
2114
+ at = match.index + match[0].length
2115
+ }
2116
+ if (at < text.length) pieces.push({ text: text.slice(at), math: false })
2117
+ return pieces.length === 0 ? [{ text, math: false }] : pieces
2118
+ }
2119
+
1764
2120
  function renderSelectionText(value) {
1765
2121
  const text = String(value ?? '')
1766
2122
  const formula = /\$\$[\s\S]+?\$\$|\$(?!\s)[^$\n]+?\$/g
@@ -1892,7 +2248,7 @@ function createLibraryModel() {
1892
2248
  * 只脱**行内排版**标签的壳、保留里面的文字。用白名单而不是「把所有尖括号都删掉」:
1893
2249
  * markdown 的自动链接写作尖括号包 URL,把尖括号一律当标签会把链接吃掉。
1894
2250
  */
1895
- const INLINE_TAG_RE = /<\/?\s*(?:sup|sub|i|em|b|strong|u|s|del|ins|mark|small|big|tt|code|abbr|cite|q|span|font)(?:\s[^<>]*)?\s*\/?>/gi
2251
+ const INLINE_TAG_RE = /<\/?\s*(?:sup|sub|i|em|b|strong|u|s|del|ins|mark|small|big|tt|code|abbr|cite|q|span|font)(?:\s+[a-z-]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))*\s*\/?>/gi
1896
2252
  const mapChars = (value, table) => Array.from(String(value), ch => table[ch] ?? ch).join('')
1897
2253
  /**
1898
2254
  * 把正文里的行内 HTML 换成等价的可读字符(D150)。
@@ -2598,6 +2954,53 @@ function createLibraryModel() {
2598
2954
  + '&page=' + encodeURIComponent(String(page)) + '&width=' + width + (crop ? '&crop=1' : '')
2599
2955
  }
2600
2956
 
2957
+ /**
2958
+ * 字形宽度的测量缓存(连续滚动的性能关键之一)。
2959
+ *
2960
+ * 🔴 **为什么必须缓存**:逐字符对齐要对每个字符调一次 `canvas.measureText`。
2961
+ * 真实论文实测:一篇 9 页的论文共 16,491 个字符 —— 每页一万六千次**同步**测量。
2962
+ * 单页时代这样建一次还能接受;连续滚动下窗口里同时挂三页,一次重建就是近五万次
2963
+ * `measureText`,那是主线程直接卡住半秒的量级(滚轮会一顿一顿)。
2964
+ *
2965
+ * 🔴 **为什么缓存有效率极高**:同一篇论文里出现的不同字符只有 85 个,字号虽随行高
2966
+ * 浮动,但量化到 0.1px 之后只有二十来档 —— 去重上界约 2,000 次,比逐次测量省 88%。
2967
+ * 字体固定是 serif(与 CSS 的 `.paper-pdf-word` 一致),所以"同一字号 + 同一字串"
2968
+ * 的宽度是确定的,缓存不会失真。
2969
+ *
2970
+ * 量化到 0.1px 是刻意的:字号算出来是浮点(行高 × 页高 / 1000),不量化则几乎每个
2971
+ * 词的 key 都不同,缓存命中率会掉到接近 0。0.1px 的差异在屏幕上不可见,而选区宽度
2972
+ * 只由 `letter-spacing` 的**差值**决定,缩放时也不会累积误差。
2973
+ */
2974
+ const glyphWidthCache = new Map()
2975
+ /** 缓存上界:一篇论文 85 个字符 × 三十档字号也到不了 5,000,超了说明用法出问题了。 */
2976
+ const GLYPH_CACHE_LIMIT = 5000
2977
+ /**
2978
+ * 量一个字符串在某个字号下的宽度(带缓存)。
2979
+ *
2980
+ * @param {CanvasRenderingContext2D|null} context 测量用的 2d 上下文
2981
+ * @param {number} size 字号(px)
2982
+ * @param {string} text 要量的字串
2983
+ * @returns {number|null} 宽度;上下文不可用是 null(调用方据此跳过对齐,不编一个宽度)
2984
+ */
2985
+ function glyphWidthOf(context, size, text) {
2986
+ if (context === null || context === undefined) return null
2987
+ const pixels = Number(size)
2988
+ if (!Number.isFinite(pixels) || pixels <= 0) return null
2989
+ // 量化到 0.1px —— 不量化则每个词的 key 都不同,缓存等于没有(见上面的说明)。
2990
+ const quantized = Math.round(pixels * 10) / 10
2991
+ const key = quantized + '|' + text
2992
+ const hit = glyphWidthCache.get(key)
2993
+ if (hit !== undefined) return hit
2994
+ context.font = quantized + 'px serif'
2995
+ const measured = context.measureText(text).width
2996
+ if (!Number.isFinite(measured)) return null
2997
+ // 满了就整片清掉而不是逐条淘汰:条目本身很便宜(数字 + 短串),
2998
+ // 而一篇论文的字符集是稳定的,清掉之后下一轮的命中率依然高。
2999
+ if (glyphWidthCache.size >= GLYPH_CACHE_LIMIT) glyphWidthCache.clear()
3000
+ glyphWidthCache.set(key, measured)
3001
+ return measured
3002
+ }
3003
+
2601
3004
  /**
2602
3005
  * bbox(0–1000 归一化坐标) → overlay 的百分比样式。
2603
3006
  *
@@ -2916,16 +3319,31 @@ function createLibraryModel() {
2916
3319
  // 🔴 与编号制最大的差别是**没有唯一键**。"姓氏 + 年份"在 AI 领域经常撞车(同一作者同年
2917
3320
  // 多篇),所以索引是一对多:命中几条就全列,由读者自己判断。宁可显示两条让人选,也不要
2918
3321
  // 挑一条赌对 —— 猜错时读者无从知道错。
2919
- /** `(Surname et al., 2020)` / `(Surname & Other, 2020)` / `(Surname, 2020)`。 */
2920
- const AUTHOR_YEAR =
2921
- /\(\s*([\p{Lu}][\p{L}'-]+)(?:\s+et\s+al\.?|\s*(?:&|and)\s*[\p{Lu}][\p{L}'-]+)?\s*,\s*(\d{4})[a-z]?\s*\)/gu
2922
- // 🔴 三个正则都**必须带 u flag**:`\p{Lu}` / `\p{L}` 是 Unicode 属性转义,没有 u 时
3322
+ //
3323
+ // 🔴 参考文献有**两种排版**,两种都得认(实测一篇 AAAI 式论文 27 条全灭):
3324
+ // · CS 式 `Zhang, Y. Title. 2020.` —— 姓在前,后面跟逗号
3325
+ // · AAAI 式 `Parth Sarthi, Salman Abdullah, …, and Christopher D. Manning. 2024.`
3326
+ // —— 名在前姓在后,年份在整串作者**之后**
3327
+ // 所以不再拿正则硬抠"姓 + 逗号",改成**先按年份切开、再从作者串里取第一个人的最后一个词**。
3328
+ /** 整个括号。**不**要求里面只有一条引用:`(A et al., 2024; B et al., 2025)` 是常态。 */
3329
+ const AUTHOR_YEAR = /\(([^()]{1,240})\)/gu
3330
+ // 🔴 下面的正则都**必须带 u flag**:`\p{Lu}` / `\p{L}` 是 Unicode 属性转义,没有 u 时
2923
3331
  // 会被当成字面量 p / L / u,正则永远匹配不上而**不报错** —— 表现为索引恒为空、悬停全无反应。
2924
3332
  // 这条踩过一次(首版漏了 u,4 条作者-年份用例全挂)。
2925
- /** 参考文献条目开头的姓:surname, Initial. */
2926
- const REFERENCE_SURNAME = /^\s*(?:\[\s*\d{1,3}\s*\]\s*)?([\p{Lu}][\p{L}'-]+)\s*,/u
2927
- /** 条目里出现的第一个四位数年份。 */
2928
- const REFERENCE_YEAR = /\b(\d{4})\b/
3333
+ /** `e.g.,` / `i.e.,` / `cf.` / `see` 这些前缀不属于引用本身,逐条匹配前先剥掉。 */
3334
+ const CITE_PREFIX = /^\s*(?:e\.g\.|i\.e\.|cf\.|see|also)\s*,?\s*/i
3335
+ /** 并列里的一条:`Surname, 2020` / `Surname et al., 2020` / `Surname and Other, 2020`。 */
3336
+ const CITE_ITEM =
3337
+ /^\s*([\p{Lu}][\p{L}'-]+)(?:\s+et\s+al\.?|\s*(?:&|and)\s+[\p{Lu}][\p{L}'-]+(?:\s+[\p{Lu}][\p{L}'-]+)?)?\s*,\s*((?:19|20)\d{2})[a-z]?\s*$/u
3338
+ /**
3339
+ * 条目里第一个年份。
3340
+ *
3341
+ * 🔴 尾巴上的年份后缀要一起吃掉:`\b\d{4}\b` 匹配不了 `2024a`,那种条目会整条掉出索引。
3342
+ * 以 `19` / `20` 开头也顺带挡掉了页码 `1234` 之类误判。
3343
+ */
3344
+ const REFERENCE_YEAR = /\b((?:19|20)\d{2})[a-z]?\b/
3345
+ /** 作者串里一个像姓的词。`O'Brien` / `Gutiérrez` / `Liu-Lin` 都要能过。 */
3346
+ const NAME_WORD = /^[\p{Lu}][\p{L}'-]*$/u
2929
3347
 
2930
3348
  /** 匹配键:姓氏折叠成小写 + 年份。作者大小写与变音符号不在这一层处理。 */
2931
3349
  function authorYearKey(surname, year) {
@@ -2934,10 +3352,59 @@ function createLibraryModel() {
2934
3352
  : ''
2935
3353
  }
2936
3354
 
3355
+ /**
3356
+ * 参考文献条目 → 第一作者的姓。
3357
+ *
3358
+ * 两步,顺序不能反:
3359
+ * 1. **先按年份切开**。年份之后是标题、期刊、卷号,里面全是首字母大写的词 ——
3360
+ * 不先切掉就会取到 `Cognition` / `Psychological` 这种,索引里凭空多出一条假条目。
3361
+ * 2. 再从作者串里取**第一个人的最后一个词**。第一个人的边界是 `and` / `&` / 逗号 ——
3362
+ * 三种排版都用它们分隔作者。
3363
+ *
3364
+ * 逗号在两种排版里含义不同(`Smith, John` 是"姓, 名",而 `Ge Bai, Jie Liu` 是作者分隔),
3365
+ * 但两种情况下第一个逗号之前都正好是第一作者的姓氏串,所以先切逗号两边都对。
3366
+ *
3367
+ * @param {unknown} source 参考文献原文。
3368
+ * @returns {string} 姓氏;认不出时为空串(那条引用只是悬停没反应,不会错配到别人)。
3369
+ */
3370
+ function referenceSurname(source) {
3371
+ const lead = String(source ?? '').replace(/^\s*\[\s*\d{1,5}\s*\]\s*/, '')
3372
+ if (lead === '') return ''
3373
+ const year = REFERENCE_YEAR.exec(lead)
3374
+ const authors = year === null ? lead : lead.slice(0, year.index)
3375
+ const pick = zone => {
3376
+ const first = zone.split(/\s+(?:and|&)\s+|,/)[0]
3377
+ // 🔴 尾部句点必须剥掉:`Leonard Talmy.` 里 `Talmy.` 带点,不剥就过不了 NAME_WORD,
3378
+ // 于是只剩 `Leonard` 当姓 —— 索引里多出一个"Leonard 1975",正文的 `Talmy, 1975` 全落空。
3379
+ const words = first.trim().replace(/[.,;:]+$/, '').split(/\s+/).filter(word => NAME_WORD.test(word))
3380
+ return words.length === 0 ? '' : words[words.length - 1]
3381
+ }
3382
+ // 年份在最前(极少数期刊把年份编进卷首)时作者串是空的,退回整条开头再试一次。
3383
+ return pick(authors) || pick(lead)
3384
+ }
3385
+
3386
+ /**
3387
+ * 一个括号里解析出的全部引用。`;` 分隔并列,逐条剥掉 `e.g.,` 之类前缀。
3388
+ *
3389
+ * 🔴 任一条认不出就**整段作废**,与编号制同一口径(那个编号不在本篇就整段按纯文本):
3390
+ * 只标出认得的一半,读者会以为括号里只有那一半。
3391
+ *
3392
+ * @param {string} inner 括号内部(不含两侧圆括号)。
3393
+ * @returns {Array<{surname: string, year: string}>} 一条都认不出时为空数组。
3394
+ */
3395
+ function authorYearItems(inner) {
3396
+ const items = []
3397
+ for (const chunk of String(inner).split(';')) {
3398
+ const match = CITE_ITEM.exec(chunk.replace(CITE_PREFIX, ''))
3399
+ if (match === null) return []
3400
+ items.push({ surname: match[1], year: match[2] })
3401
+ }
3402
+ return items
3403
+ }
3404
+
2937
3405
  /**
2938
3406
  * 从参考文献块建「姓氏|年份 → 块」的一对多索引。
2939
3407
  *
2940
- * 姓氏取条目开头(可带 `[n]` 前缀)的第一个大写词,年份取条目里第一个四位数 ——
2941
3408
  * 学术期刊格式千差万别,这是**启发式**而不是解析器。认不出来的条目直接跳过:
2942
3409
  * 索引里少一条只是那条引用悬停没反应,不会错配到别的条目上。
2943
3410
  *
@@ -2950,10 +3417,10 @@ function createLibraryModel() {
2950
3417
  if (block === null || typeof block !== 'object' || typeof block.id !== 'string') continue
2951
3418
  if (readerKindOf(block) !== 'references') continue
2952
3419
  const source = typeof block.sourceText === 'string' ? block.sourceText : ''
2953
- const surname = REFERENCE_SURNAME.exec(source)
3420
+ const surname = referenceSurname(source)
2954
3421
  const year = REFERENCE_YEAR.exec(source)
2955
- if (surname === null || year === null) continue
2956
- const key = authorYearKey(surname[1], year[1])
3422
+ if (surname === '' || year === null) continue
3423
+ const key = authorYearKey(surname, year[1])
2957
3424
  if (key === '') continue
2958
3425
  const entry = { blockId: block.id, text: source.replace(REFERENCE_LEAD, '').trim() }
2959
3426
  const list = index.get(key)
@@ -2969,11 +3436,15 @@ function createLibraryModel() {
2969
3436
  * 只产出**索引里真有**的标记:查不到的括号原样留在文本里。这一条与编号制同一口径 ——
2970
3437
  * 点了没反应/悬停了没内容,比没有标记更坏。
2971
3438
  *
2972
- * 标记带 `ambiguous`:命中多条时为真,渲染层据此提示"共 N 条可能匹配"。
3439
+ * 括号里并列多条时,**整段合成一个标记**(而不是拆成几个可点区域):读者看到的是
3440
+ * 一个括号,悬停展开全部条目才符合直觉;拆开还会让"哪几个字属于同一条引用"变得无法判断。
3441
+ * 标记上带 `items`(每条的 `姓氏|年份` 键),形状与编号制的多标号一致。
3442
+ *
3443
+ * 标记带 `ambiguous`:全部条目命中总数 > 1 时为真,渲染层据此提示"共 N 条可能匹配"。
2973
3444
  *
2974
3445
  * @param {unknown} text 段落文本。
2975
3446
  * @param {unknown} index {@link authorYearIndex} 的产物。
2976
- * @returns {Array<{type: string, value: string, surname: string, year: string, ambiguous?: boolean, count?: number} | {type: 'text', text: string}>}
3447
+ * @returns {Array<{type: string, value: string, surname?: string, year?: string, items?: string[], ambiguous?: boolean, count?: number} | {type: 'text', text: string}>}
2977
3448
  */
2978
3449
  function inlineAuthors(text, index) {
2979
3450
  if (typeof text !== 'string' || text === '' || !(index instanceof Map) || index.size === 0) return []
@@ -2986,24 +3457,140 @@ function createLibraryModel() {
2986
3457
  let cursor = 0
2987
3458
  AUTHOR_YEAR.lastIndex = 0
2988
3459
  for (let match = AUTHOR_YEAR.exec(text); match !== null; match = AUTHOR_YEAR.exec(text)) {
2989
- const key = authorYearKey(match[1], match[2])
2990
- const hits = key === '' ? undefined : index.get(key)
2991
- if (hits === undefined || hits.length === 0) continue
3460
+ const items = authorYearItems(match[1])
3461
+ if (items.length === 0) continue
3462
+ // 先确认**每一条**都查得到,再决定要不要出标记:查到一半就放弃,才不会出现
3463
+ // "括号里两条、只标了一条"这种让人误解的部分标记。
3464
+ const keys = []
3465
+ let total = 0
3466
+ let known = true
3467
+ for (const item of items) {
3468
+ const key = authorYearKey(item.surname, item.year)
3469
+ const hits = key === '' ? undefined : index.get(key)
3470
+ if (hits === undefined || hits.length === 0) { known = false; break }
3471
+ keys.push(key)
3472
+ total += hits.length
3473
+ }
3474
+ if (!known) continue
2992
3475
  plain += text.slice(cursor, match.index)
2993
3476
  flush()
2994
- parts.push({
2995
- type: 'author',
2996
- value: match[0],
2997
- surname: match[1],
2998
- year: match[2],
2999
- ...(hits.length > 1 ? { ambiguous: true, count: hits.length } : {}),
3000
- })
3477
+ const single = items.length === 1
3478
+ const part = { type: 'author', value: match[0] }
3479
+ // 单条的字段形状**保持不变**:既有 4 条用例按字段全等断言,多一个字段就红。
3480
+ if (single) {
3481
+ part.surname = items[0].surname
3482
+ part.year = items[0].year
3483
+ } else {
3484
+ part.items = keys
3485
+ }
3486
+ if (total > 1) {
3487
+ part.ambiguous = true
3488
+ part.count = total
3489
+ }
3490
+ parts.push(part)
3001
3491
  cursor = match.index + match[0].length
3002
3492
  }
3003
3493
  plain += text.slice(cursor)
3004
3494
  flush()
3005
3495
  return parts
3006
3496
  }
3497
+ // ---- PDF 原页页栈(连续滚动)----
3498
+ /**
3499
+ * 一篇论文的页身份键:`文档|页|裁边档`。
3500
+ *
3501
+ * 🔴 **裁边是身份的一部分**:同一页裁与不裁拿到的坐标不是一套(宿主 readPdfPage 按满页口径
3502
+ * 缓存、cropPdfGroups 在读出后换算),拿裁边的文字层去配整页的位图,选字框会整片偏出页面。
3503
+ * 所以 key 里必须带它,改 key 就等于换一份数据,与旧实现在 pdfData.cropped 上做的判定同源。
3504
+ *
3505
+ * @param {unknown} documentId 本篇 documentId
3506
+ * @param {unknown} page 页码(1 起)
3507
+ * @param {unknown} crop 是否裁边
3508
+ * @returns {string} 空串 = 这个身份不成立(文档 id 为空或页码不是正整数)
3509
+ */
3510
+ function pdfStackKey(documentId, page, crop) {
3511
+ const id = typeof documentId === 'string' ? documentId : ''
3512
+ const number = Number(page)
3513
+ if (id === '' || !Number.isSafeInteger(number) || number < 1) return ''
3514
+ return id + '|' + number + '|' + (crop ? '1' : '0')
3515
+ }
3516
+
3517
+ /**
3518
+ * 该挂载哪几页:当前页 ± radius,并夹在 [1, pageCount] 里。
3519
+ *
3520
+ * 🔴 **这是连续滚动唯一的性能闸门**。一页的文字层约 4300 个 DOM 节点(逐字符对齐的代价,
3521
+ * 见 client.js 里 pdfPageView 的说明),12 页全挂就是 5 万个节点 —— 滚动与重涂都会被拖死。
3522
+ * 只挂「当前页 ± 半径」把常驻节点数钉在 (2·radius+1) 页的量级,滚出窗口的页整页卸载。
3523
+ *
3524
+ * radius = 1 是**滑动手感**的下限:滚到一页底部时下一页必须已经在 DOM 里,否则会先看到
3525
+ * 一屏骨架再等 JSON。再大只是白烧节点,滚一页用不到第三页。
3526
+ *
3527
+ * @param {unknown} page 当前页
3528
+ * @param {unknown} pageCount 总页数
3529
+ * @param {unknown} radius 前后各挂几页
3530
+ * @returns {number[]} 升序页码;参数不成立时空数组(**不编一圈默认页**)
3531
+ */
3532
+ function pdfPageWindow(page, pageCount, radius = 1) {
3533
+ const current = Number(page)
3534
+ const total = Number(pageCount)
3535
+ if (!Number.isSafeInteger(current) || current < 1) return []
3536
+ if (!Number.isSafeInteger(total) || total < 1) return []
3537
+ const span = Number.isSafeInteger(Number(radius)) && Number(radius) >= 0 ? Number(radius) : 1
3538
+ const from = Math.max(1, current - span)
3539
+ const to = Math.min(total, current + span)
3540
+ const pages = []
3541
+ for (let number = from; number <= to; number++) pages.push(number)
3542
+ return pages
3543
+ }
3544
+
3545
+ /**
3546
+ * 页框宽高比,**按 CSS `aspect-ratio` 的口径给(宽 / 高)**(纯函数)。
3547
+ *
3548
+ * 🔴 为什么可以篇内统一:实测同一篇论文各页尺寸逐页相同(PDF 页面框固定),所以一篇之内
3549
+ * 用同一个比例不会让任何一页变形;换来的是**不必等每页位图加载完就能定高度** ——
3550
+ * 否则滚动条会随着每一页加载完毕而跳动,而连续滚动最刺眼的就是这种跳。
3551
+ *
3552
+ * 🔴 方向别搞反:CSS 的 `aspect-ratio` 写的是**宽 / 高**。给成高 / 宽时,
3553
+ * A4 那种竖版页会被排成横版(0.77 与 1.29 差了 67%),整篇高度全错。
3554
+ * 换算不出正数时返回 null,调用方退回「按图片自然尺寸」而不是编一个比例。
3555
+ *
3556
+ * @param {unknown} width 页面宽(PDF 点)
3557
+ * @param {unknown} height 页面高(PDF 点)
3558
+ * @returns {number|null} 宽 / 高;无效是 null
3559
+ */
3560
+ function pdfPageAspectOf(width, height) {
3561
+ const w = Number(width)
3562
+ const h = Number(height)
3563
+ if (!Number.isFinite(w) || !Number.isFinite(h) || !(w > 0) || !(h > 0)) return null
3564
+ return w / h
3565
+ }
3566
+
3567
+ /**
3568
+ * 从滚动位置反推"现在是第几页"(纯函数)。
3569
+ *
3570
+ * 🔴 用**页顶坐标**而不是"视口中心落在谁身上":连续滚动下用户可能正停在两页交界处,
3571
+ * 中心判据在那一瞬间会来回跳(页码跟着闪),而"最后一个页顶已经滚过视口上沿的页"
3572
+ * 单调、稳定,滚过一页才前进一页。
3573
+ *
3574
+ * @param {number[]} tops 各页页顶的 scrollTop 偏移(升序)
3575
+ * @param {unknown} pages 与 tops 一一对应的页码
3576
+ * @param {unknown} scrollTop 当前滚动位置
3577
+ * @returns {number|null} 页码;参数不成立是 null
3578
+ */
3579
+ function pdfPageAt(tops, pages, scrollTop) {
3580
+ if (!Array.isArray(tops) || !Array.isArray(pages) || tops.length !== pages.length) return null
3581
+ if (tops.length === 0) return null
3582
+ const position = Number(scrollTop)
3583
+ if (!Number.isFinite(position)) return null
3584
+ // 留 2px 容差:滚动容器的 scrollTop 是整数化的,页顶算出来可能带小数,
3585
+ // 差这一线就会让"刚滚到下一页"判成还在上一页。
3586
+ let found = Number(pages[0])
3587
+ for (let index = 0; index < tops.length; index++) {
3588
+ if (Number(tops[index]) <= position + 2) found = Number(pages[index])
3589
+ else break
3590
+ }
3591
+ return Number.isSafeInteger(found) && found > 0 ? found : null
3592
+ }
3593
+
3007
3594
  // END CLIENT PARTS
3008
3595
  // 量容器的实际宽度(resize 时重量):ResizeObserver 不在就退回 window resize,清理函数
3009
3596
  // 一律走同一个 disconnect 形状。回调 ref 而不是 ref 对象 —— 节点挂上/换掉时都要重挂观察者。
@@ -3300,6 +3887,13 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
3300
3887
 
3301
3888
  .paper-pdf-controls{display:flex;align-items:center;gap:4px;flex:0 0 auto;flex-wrap:wrap;font-size:12px;color:var(--paper-muted)}
3302
3889
  .paper-pdf-controls .paper-btn{padding:3px 6px}
3890
+ /* ---- 连续滚动(页栈)----
3891
+ 页面一页页竖排,滚动交给 .paper-reader-layout 的原生 overflow:auto —— 滚轮 / 触控板 /
3892
+ 滚动条因此天然都是"翻页",不需要任何 wheel 事件处理。 */
3893
+ .paper-pdf-stack{display:flex;flex-direction:column;flex:0 0 auto;min-width:0;align-self:stretch;gap:calc(14px * var(--paper-pdf-zoom,1))}
3894
+ /* 页位:一页的"座位"。它比页面本身高一点点(就是上下那半格间距),保证滚动到底时
3895
+ 下一章的第一行也露出来,用户能看出"还没完"。min-height 由行内样式按统一宽高比给。 */
3896
+ .paper-pdf-slot{display:flex;flex-direction:column;flex:0 0 auto;min-width:0;scroll-margin-top:0}
3303
3897
  .paper-pdf-page{position:relative;flex:0 0 auto;min-width:0;align-self:flex-start;background:var(--paper-pdf-paper,#fff);overflow:hidden}
3304
3898
  .paper-pdf-image{display:block;width:100%;max-width:none;height:auto;user-select:none;-webkit-user-drag:none}
3305
3899
  .paper-pdf-text{position:absolute;left:0;top:0;transform:scale(var(--paper-pdf-scale,0));transform-origin:0 0;z-index:1}
@@ -4244,7 +4838,13 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4244
4838
  alt: payload.caption === '' ? line.text : payload.caption,
4245
4839
  })
4246
4840
  // 图注也过一遍行内 HTML:图块里同样会出现上标(如 "Fig. 2<sup>a</sup>")。
4247
- return h(tag ?? "p", shared, image, displayInlineHtml(line.text))
4841
+ // 🔴 但图注里的 `$…$` 必须交给渲染器:实测 STITCH 的 Figure 2 图注写着
4842
+ // `Thematic Scope $( \sigma _ { t } ) .$`,整段字面显示出来就是一屏 LaTeX 源码。
4843
+ // 只切出公式段送进 MarkdownText,其余仍是纯文本 —— 图注照样不做强调解析。
4844
+ return h(tag ?? "p", shared, image, captionPieces(displayInlineHtml(line.text)).map((piece, index) =>
4845
+ piece.math
4846
+ ? h(MarkdownText, { key: index, text: piece.text, labels: MARKDOWN_LABELS, variant: MARKDOWN_VARIANT })
4847
+ : piece.text))
4248
4848
  }
4249
4849
  // markdownText 是真正喂给渲染器的串(表格 / 公式 / 代码),缺省退回显示文本。
4250
4850
  const text = typeof payload?.markdownText === "string" && payload.markdownText !== ""
@@ -4464,17 +5064,28 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4464
5064
  const [exported, setExported] = React.useState('')
4465
5065
  // null follows the saved reading position or the first parsed page.
4466
5066
  const [readerPage, setReaderPage] = React.useState(null)
4467
- const [pdfData, setPdfData] = React.useState(null)
5067
+ // ---- PDF 原页页栈(连续滚动)----
5068
+ // 🔴 **从「一页」变成「一份按页键索引的页字典」**。单值那版的全部判据都写成
5069
+ // `pdfData.documentId === readerId && pdfData.page === currentPage && pdfData.cropped === pdfCrop`
5070
+ // —— 连续滚动下同时挂着好几页,这三条没有一个还能成立,必须换成按页键查:
5071
+ // 键由 pdfStackKey 统一给出(文档 + 页 + 裁边档),裁边为什么算身份见那个函数的说明。
5072
+ const [pdfPages, setPdfPages] = React.useState({})
4468
5073
  const [pdfFailure, setPdfFailure] = React.useState('')
4469
5074
  const [pdfLoading, setPdfLoading] = React.useState(false)
5075
+ // 这一篇一共有多少页。取第一份到手的文字层里的 pageCount(宿主 readPdfPage 逐页都带),
5076
+ // 拿不到就退回块列表里的最大页码 —— 不让页栈因为少一个字段就整片不渲染。
5077
+ const [pdfPageCount, setPdfPageCount] = React.useState(0)
4470
5078
  const [pdfZoom, setPdfZoom] = React.useState(1)
4471
5079
  // 裁边(默认开)。与视图档位、排版同样落 localStorage,**全局一份**:它答的是
4472
5080
  // 「我习惯怎么看原页」,不是「这一篇怎么看」。存 false 才关,缺省/读不出来都是开。
4473
5081
  const [pdfCrop, setPdfCrop] = React.useState(() => readPref(CROP_PREF_KEY)?.crop !== false)
4474
5082
  const [pdfImageAttempt, setPdfImageAttempt] = React.useState(0)
4475
- const pdfFrameRef = React.useRef(null)
5083
+ // 页栈里**每一页**各有一个 DOM 容器(.paper-pdf-page),比例尺与涂色都得逐页做。
5084
+ const pdfFrameRefs = React.useRef(new Map())
4476
5085
  const pdfMeasureRef = React.useRef(null)
4477
- const pdfRequestRef = React.useRef(null)
5086
+ // 在飞的文字层请求,**按页键分槽**:单槽那版换页时会 abort 掉上一页,连续滚动下
5087
+ // 那等于「滚到上一页就把下一页的请求掐死」,来回滚会一直重取。
5088
+ const pdfRequestRef = React.useRef(new Map())
4478
5089
  // <img onError> does not expose the route's status code.
4479
5090
  // P21 起它**只服务详情页封面**(右栏的原页面板已移除)。
4480
5091
  const [pageNote, setPageNote] = React.useState('')
@@ -4719,6 +5330,27 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4719
5330
  * 替身没有 DOM)—— 不写一个假的 0%,那会把用户读到一半的位置抹掉。
4720
5331
  */
4721
5332
  const onReaderScroll = event => {
5333
+ // 🔴 PDF 原页档(连续滚动)**也要接管滚动**:这一档没有正文块可量,但滚动位置就是
5334
+ // "我在第几页"。原来这一档 onScroll 是 undefined,于是翻页只能靠按钮;连续滚动之后
5335
+ // 页面一页页排开,滚动自然就该更新当前页 —— 而当前页是页栈窗口的输入,
5336
+ // 不更新的话滚到第 5 页时窗口还停在第 1 页附近,屏幕上是空的。
5337
+ if (isPdfPane(paneView)) {
5338
+ const tops = []
5339
+ const pages = []
5340
+ for (const page of pdfWindow) {
5341
+ const node = pdfFrameRefs.current.get(page) ?? null
5342
+ const top = node === null ? null : blockScrollTopOf(layoutElRef.current, node, 0)
5343
+ if (top === null) continue
5344
+ tops.push(top)
5345
+ pages.push(page)
5346
+ }
5347
+ const at = pdfPageAt(tops, pages, layoutElRef.current?.scrollTop ?? 0)
5348
+ if (at !== null && at !== currentPage) {
5349
+ setReaderPage(at)
5350
+ readingRef.current = { block: readerBlocks.find(block => block.page === at)?.id ?? '', page: at }
5351
+ }
5352
+ return
5353
+ }
4722
5354
  // 量一次、两处用:游标要的是块 id,锚点还要带上块内比例(D189 见 topAnchorOf)。
4723
5355
  const anchor = topAnchorOf(event?.currentTarget ?? layoutElRef.current)
4724
5356
  const cursor = readingCursorOf(anchor === null ? '' : anchor.blockId, readingRowsRef.current)
@@ -4728,9 +5360,25 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4728
5360
  // 并排时把「我读到哪一段」广播给另一格(D183)。只在并排里发 —— 单格时没有听众,
4729
5361
  // 白算一次锚点。判据是本格是不是被分出来的那一格,或对面那格有没有登记过存在。
4730
5362
  if (!paneSyncLiveRef.current) return
4731
- // 回声屏蔽(D185 / D189):跟随途中或刚跟完的静默窗口里一律不广播。
4732
- // 🔴 只比「游标是否正好落在目标块上」不够了:跟随是**逐帧**靠近的,途中游标会扫过
4733
- // 一串中间块,每一个都会被当成"读者滚到了这里"推回去,两格就互相拖着走。
5363
+ // 🔴 **手动滚动优先于跟随**(2026-11-20 用户实测抓出)。
5364
+ //
5365
+ // 现象:并排里先在译文滚,原文跟着滚;接着去滚原文,**原文一动不动**。反过来一样。
5366
+ //
5367
+ // 根因不是渲染,是这里原来只 `return` 了事:
5368
+ //
5369
+ // ```text
5370
+ // A 滚 → 广播 → B 的 paneFollowRef 非空、排上 requestAnimationFrame
5371
+ // runFollow 每帧 container.scrollTop = next,并把 hold 推到 now+120ms
5372
+ // 用户去滚 B → onReaderScroll 被 hold 拦下 return(既不广播,也不取消 follow)
5373
+ // → 但 runFollow 还在跑,下一帧又把 B 拉回去 → 用户看到「滚不动」
5374
+ // ```
5375
+ //
5376
+ // 所以静默窗口只该压**广播**,不能顺手把用户的操作也压掉。用户真的滚动时,
5377
+ // 必须立刻终止本格的跟随,并把状态交还给用户。
5378
+ // 🔴 **不能靠 scroll 事件本身来区分「用户」和「回声」**:回声也是 scroll 事件,
5379
+ // 而且它在 paneFollowRef 还有效时就到了 —— 拿它取消跟随,跟随会被自己的尾巴打断,
5380
+ // 永远收敛不了。真正的用户信号只有**输入事件**(滚轮 / 触摸 / 指针 / 按键),
5381
+ // 所以那一路单独取消跟随(见 stopFollowForUser),这里仍然只压广播。
4734
5382
  if (Date.now() < paneSyncHoldRef.current.until) return
4735
5383
  publishScrollAnchor(readerRef.current, cursor.block, paneRole, anchor === null ? 0 : anchor.ratio)
4736
5384
  }
@@ -4786,11 +5434,54 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4786
5434
  }
4787
5435
  if (typeof requestAnimationFrame === 'function') paneFollowFrameRef.current = requestAnimationFrame(runFollow)
4788
5436
  }
5437
+ /**
5438
+ * 用户一旦真的动手,立刻交出控制权(2026-11-20 用户实测)。
5439
+ *
5440
+ * 🔴 判据必须用**输入事件**,不能用 scroll 事件:跟随自身每帧设 scrollTop,
5441
+ * 它产生的 scroll 事件与用户的混在一起,拿来判断会把跟随自己的尾巴当成人手,
5442
+ * 跟随永远收敛不了。滚轮、触摸、指针按下、方向键 —— 这些只可能来自用户。
5443
+ *
5444
+ * 不这么做的后果(实测):A 格滚完,B 格的 runFollow 还在跑;用户去滚 B,
5445
+ * 每帧被拉回 A 的位置,表现出来就是「这一格滚不动」,且要等 follow 自己收敛才恢复。
5446
+ */
5447
+ const stopFollowForUser = () => {
5448
+ if (paneFollowRef.current === null && paneFollowFrameRef.current === null)
5449
+ return
5450
+ paneFollowRef.current = null
5451
+ if (paneFollowFrameRef.current !== null && typeof cancelAnimationFrame === 'function')
5452
+ cancelAnimationFrame(paneFollowFrameRef.current)
5453
+ paneFollowFrameRef.current = null
5454
+ // 窗口一起撤掉:下一帧用户的真实滚动应当照常广播给对面。
5455
+ paneSyncHoldRef.current.until = 0
5456
+ }
5457
+ // 🔴 **监听挂在第一次真正收到锚点上,不在 effect 开头**(2026-11-20)。
5458
+ //
5459
+ // 这个 effect 的依赖是 [paneRole, paneView],它不能保证在 layoutRef 回调 ref
5460
+ // 赋值之后再跑一次。effect 开头直接读 `layoutElRef.current` 可能拿到 null,
5461
+ // 于是监听静默没挂上 —— 而用户看到的仍然是「滚不动」,且没有任何报错。
5462
+ // 收到锚点时容器一定已经挂好(锚点就是从滚动容器里发出来的),在那儿挂最稳。
5463
+ let settled = null
5464
+ const bindUserStop = () => {
5465
+ const node = layoutElRef.current
5466
+ if (node === null || node === settled || typeof node?.addEventListener !== 'function') return
5467
+ if (settled !== null && typeof settled.removeEventListener === 'function') {
5468
+ settled.removeEventListener('wheel', stopFollowForUser)
5469
+ settled.removeEventListener('touchmove', stopFollowForUser)
5470
+ settled.removeEventListener('pointerdown', stopFollowForUser)
5471
+ settled.removeEventListener('keydown', stopFollowForUser)
5472
+ }
5473
+ settled = node
5474
+ settled.addEventListener('wheel', stopFollowForUser, { passive: true })
5475
+ settled.addEventListener('touchmove', stopFollowForUser, { passive: true })
5476
+ settled.addEventListener('pointerdown', stopFollowForUser, { passive: true })
5477
+ settled.addEventListener('keydown', stopFollowForUser)
5478
+ }
4789
5479
  const stop = subscribeScrollAnchor(anchor => {
4790
5480
  if (!shouldFollowAnchor(anchor, { live: paneSyncLiveRef.current, role: paneRole, documentId: readerRef.current })) return
4791
5481
  const container = layoutElRef.current
4792
5482
  if (container === null || typeof container !== 'object') return
4793
5483
  if (blockNodeOf(container, anchor.blockId) === null) return
5484
+ bindUserStop()
4794
5485
  paneFollowRef.current = { blockId: anchor.blockId, ratio: anchor.ratio }
4795
5486
  // 已经有一帧在等就复用它:锚点每秒会来几十次,每次都排一帧等于自己跟自己打架。
4796
5487
  if (paneFollowFrameRef.current === null && typeof requestAnimationFrame === 'function') {
@@ -4799,11 +5490,17 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
4799
5490
  })
4800
5491
  return () => {
4801
5492
  stop()
5493
+ if (settled !== null && typeof settled.removeEventListener === 'function') {
5494
+ settled.removeEventListener('wheel', stopFollowForUser)
5495
+ settled.removeEventListener('touchmove', stopFollowForUser)
5496
+ settled.removeEventListener('pointerdown', stopFollowForUser)
5497
+ settled.removeEventListener('keydown', stopFollowForUser)
5498
+ }
4802
5499
  if (paneFollowFrameRef.current !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(paneFollowFrameRef.current)
4803
5500
  paneFollowFrameRef.current = null
4804
5501
  paneFollowRef.current = null
4805
5502
  }
4806
- }, [paneRole, paneView])
5503
+ }, [paneRole, paneView, readerId])
4807
5504
 
4808
5505
  // ---- 阅读器(T16b) ----
4809
5506
  // 进入阅读器时拉一次 /reader。**只在进入时拉**,不挂轮询:/reader 会带一整篇的块,
@@ -5080,7 +5777,7 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
5080
5777
  try {
5081
5778
  const result = await api('/gloss', {
5082
5779
  method: 'POST',
5083
- body: JSON.stringify({ documentId: readerId, blockId: segment.blockId, quote: segment.quote, ...(segment.pdfPage ? { pdfPage: segment.pdfPage } : {}) }),
5780
+ body: JSON.stringify({ sessionId, documentId: readerId, blockId: segment.blockId, quote: segment.quote, ...(segment.pdfPage ? { pdfPage: segment.pdfPage } : {}) }),
5084
5781
  ...(controller === null ? {} : { signal: controller.signal }),
5085
5782
  })
5086
5783
  if (glossSeq.current !== seq) return
@@ -5146,7 +5843,7 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
5146
5843
  try {
5147
5844
  const result = await api('/gloss', {
5148
5845
  method: 'POST',
5149
- body: JSON.stringify({ documentId: readerId, blockId: segment.blockId, quote: segment.quote, ...(segment.pdfPage ? { pdfPage: segment.pdfPage } : {}) }),
5846
+ body: JSON.stringify({ sessionId, documentId: readerId, blockId: segment.blockId, quote: segment.quote, ...(segment.pdfPage ? { pdfPage: segment.pdfPage } : {}) }),
5150
5847
  ...(controller === null ? {} : { signal: controller.signal }),
5151
5848
  })
5152
5849
  if (glossSeq.current !== seq) return
@@ -5453,9 +6150,10 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
5453
6150
  let failure = ''
5454
6151
  try {
5455
6152
  for (const target of targets) {
5456
- const nativePage = target.pdfPage ?? (pdfData?.documentId === documentId && pdfData.groups?.some(group => group.id === target.blockId) ? pdfData.page : undefined)
6153
+ // 这一块在页栈的哪一页上:按页键遍历已挂载的页找(页栈之前是直接读 pdfData.page)。
6154
+ const nativePage = target.pdfPage ?? pdfMountedPages.find(page => pdfPages[pdfStackKey(documentId, page, pdfCrop)]?.groups?.some(group => group.id === target.blockId))
5457
6155
  try {
5458
- const result = await api('/gloss', { method: 'POST', body: JSON.stringify({ documentId, blockId: target.blockId, quote: target.quote, align: true, markId: target.id, ...(nativePage ? { pdfPage: nativePage } : {}) }) })
6156
+ const result = await api('/gloss', { method: 'POST', body: JSON.stringify({ sessionId, documentId, blockId: target.blockId, quote: target.quote, align: true, markId: target.id, ...(nativePage ? { pdfPage: nativePage } : {}) }) })
5459
6157
  if (readerRef.current !== documentId) return
5460
6158
  if (typeof result?.parallelQuote === 'string' && result.parallelQuote) {
5461
6159
  matched += 1
@@ -5945,41 +6643,112 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
5945
6643
  const zhLines = React.useMemo(() => columns !== null ? columns.zh : visibleRows(readerVisible, paneView === 'notes' ? 'zh' : paneView, 'single'), [columns, readerVisible, paneView])
5946
6644
  const srcLines = columns !== null ? columns.src : []
5947
6645
  // ---- PDF page and native selection layer ----
6646
+ // 这篇的最后一页。放在渲染期最前:页栈窗口、滚动比例、翻页按钮都要用它,
6647
+ // 而它只跟块列表有关 —— 摆到页栈下面会在渲染期撞 TDZ(依赖数组在求值时立即读它)。
6648
+ const readerLastPage = React.useMemo(() => readerBlocks.reduce((max, row) => (typeof row.page === 'number' && row.page > max ? row.page : max), 0), [readerBlocks])
5948
6649
  const firstPage = React.useMemo(() => (readerBlocks.find(row => typeof row.page === 'number')?.page) ?? 1, [readerBlocks])
5949
6650
  const currentPage = readerPage === null ? firstPage : readerPage
5950
- const activePdf = pdfData?.documentId === readerId && pdfData.page === currentPage && pdfData.cropped === pdfCrop ? pdfData : null
6651
+ // 当前页的文字层。页栈里同时挂着好几页,但**"当前页"仍是单数** —— 阅读位置、进度落盘、
6652
+ // 并排广播都只认一页。查不到是 null(第一次打开、这一页还在路上)。
6653
+ const activePdf = pdfPages[pdfStackKey(readerId, currentPage, pdfCrop)] ?? null
6654
+ // 这篇一共几页:首份文字层给的 pageCount 最准(宿主逐页都带),拿不到时退回块列表的最大页码。
6655
+ const pdfTotal = pdfPageCount > 0 ? pdfPageCount : readerLastPage
6656
+ // 该挂载哪几页。radius=1 就是「当前页 ± 1」,是滑动手感的下限:滚到一页底部时
6657
+ // 下一页必须已经在 DOM 里,否则会先看到一屏骨架再等 JSON。见 pdfPageWindow 的说明。
6658
+ const pdfWindow = React.useMemo(
6659
+ () => (isPdfPane(paneView) ? pdfPageWindow(currentPage, pdfTotal, 1) : []),
6660
+ [paneView, currentPage, pdfTotal],
6661
+ )
6662
+ // 已挂载那几页的页码(页栈之外的地方拿它反查"这一块在第几页")。
6663
+ const pdfMountedPages = pdfWindow
6664
+ /**
6665
+ * 窗口内所有页的文字层段落合集。
6666
+ *
6667
+ * 🔴 划线与引用涂色都要按**块**找文本,而连续滚动下一个块可能落在窗口内任意一页 ——
6668
+ * 只看当前页会漏掉滚到一半时横跨两页的那些块(旧单页版永远只有一页,所以没这个问题)。
6669
+ * 合集顺序按页码升序,pdfBlockTextOf 取第一个命中的段落,与旧口径一致。
6670
+ */
6671
+ const pdfGroupsAll = React.useMemo(() => {
6672
+ const merged = []
6673
+ for (const page of pdfWindow) {
6674
+ const data = pdfPages[pdfStackKey(readerId, page, pdfCrop)]
6675
+ if (data === undefined || !Array.isArray(data.groups)) continue
6676
+ for (const group of data.groups) merged.push(group)
6677
+ }
6678
+ return merged
6679
+ // pdfMountedPages 是 pdfWindow 的别名,不另立依赖。
6680
+ }, [pdfWindow, pdfPages, readerId, pdfCrop])
6681
+ /**
6682
+ * 取某一页的文字层(按页键去重、按页并发,不互相 abort)。
6683
+ *
6684
+ * 🔴 与单槽那版的差别全在**并发语义**上:原来换页就 abort 上一页,因为同时只需要一页;
6685
+ * 连续滚动下页面栈里前后各挂一页,abort 会让「往回滚一页」重新走一遍网络。
6686
+ * 现在一个页键一个槽位,重复请求直接复用同一个 promise,只有强制重试才换 controller。
6687
+ *
6688
+ * @param {string} documentId 本篇 documentId
6689
+ * @param {number} page 页码(1 起)
6690
+ * @param {boolean} force 忽略已到手的那份,重新取("重试 PDF"按钮)
6691
+ */
5951
6692
  async function loadPdfPage(documentId = readerId, page = currentPage, force = false) {
5952
6693
  if (!documentId) return
6694
+ const key = pdfStackKey(documentId, page, pdfCrop)
6695
+ if (key === '') return
5953
6696
  if (force) setPdfImageAttempt(value => value + 1)
5954
- // 裁边档位是缓存身份的一部分:同一页裁与不裁拿到的坐标不是一套,不能互相顶替。
5955
- const key = documentId + ':' + page + ':' + (pdfCrop ? 'crop' : 'full')
5956
- if (!force && pdfData?.documentId === documentId && pdfData.page === page && pdfData.cropped === pdfCrop) return
5957
- if (!force && pdfRequestRef.current?.key === key) return pdfRequestRef.current.promise
5958
- pdfRequestRef.current?.controller?.abort()
6697
+ const flight = pdfRequestRef.current
6698
+ // 已经有这一页了,且不是强制重试:什么都不用做(滚动窗口会反复调到这里)。
6699
+ if (!force && pdfPages[key] !== undefined) return
6700
+ if (!force && flight.has(key)) return flight.get(key).promise
6701
+ flight.get(key)?.controller?.abort()
5959
6702
  const controller = typeof AbortController === 'function' ? new AbortController() : null
5960
6703
  const request = { key, controller }
5961
- pdfRequestRef.current = request
6704
+ flight.set(key, request)
5962
6705
  setPdfFailure(''); setPdfLoading(true)
5963
6706
  request.promise = api('/pdf-page?documentId=' + encodeURIComponent(documentId) + '&page=' + page + (pdfCrop ? '&crop=1' : ''),
5964
6707
  controller ? { signal: controller.signal } : undefined).then(data => {
5965
- if (readerRef.current !== documentId || pdfRequestRef.current !== request) return
5966
- setPdfData({ ...data, documentId, cropped: pdfCrop })
6708
+ // 换篇之后,旧篇还在飞的请求回来要丢掉 —— 判据是**这一篇还是不是当前篇**,
6709
+ // 而不是"这个槽位有没有被顶掉"(槽位按页键分开,永远顶不到彼此)。
6710
+ if (readerRef.current !== documentId) return
6711
+ setPdfPages(current => ({ ...current, [key]: { ...data, documentId, cropped: pdfCrop } }))
6712
+ const count = Number(data?.pageCount)
6713
+ if (Number.isSafeInteger(count) && count > 0) setPdfPageCount(current => (current === count ? current : count))
5967
6714
  }).catch(reason => {
5968
- if (reason?.name !== 'AbortError' && readerRef.current === documentId && pdfRequestRef.current === request) setPdfFailure(String(reason?.message ?? reason))
6715
+ if (reason?.name !== 'AbortError' && readerRef.current === documentId) setPdfFailure(String(reason?.message ?? reason))
5969
6716
  }).finally(() => {
5970
- if (pdfRequestRef.current === request) { pdfRequestRef.current = null; setPdfLoading(false) }
6717
+ if (flight.get(key) === request) {
6718
+ flight.delete(key)
6719
+ // 还有别的页在路上就别熄灭加载提示 —— 连续滚动下同时两三页是常态。
6720
+ if (flight.size === 0) setPdfLoading(false)
6721
+ }
5971
6722
  })
5972
6723
  return request.promise
5973
6724
  }
6725
+ /**
6726
+ * 滚到某一页的页顶(按钮与滚轮**共用这一个入口**)。
6727
+ *
6728
+ * 🔴 用户裁定「按钮保留,点击下一页自动移动到下一页」:连续滚动下按钮不再是"换一份数据",
6729
+ * 而是"把容器滚到那一页"。与滚轮共用同一个滚动位置,两种操作因此不可能各说一套。
6730
+ * 平滑滚动用 `behavior:'smooth'`;量不到页顶(还没挂上、替身没有 DOM)时退回朴素 scrollTo,
6731
+ * 不编一个位置。
6732
+ */
6733
+ const scrollToPage = page => {
6734
+ const container = layoutElRef.current
6735
+ const node = pdfFrameRefs.current.get(page) ?? null
6736
+ const top = node === null ? null : blockScrollTopOf(container, node, 0)
6737
+ if (top !== null) container?.scrollTo?.({ top, left: 0, behavior: 'smooth' })
6738
+ else container?.scrollTo?.({ top: 0, left: 0 })
6739
+ }
5974
6740
  const changePdfPage = page => {
5975
6741
  dismissMark()
5976
6742
  pendingScrollRef.current = ''
5977
6743
  setScrollTarget('')
5978
- layoutElRef.current?.scrollTo?.({ top: 0, left: 0 })
5979
- setReaderPage(page)
5980
- const row = readerBlocks.find(block => block.page === page)
5981
- readingRef.current = { block: row?.id ?? '', page }
5982
- void loadPdfPage(readerId, page)
6744
+ const target = Number(page)
6745
+ if (!Number.isSafeInteger(target) || target < 1) return
6746
+ // 先确保这一页与它的邻居在窗口里(快速连点时窗口还没跟上),再滚过去。
6747
+ void loadPdfPage(readerId, target)
6748
+ setReaderPage(target)
6749
+ scrollToPage(target)
6750
+ const row = readerBlocks.find(block => block.page === target)
6751
+ readingRef.current = { block: row?.id ?? '', page: target }
5983
6752
  // 并排时把「我翻到哪一段」广播给对面(D188,用户实测报「PDF 翻页时译文没跟着滑」)。
5984
6753
  // 🔴 原页档**没有 scroll 事件**(onScroll 在这一档是 undefined),所以它是全仓唯一
5985
6754
  // 不会自动发锚点的档 —— 翻页必须在这里显式补一发,否则对面永远停在原处。
@@ -5989,32 +6758,78 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
5989
6758
  publishScrollAnchor(readerRef.current, row.id, paneRole, 0)
5990
6759
  }
5991
6760
  }
6761
+ // 窗口内的每一页都要有文字层:滚到边界之前下一页必须已经在(见 pdfPageWindow)。
6762
+ // 依赖里放 pdfWindow 而不只是 currentPage —— 页数从 0 变成真实值时窗口会重算。
5992
6763
  React.useEffect(() => {
5993
- if (isPdfPane(paneView)) void loadPdfPage()
5994
- }, [readerId, currentPage, paneView])
5995
- // 切裁边档位要重新取一页:坐标与图都随它变,留着旧的一份会图文错位。
6764
+ if (!isPdfPane(paneView) || readerId === '') return
6765
+ for (const page of pdfWindow) void loadPdfPage(readerId, page)
6766
+ }, [readerId, pdfWindow, paneView])
6767
+ // 切裁边档位要重取:键里的裁边变了,旧那份一个字也用不上(坐标与图都随它变)。
5996
6768
  React.useEffect(() => {
5997
6769
  if (!isPdfPane(paneView) || !readerId) return
5998
- void loadPdfPage(readerId, currentPage, false)
6770
+ for (const page of pdfWindow) void loadPdfPage(readerId, page)
5999
6771
  }, [pdfCrop])
6000
- React.useEffect(() => () => pdfRequestRef.current?.controller?.abort(), [])
6772
+ // 卸载:把所有在飞的页请求一起撤掉(Map 里可能有好几个,单槽那版只撤了一个)。
6773
+ React.useEffect(() => () => {
6774
+ for (const request of pdfRequestRef.current.values()) request.controller?.abort()
6775
+ pdfRequestRef.current.clear()
6776
+ }, [])
6777
+ // 比例尺逐页算:文字层按 PDF 点坐标绝对定位,得乘上"这一页渲染出来多宽 / PDF 多宽"。
6778
+ // 🔴 每页各一份 ResizeObserver 而不是只观察当前页 —— 否则滚到下一页时它的比例尺还是 0,
6779
+ // 整层文字会缩成一个点(transform:scale(0) 就在 CSS 里当默认值)。
6001
6780
  React.useEffect(() => {
6002
- const frame = pdfFrameRef.current
6003
- if (!isPdfPane(paneView) || !activePdf || !frame) return
6004
- const fit = () => frame.style.setProperty('--paper-pdf-scale', String(frame.getBoundingClientRect().width / activePdf.width))
6005
- fit()
6006
- const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(fit) : null
6007
- observer?.observe(frame)
6008
- window.addEventListener('resize', fit)
6009
- return () => { observer?.disconnect(); window.removeEventListener('resize', fit) }
6010
- }, [activePdf, paneView, pdfZoom])
6011
- const pdfPageView = React.useMemo(() => h('div', {
6012
- className: 'paper-pdf-page', ref: pdfFrameRef, 'data-page': currentPage,
6013
- style: { width: (pdfZoom * 100) + '%' },
6781
+ if (!isPdfPane(paneView)) return undefined
6782
+ const frames = pdfFrameRefs.current
6783
+ const cleanups = []
6784
+ for (const page of pdfWindow) {
6785
+ const frame = frames.get(page) ?? null
6786
+ const data = pdfPages[pdfStackKey(readerId, page, pdfCrop)] ?? null
6787
+ if (frame === null || data === null || !(Number(data.width) > 0)) continue
6788
+ const fit = () => frame.style.setProperty('--paper-pdf-scale', String(frame.getBoundingClientRect().width / data.width))
6789
+ fit()
6790
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(fit) : null
6791
+ observer?.observe(frame)
6792
+ cleanups.push(() => observer?.disconnect())
6793
+ }
6794
+ const onResize = () => {
6795
+ for (const page of pdfWindow) {
6796
+ const frame = frames.get(page) ?? null
6797
+ const data = pdfPages[pdfStackKey(readerId, page, pdfCrop)] ?? null
6798
+ if (frame === null || data === null || !(Number(data.width) > 0)) continue
6799
+ frame.style.setProperty('--paper-pdf-scale', String(frame.getBoundingClientRect().width / data.width))
6800
+ }
6801
+ }
6802
+ window.addEventListener('resize', onResize)
6803
+ return () => { for (const stop of cleanups) stop(); window.removeEventListener('resize', onResize) }
6804
+ }, [pdfWindow, pdfPages, paneView, readerId, pdfCrop, pdfZoom])
6805
+ /**
6806
+ * 一页的原页位图 + 选字层(连续滚动的**一个页位**)。
6807
+ *
6808
+ * 🔴 与单页那版的差别只在**入参**:原来的 `activePdf` 是"永远指向当前页"的闭包变量,
6809
+ * 页栈里同时挂着前后各一页,每一页都得按自己的文字层画,所以它变成参数。
6810
+ * 函数体一根线不动 —— 位图与坐标同源(同 crop 档)、逐字符 span 拉伸对齐、
6811
+ * 引用悬停走 ref 转存,全部照旧,这样选字精度不会被这次改动碰到。
6812
+ *
6813
+ * @param {number} page 页码(1 起)
6814
+ * @param {object|null} activePdf 这一页的文字层(未到是 null,只画位图)
6815
+ * @param {number|null} aspect 统一的宽高比(见 pdfPageAspectOf),null 时按图片自然尺寸
6816
+ */
6817
+ const pdfPageNode = (page, activePdf, aspect) => h('div', {
6818
+ className: 'paper-pdf-page',
6819
+ // 每页一个容器引用:比例尺、滚动定位、涂色都要按页找到它。
6820
+ ref: node => { if (node === null) pdfFrameRefs.current.delete(page); else pdfFrameRefs.current.set(page, node) },
6821
+ 'data-page': page,
6822
+ style: {
6823
+ width: (pdfZoom * 100) + '%',
6824
+ // 位图没到之前先用统一比例占住高度,滚动条不会随加载跳动。
6825
+ aspectRatio: aspect === null ? undefined : String(aspect),
6826
+ },
6014
6827
  }, h('img', {
6015
- key: readerId + ':' + currentPage + ':' + pdfImageAttempt,
6016
- className: 'paper-pdf-image', src: pageImageUrl(readerId, currentPage, PAGE_IMAGE_WIDTH, pdfCrop), alt: 'PDF 原文 · 第 ' + currentPage + ' 页',
6828
+ key: readerId + ':' + page + ':' + pdfImageAttempt,
6829
+ className: 'paper-pdf-image', src: pageImageUrl(readerId, page, PAGE_IMAGE_WIDTH, pdfCrop), alt: 'PDF 原文 · 第 ' + page + ' 页',
6017
6830
  draggable: false, width: activePdf?.width, height: activePdf?.height,
6831
+ // 窗口里通常还挂着前后各一页,让浏览器自己排加载顺序比我们抢带宽更准。
6832
+ loading: 'lazy', decoding: 'async',
6018
6833
  onError: () => setPdfFailure(PAGE_IMAGE_FAILED_NOTE),
6019
6834
  }), activePdf ? h('div', { className: 'paper-pdf-text', style: { width: activePdf.width, height: activePdf.height } },
6020
6835
  activePdf.groups.map(group => {
@@ -6026,7 +6841,8 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6026
6841
  rows.at(-1).words.push(word)
6027
6842
  }
6028
6843
  return h('div', {
6029
- className: 'paper-pdf-block', key: group.id, 'data-block-id': group.id, 'data-language': 'source', 'data-pdf-page': activePdf.page,
6844
+ // 🔴 key 必须带上 part:一个块被拆成多段时 id 相同,只按 id 做 key 会撞。
6845
+ className: 'paper-pdf-block', key: group.id + '#' + (group.part ?? 0), 'data-block-id': group.id, 'data-language': 'source', 'data-pdf-page': activePdf.page,
6030
6846
  style: { left: bounds[0] * activePdf.width / 1000, top: bounds[1] * activePdf.height / 1000,
6031
6847
  width: (bounds[2] - bounds[0]) * activePdf.width / 1000, height: (bounds[3] - bounds[1]) * activePdf.height / 1000 },
6032
6848
  onMouseUp: event => { event.stopPropagation?.(); captureSelection(event, true) },
@@ -6078,8 +6894,9 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6078
6894
  if (!node || !(width > 0)) return
6079
6895
  const context = pdfMeasureRef.current ??= document.createElement('canvas').getContext?.('2d')
6080
6896
  if (!context) return
6081
- context.font = size + 'px serif'
6082
- const metrics = pdfWordMetrics(core, width, gap, text => context.measureText(text).width)
6897
+ // 走 glyphWidthOf 而不是直接 measureText:同一字号 + 同一字串的宽度是确定的,
6898
+ // 缓存能省掉 88% 的测量(见 glyphWidthOf 的说明)。
6899
+ const metrics = pdfWordMetrics(core, width, gap, text => glyphWidthOf(context, size, text) ?? 0)
6083
6900
  if (!metrics) return
6084
6901
  node.style.letterSpacing = metrics.letterSpacing + 'px'
6085
6902
  node.style.wordSpacing = metrics.wordSpacing + 'px'
@@ -6090,9 +6907,9 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6090
6907
  const stretchChar = (node, advance) => {
6091
6908
  if (!node) return
6092
6909
  const context = pdfMeasureRef.current ??= document.createElement('canvas').getContext?.('2d')
6093
- if (!context) return
6094
- context.font = size + 'px serif'
6095
- node.style.letterSpacing = (advance - context.measureText(node.textContent).width) + 'px'
6910
+ const measured = glyphWidthOf(context, size, node.textContent)
6911
+ if (measured === null) return
6912
+ node.style.letterSpacing = (advance - measured) + 'px'
6096
6913
  }
6097
6914
  return h('span', {
6098
6915
  className: 'paper-pdf-word', key: index,
@@ -6107,9 +6924,44 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6107
6924
  }, char.text)) : core)
6108
6925
  }))
6109
6926
  }))
6110
- })) : null), [activePdf, readerId, currentPage, pdfZoom, pdfImageAttempt, pdfCrop])
6111
- // 这篇的最后一页。放在渲染期:滚动那条与翻页那条都要用它算比例,而它只跟块列表有关。
6112
- const readerLastPage = React.useMemo(() => readerBlocks.reduce((max, row) => (typeof row.page === 'number' && row.page > max ? row.page : max), 0), [readerBlocks])
6927
+ })) : null)
6928
+ /**
6929
+ * 页栈本体:窗口内的每一页竖直排开,滚轮 / 触控板 / 滚动条全都交给浏览器原生滚动。
6930
+ *
6931
+ * 🔴 这就是「鼠标滑动浏览上一页/下一页」的全部实现 —— **没有任何 wheel 事件处理**。
6932
+ * 容器本来就是 overflow:auto 的 .paper-reader-layout,页面一页页往下排之后,
6933
+ * 滑动就是滚动,滚动就是翻页。这与「连续滚动,页面一页页往下排」的裁定一致。
6934
+ *
6935
+ * 🔴 **窗口化是唯一的数据闸门**:一页文字层约 4,300 个 DOM 节点(逐字符对齐的代价,
6936
+ * 见 pdfPageNode 的说明),全篇 12 页就是 5 万个节点 —— 滚动与重涂都会被拖死。
6937
+ * pdfPageWindow 只放「当前页 ± 1」,滚出窗口的页整页卸载(不是 display:none,
6938
+ * 那还占着节点)。滚到一页底部时下一页必然已在 DOM 里,所以看不到骨架。
6939
+ *
6940
+ * 🔴 页与页之间的间距随缩放走:固定 px 在 300% 时看起来像条分割线。
6941
+ */
6942
+ const pdfPageView = React.useMemo(() => {
6943
+ // 比例尺取窗口内任一份到手的文字层:篇内各页尺寸相同(实测),所以一份就够。
6944
+ const sample = pdfWindow
6945
+ .map(page => pdfPages[pdfStackKey(readerId, page, pdfCrop)])
6946
+ .find(data => data !== undefined) ?? null
6947
+ const aspect = sample === null ? null : pdfPageAspectOf(sample.width, sample.height)
6948
+ return h('div', { className: 'paper-pdf-stack', 'data-pages': String(pdfWindow.length) },
6949
+ pdfWindow.map(page => h('div', {
6950
+ className: 'paper-pdf-slot' + (page === currentPage ? ' is-current' : ''),
6951
+ key: page,
6952
+ 'data-page': page,
6953
+ // 🔴 **不要给页位设高度**,高度一律由页图自己撑开。
6954
+ //
6955
+ // 踩过的坑:这里原来写 `minHeight: calc(100% * aspect)`。百分比是相对**容器**
6956
+ // 高度解析的,而容器高度又由内容加起来 —— 自引用。实测结果就是裁边档下面露出
6957
+ // 一大片纸色空白:图按裁边后的比例只有 0.66 高,容器却按满页 0.77 撑着,
6958
+ // 差出来的那一截全是背景色(用户截图报的"上下的边没有裁")。
6959
+ //
6960
+ // 页面图本身带 `aspect-ratio`(见 pdfPageNode),位图没到时也已经有正确高度,
6961
+ // 所以页位完全不需要自己再撑一遍。这样裁边与整页两档的高度各自由各自的宽高比
6962
+ // 决定,永远不会互相打架。
6963
+ }, pdfPageNode(page, pdfPages[pdfStackKey(readerId, page, pdfCrop)] ?? null, aspect))))
6964
+ }, [pdfWindow, pdfPages, readerId, currentPage, pdfZoom, pdfImageAttempt, pdfCrop])
6113
6965
  // Keep the reading bridge available when the library view remounts.
6114
6966
  // 这个 effect 必须放在 currentPage 声明之后 —— 依赖数组在渲染期求值,写前面会撞 TDZ。
6115
6967
  React.useEffect(() => {
@@ -6238,13 +7090,16 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6238
7090
  layoutElRef.current ?? (typeof document !== 'undefined' ? document : null),
6239
7091
  markHighlightNames.current,
6240
7092
  markGroups(marks),
6241
- isPdfPane(paneView) && activePdf ? reader?.blocks?.map(block => {
6242
- const group = activePdf.groups.find(group => group.id === block.id)
6243
- return group ? { ...block, sourceText: group.text } : block
7093
+ // 🔴 用**窗口内全部页**的段落合集,不是当前页那一份:连续滚动下一个块可能落在
7094
+ // 相邻那一页上,只看当前页会让滚到一半时的划线整片对不上(旧单页版没有这个问题)。
7095
+ isPdfPane(paneView) && pdfGroupsAll.length > 0 ? reader?.blocks?.map(block => {
7096
+ // 整块正文:块可能被拆成多段 DOM,取某一段会漏另一半。
7097
+ const text = pdfBlockTextOf(pdfGroupsAll, block.id)
7098
+ return text === '' ? block : { ...block, sourceText: text }
6244
7099
  }) : reader?.blocks,
6245
7100
  )
6246
7101
  return undefined
6247
- }, [highlightSupport, view, reader, marks, paneView, activePdf])
7102
+ }, [highlightSupport, view, reader, marks, paneView, pdfGroupsAll])
6248
7103
  // ---- 引用悬停预览(T25b)----
6249
7104
  // 与划线同一范式:渲染树不动,effect 里把已挂载的 DOM 包上 span(见 paintCiteSpans)。
6250
7105
  // 依赖与划线那条一致 —— 正文 DOM 会在切换档位时重建,span 必须跟着重包。
@@ -6274,11 +7129,13 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6274
7129
  // 只涂前者时原页那侧静默没有任何反应 —— 界面上看不出错,只是"悬停不管用"。
6275
7130
  // PDF 这侧的块文本以文字层 group.text 为准(与划线那条同一口径),否则段落正文与
6276
7131
  // 页面上真实的字对不上,找位置会失败。
6277
- const pdfMode = isPdfPane(paneView) && activePdf !== null
7132
+ // 🔴 用**窗口内全部页**的段落合集。连续滚动下窗口里挂着前后各一页,一个块可能落在
7133
+ // 相邻那一页上;只看当前页会让「滚到页边界时引用整片点不动」(旧单页版没这问题)。
7134
+ const pdfMode = isPdfPane(paneView) && pdfGroupsAll.length > 0
6278
7135
  const blocks = pdfMode
6279
7136
  ? (reader?.blocks ?? []).map(block => {
6280
- const group = activePdf.groups.find(item => item.id === block.id)
6281
- return group ? { ...block, sourceText: group.text } : block
7137
+ const text = pdfBlockTextOf(pdfGroupsAll, block.id)
7138
+ return text === '' ? block : { ...block, sourceText: text }
6282
7139
  })
6283
7140
  : reader?.blocks
6284
7141
  const parts = citePartsOf(citeRowsById, blocks, readerNumbers(blocks ?? []))
@@ -6312,28 +7169,47 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6312
7169
  paintCiteSpans(layoutElRef.current ?? (typeof document !== 'undefined' ? document : null), parts)
6313
7170
  painted.layout = layoutKey
6314
7171
  }
6315
- // 🔴 PDF 侧另有一份签名:**任何让页面树 useMemo 重算的输入**都会重建整棵子树并
6316
- // 丢掉 data-cite-span,那时块内容可能一模一样,仍然必须重涂。
6317
- // 页面树的依赖是 [activePdf, readerId, currentPage, pdfZoom, pdfImageAttempt, pdfCrop]
7172
+ // 🔴 PDF 侧另有一份签名:**任何让页面栈重算的输入**都会重建那几页的子树并丢掉
7173
+ // data-cite-span,那时块内容可能一模一样,仍然必须重涂。
7174
+ // 页面栈的依赖是 [pdfWindow, pdfPages, readerId, currentPage, pdfZoom, pdfImageAttempt, pdfCrop]
6318
7175
  // —— 少放一个就会出现「缩放之后悬停失灵」,而界面上完全不报错。
7176
+ // 🔴 签名里**必须有 pdfWindow**:连续滚动时窗口随当前页滑动而换人,
7177
+ // 页内容与块内容可能一个字没变(来回滚同一段),但挂载的是另外几页。
6319
7178
  const pdfKey = pdfMode
6320
- ? `${activePdf.page}:${pdfCrop ? 1 : 0}:${currentPage}:${pdfZoom}:${pdfImageAttempt}:${signature}`
7179
+ ? `${pdfWindow.join('.')}:${pdfCrop ? 1 : 0}:${pdfZoom}:${pdfImageAttempt}:${signature}`
6321
7180
  : ''
6322
- const pdfStillMarked = () => {
6323
- const scope = pdfFrameRef.current
6324
- if (scope === null || typeof scope?.querySelectorAll !== 'function') return false
6325
- return scope.querySelectorAll('[data-cite-span]').length > 0
7181
+ /**
7182
+ * PDF 侧要不要重涂:**逐页探测**。
7183
+ *
7184
+ * 🔴 与正文栏同一条纪律(见 stillMarked 的说明):签名只当省钱的门槛,正确性落在
7185
+ * 「DOM 里标记还在不在」上。连续滚动后窗口里有多页,任何一页丢了标记都要重涂 ——
7186
+ * 只探当前页会让「滚过去再滚回来」的那一页悬停整片失灵。
7187
+ */
7188
+ const pdfMissing = () => {
7189
+ for (const page of pdfWindow) {
7190
+ const scope = pdfFrameRefs.current.get(page) ?? null
7191
+ if (scope === null || typeof scope?.querySelectorAll !== 'function') continue
7192
+ if (scope.querySelectorAll('[data-cite-span]').length === 0) return true
7193
+ }
7194
+ return false
6326
7195
  }
6327
- if (pdfKey !== '' && (painted.pdf !== pdfKey || !pdfStillMarked())) {
6328
- paintCiteSpans(pdfFrameRef.current, parts)
7196
+ if (pdfKey !== '' && (painted.pdf !== pdfKey || pdfMissing())) {
7197
+ // 🔴 逐页涂:一次 paintCiteSpans 只扫一个子树,而每个页位是独立子树。
7198
+ for (const page of pdfWindow) {
7199
+ const scope = pdfFrameRefs.current.get(page) ?? null
7200
+ if (scope !== null) paintCiteSpans(scope, parts)
7201
+ }
6329
7202
  painted.pdf = pdfKey
6330
7203
  } else if (pdfKey === '') {
6331
7204
  painted.pdf = ''
6332
7205
  }
6333
7206
  return undefined
6334
7207
  // readerBlocks 在依赖里:渲染行变了(换篇、重解析)标记位置也跟着变。
6335
- // currentPage 在依赖里:PDF 原页翻页是**整棵子树重建**,不重涂新页就没有悬停。
6336
- }, [view, reader, readerBlocks, paneView, activePdf, currentPage, pdfZoom, pdfCrop, pdfImageAttempt])
7208
+ // pdfWindow 在依赖里:连续滚动时窗口换人 = 挂载的页换了,不重涂新页就没有悬停。
7209
+ // 🔴 pdfPages 与 pdfWindow **两个都要**在依赖里,不能靠 pdfGroupsAll 的传递性:
7210
+ // 页面栈会因这两者任一变化而重建,而"重建就必须重涂"这条不变量要在源码里看得见
7211
+ // (cite-dom.test.js 逐项比对这两份清单,传递性一律视为没写)。
7212
+ }, [view, reader, readerBlocks, paneView, pdfGroupsAll, pdfPages, pdfWindow, currentPage, pdfZoom, pdfCrop, pdfImageAttempt])
6337
7213
  React.useEffect(() => () => { if (citeTimer.current) clearTimeout(citeTimer.current) }, [])
6338
7214
  /**
6339
7215
  * 指针落进/离开一个引用标记。
@@ -6364,7 +7240,11 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6364
7240
  const id = node.getAttribute('data-cite-span')
6365
7241
  const root = node.ownerDocument ?? (typeof document === 'undefined' ? null : document)
6366
7242
  if (id === null || id === '' || root === null) return []
6367
- const scope = pdfFrameRef.current ?? root
7243
+ // 🔴 从**标记自己所在的那个页位**往上找检查范围,而不是写死当前页:
7244
+ // 连续滚动下窗口里挂着多页,悬停发生的那一页不一定是 currentPage(用户可能正在
7245
+ // 滚向下一页的途中),拿 currentPage 那个容器去找会一个都找不到 —— 表现为"整组不亮"。
7246
+ const own = typeof node.closest === 'function' ? node.closest('.paper-pdf-page') : null
7247
+ const scope = own ?? root
6368
7248
  if (typeof scope.querySelectorAll !== 'function') return []
6369
7249
  return [...scope.querySelectorAll('[data-cite-span]')].filter(item => item.getAttribute('data-cite-span') === id)
6370
7250
  }
@@ -6389,6 +7269,15 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6389
7269
  const hit = citeLookup.numbers.get(number)
6390
7270
  if (hit !== undefined) entries.push(hit)
6391
7271
  }
7272
+ } else if (node.getAttribute('data-cite-items') !== null) {
7273
+ // 并列:data-cite-items 是「姓氏|年份」键的逗号分隔串。键里不含逗号
7274
+ // (authorYearKey 用 | 连接),所以直接 split 是安全的。
7275
+ // 🔴 不能用 surname/year 那两个属性查 —— 并列标记上它们**是空的**(整段一个标记,
7276
+ // 没有单一姓氏),拿空键查表必然落空,表现是"括号标出来了但悬停没内容"。
7277
+ for (const key of String(node.getAttribute('data-cite-items')).split(',')) {
7278
+ const hits = citeLookup.authors instanceof Map ? citeLookup.authors.get(key) : undefined
7279
+ if (Array.isArray(hits)) entries.push(...hits)
7280
+ }
6392
7281
  } else {
6393
7282
  entries = ambiguousLookup(
6394
7283
  citeLookup.authors,
@@ -6723,7 +7612,7 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6723
7612
  : (translateLive > 0 && h('button', { className: 'paper-btn', type: 'button', disabled: busy, onClick: () => pauseAllTranslations() }, '暂停翻译')),
6724
7613
  (translateLive > 0 || translatePaused) && h('button', { className: 'paper-btn danger', type: 'button', disabled: busy, onClick: () => cancelAllTranslations() }, '取消翻译')),
6725
7614
  unresolved.map(job => h('article', { className: 'paper-card', key: job.id, 'data-job-kind': JOB_KINDS.parse },
6726
- h('div', { className: 'paper-row' }, h('div', null, h('div', { className: 'paper-name' }, job.pdfName || job.pdfPath), h('div', { className: 'paper-meta' }, job.error || '后台处理中')), h('span', { className: 'paper-status' }, jobKindLabel(job), ' · ', job.status)),
7615
+ h('div', { className: 'paper-row' }, h('div', null, h('div', { className: 'paper-name' }, job.pdfName || job.pdfPath), h('div', { className: 'paper-meta' }, jobMetaText(job))), h('span', { className: 'paper-status' }, jobKindLabel(job), ' · ', job.status)),
6727
7616
  RETRYABLE_STATUSES.includes(job.status) && h('button', { className: 'paper-btn', type: 'button', disabled: busy, onClick: () => retry(job.id) }, '↻ 重新解析'))),
6728
7617
  // 翻译任务卡片。角标与解析卡片共用同一套 status 文案,但按钮是另一组 ——
6729
7618
  // 翻译在跑时能暂停/取消(远程调用有成本),停了之后能重新触发或只重试失败的那部分。
@@ -6735,7 +7624,7 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6735
7624
  // 第二下又落回同一条分支,请求**从来没发出去过**。
6736
7625
  const cancelArmed = armed === `cancel-translate:${job.documentId}`
6737
7626
  return h('article', { className: 'paper-card', key: job.id, 'data-job-kind': JOB_KINDS.translate },
6738
- h('div', { className: 'paper-row' }, h('div', null, h('div', { className: 'paper-name' }, job.pdfName || job.pdfPath), h('div', { className: 'paper-meta' }, job.error || '后台翻译中')), h('span', { className: 'paper-status' }, jobKindLabel(job), ' · ', job.status)),
7627
+ h('div', { className: 'paper-row' }, h('div', null, h('div', { className: 'paper-name' }, job.pdfName || job.pdfPath), h('div', { className: 'paper-meta' }, jobMetaText(job))), h('span', { className: 'paper-status' }, jobKindLabel(job), ' · ', job.status)),
6739
7628
  actions.length === 0 ? null : h('div', { className: 'paper-actions' },
6740
7629
  actions.includes('translate') && h('button', { className: 'paper-btn primary', type: 'button', disabled: busy, onClick: () => translateIncremental(job.documentId), 'aria-label': `翻译 ${job.pdfName || job.pdfPath}` }, '翻译'),
6741
7630
  actions.includes('translateAll') && h('button', { className: 'paper-btn', type: 'button', disabled: busy, onClick: () => translate(job.documentId), 'aria-label': `整篇重译 ${job.pdfName || job.pdfPath}` }, '整篇重译'),
@@ -6850,8 +7739,10 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6850
7739
  readerNotice !== '' && h('div', { className: 'paper-notice', role: 'status' }, readerNotice),
6851
7740
  isPdfPane(paneView) && readerId !== '' && h('div', { className: 'paper-pdf-controls', 'aria-label': 'PDF 阅读控制' },
6852
7741
  h('button', { className: 'paper-btn', type: 'button', disabled: currentPage <= 1, onClick: () => changePdfPage(currentPage - 1) }, '上一页'),
6853
- h('span', {}, '第 ' + currentPage + ' / ' + (pdfData?.documentId === readerId ? pdfData.pageCount : readerLastPage) + ' 页'),
6854
- h('button', { className: 'paper-btn', type: 'button', disabled: currentPage >= (pdfData?.documentId === readerId ? pdfData.pageCount : readerLastPage), onClick: () => changePdfPage(currentPage + 1) }, '下一页'),
7742
+ h('span', {}, '第 ' + currentPage + ' / ' + pdfTotal + ' 页'),
7743
+ // 🔴 按钮保留(用户裁定):连续滚动下它不再是"换一份数据",而是把容器滚到下一页
7744
+ // 的页顶 —— 与滚轮共用同一个滚动位置,两种操作不可能各说一套。
7745
+ h('button', { className: 'paper-btn', type: 'button', disabled: currentPage >= pdfTotal, onClick: () => changePdfPage(currentPage + 1) }, '下一页'),
6855
7746
  h('button', { className: 'paper-btn', type: 'button', 'aria-label': '缩小 PDF', disabled: pdfZoom <= 0.5, onClick: () => setPdfZoom(value => Math.max(0.5, value - 0.25)) }, '−'),
6856
7747
  h('button', { className: 'paper-btn', type: 'button', 'aria-label': 'PDF 适合宽度', onClick: () => setPdfZoom(1) }, Math.round(pdfZoom * 100) + '%'),
6857
7748
  h('button', { className: 'paper-btn', type: 'button', 'aria-label': '放大 PDF', disabled: pdfZoom >= 3, onClick: () => setPdfZoom(value => Math.min(3, value + 0.25)) }, '+'),
@@ -6882,7 +7773,9 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
6882
7773
  onMouseOver: onCiteOver,
6883
7774
  onMouseOut: onCiteOut,
6884
7775
  // 阅读位置靠这条(D163):正文自己的滚动容器才知道"视口上沿那一块"是谁。
6885
- onScroll: isPdfPane(paneView) ? undefined : onReaderScroll,
7776
+ // 🔴 PDF 原页档也挂(连续滚动):这一档的滚动位置就是"我在第几页",
7777
+ // 不挂的话滚到第 5 页而当前页还停在第 1 页,页栈窗口不跟着走,屏幕会空。
7778
+ onScroll: onReaderScroll,
6886
7779
  onMouseUp: isPdfPane(paneView) ? event => {
6887
7780
  const selection = window.getSelection?.()
6888
7781
  const focus = selection?.focusNode
@@ -10236,6 +11129,8 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
10236
11129
  // 任务类别的判据(与宿主侧 jobKindOf 同义),供 test/queue.test.js 直接断言。
10237
11130
  exports.jobKindOf = jobKindOf
10238
11131
  exports.jobKindLabel = jobKindLabel
11132
+ // 卡片副标题(含任务编号),供 test/queue.test.js 直接断言。
11133
+ exports.jobMetaText = jobMetaText
10239
11134
  exports.translationActions = translationActions
10240
11135
  exports.scanReport = scanReport
10241
11136
  // 「浏览文件」的回执文案(D182),test/add-report.test.js 直接断言。
@@ -10262,6 +11157,16 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
10262
11157
  exports.readingCursorOf = readingCursorOf
10263
11158
  exports.readerResumeOf = readerResumeOf
10264
11159
  exports.progressOf = progressOf
11160
+ // PDF 原页页栈(连续滚动):页身份键 / 挂载窗口 / 宽高比 / 滚动位置→页码。
11161
+ // 四个都是纯函数,测试直接喂数据断言,不经 DOM。
11162
+ exports.pdfStackKey = pdfStackKey
11163
+ exports.pdfPageWindow = pdfPageWindow
11164
+ exports.pdfPageAspectOf = pdfPageAspectOf
11165
+ exports.pdfPageAt = pdfPageAt
11166
+ // 字形宽度缓存(连续滚动的性能关键):逐字符对齐每页要量一万六千次,去重后省 88%。
11167
+ exports.glyphWidthOf = glyphWidthOf
11168
+ exports.glyphWidthCache = glyphWidthCache
11169
+ exports.GLYPH_CACHE_LIMIT = GLYPH_CACHE_LIMIT
10265
11170
  // 划线与笔记(T19)的纯函数:分组只认 exact,面板不筛 anchor。
10266
11171
  exports.markGroups = markGroups
10267
11172
  exports.noteRows = noteRows
@@ -10270,6 +11175,9 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
10270
11175
  // 文本级高亮(D167)的纯函数:显示文本里的原话区间、每块的第一条计划、跨块夹回、
10271
11176
  // 挂高亮的核心过程(scope/names 进出,测试喂假 DOM)。
10272
11177
  exports.quoteSpanPlan = quoteSpanPlan
11178
+ exports.locateQuoteIgnoringSpace = locateQuoteIgnoringSpace
11179
+ exports.locateQuoteAcrossFormulas = locateQuoteAcrossFormulas
11180
+ exports.formulaSplit = formulaSplit
10273
11181
  // 中英匹配(D171):句级切分与跨列映射,测试直接喂中英两列断言。
10274
11182
  exports.sentenceSpans = sentenceSpans
10275
11183
  exports.crossSentenceSpan = crossSentenceSpan
@@ -10375,6 +11283,8 @@ h4.paper-reader-block{font-size:13px;font-weight:650}
10375
11283
  exports.pageImageUrl = pageImageUrl
10376
11284
  // D150:行内 HTML 的显示改写。纯函数,单测直接喂真实论文里的那两行。
10377
11285
  exports.displayInlineHtml = displayInlineHtml
11286
+ // 图注里的行内公式切分(纯文本块也要让 `$…$` 过 KaTeX):纯函数,单测直接喂真实图注。
11287
+ exports.captionPieces = captionPieces
10378
11288
  return module.exports
10379
11289
  },
10380
11290
  })