@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
@@ -47,6 +47,22 @@
47
47
  return jobKindOf(job) === JOB_KINDS.translate ? '翻译' : '解析'
48
48
  }
49
49
 
50
+ // 卡片副标题:失败/中断时给原因,在跑时给「后台处理中」,并在有任务编号时把它露出来。
51
+ //
52
+ // 🔴 为什么要把编号显示给用户:模型回执里给的是**任务编号**,用户拿着它去问
53
+ // 「那批解析到哪了」时,得有个地方能看见同一个编号 —— 否则那个编号只存在于
54
+ // 聊天记录里,和面板对不上。翻译任务没有编号(不进任务清单),所以只加在解析卡片上。
55
+ function jobMetaText(job) {
56
+ const reason = typeof job?.error === 'string' && job.error !== ''
57
+ ? job.error
58
+ : (jobKindOf(job) === JOB_KINDS.translate ? '后台翻译中' : '后台处理中')
59
+ // 只有解析任务进任务清单,翻译任务的编号即使被塞进来也不显示 —— 那个编号查不到东西。
60
+ const taskId = jobKindOf(job) === JOB_KINDS.parse && typeof job?.taskId === 'string' && job.taskId !== ''
61
+ ? job.taskId
62
+ : ''
63
+ return taskId === '' ? reason : reason + ' · 编号 ' + taskId
64
+ }
65
+
50
66
  // 一条翻译任务当前能做什么。纯函数,单测直接断言。
51
67
  //
52
68
  // 翻译是远程模型调用、有成本,所以按钮比解析那边收敛:
@@ -400,9 +416,19 @@
400
416
  }
401
417
  const payload = readerPayloadOf(block, sourceText, id)
402
418
  // 参考文献块自己**就是**跳转目标:它的 [7] 指向自己,标出来只会让人点了个原地不动。
403
- const parts = payload.markdown === true && row.kind !== 'references'
404
- ? inlineRefs(sourceText, numbers).map((part, at) => inlinePart(part, index, at))
405
- : []
419
+ //
420
+ // 🔴 **编号制没认出任何标记时才走作者-年份制**,判据是「有没有非 text 片段」而不是
421
+ // 「数组是不是空的」:没有编号的段落,inlineRefs 返回的是 `[{type:'text', …}]` ——
422
+ // 数组非空,但一个标记都没有。早先按长度判,于是作者-年份那一路在生产路径上**永远
423
+ // 不执行**:测试直接调 inlineAuthors 所以一直是绿的,界面上却怎么点都没反应。
424
+ let parts = []
425
+ if (payload.markdown === true && row.kind !== 'references') {
426
+ const numbered = inlineRefs(sourceText, numbers)
427
+ const cited = numbered.some(part => part.type !== 'text')
428
+ ? numbered
429
+ : inlineAuthors(sourceText, numbers?.authorYears)
430
+ parts = cited.map((part, at) => inlinePart(part, index, at))
431
+ }
406
432
  row.inline = { parts, source: parts.length > 0 ? sourceText : '' }
407
433
  row.zhText = translated.text
408
434
  row.zhRaw = translated.raw
@@ -442,9 +468,14 @@
442
468
  value: part.value ?? '',
443
469
  text: part.text ?? '',
444
470
  }
445
- // 单编号不带这两项时**不补空值**:既有断言按字段全等,多一个 raw: undefined 也会红。
471
+ // 不带的字段**不补空值**:既有断言按字段全等,多一个 raw: undefined 也会红。
446
472
  if (part.raw !== undefined) shape.raw = part.raw
447
473
  if (part.items !== undefined) shape.items = part.items
474
+ // 🔴 作者-年份制靠这两项才能落到 DOM 上:paintCiteSpans 把它们写成 data-cite-surname /
475
+ // data-cite-year,showCite 再用这对键查浮层。丢了就只有标记没有内容 —— 悬停毫无反应,
476
+ // 而且不报错。与 raw/items 被丢是同一类问题,只是那一次丢的是编号制。
477
+ if (part.surname !== undefined) shape.surname = part.surname
478
+ if (part.year !== undefined) shape.year = part.year
448
479
  return shape
449
480
  }
450
481
 
@@ -645,6 +676,19 @@
645
676
  }
646
677
  }
647
678
 
679
+ /**
680
+ * 一个块在某一页上的**完整正文**(所有 part 合起来)。
681
+ *
682
+ * 🔴 块可能被拆成多段 DOM(见宿主 pdf-page.js 的 splitRuns),但划线校验、
683
+ * 高亮定位、引用识别都按**整块**做 —— 只取第一段会漏掉被图或公式隔开的另一半。
684
+ * 与宿主 pdfBlockText 同口径:有 fullText 就用它,否则把各段拼起来。
685
+ */
686
+ function pdfBlockTextOf(groups, blockId) {
687
+ const parts = (Array.isArray(groups) ? groups : []).filter(group => group?.id === blockId)
688
+ if (parts.length === 0) return ''
689
+ return parts[0].fullText ?? parts.map(part => part.text).join(' ')
690
+ }
691
+
648
692
  /**
649
693
  * 将 PDFium 原生字符的每个起点转换成浏览器可渲染的字符推进宽度。
650
694
  * 单词字体、字重、连字均不可假定等于浏览器 serif,所以不能再让
@@ -1008,6 +1052,218 @@
1008
1052
  * 相反,译文上划的线(offset = -1)照样能在 zhText 里精确定位。围栏内容整段跳过 ——
1009
1053
  * 高亮 Range 落进代码块没有视觉语义,还会把行号 / 高亮会话搅乱。
1010
1054
  */
1055
+ /** 空白字符集:行接缝的补空格、软连字符、零宽字符。与宿主 pdfQuoteInText 同口径。 */
1056
+ const spaceRun = () => /[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu
1057
+ /** 单个字符是不是空白(含软连字符、零宽字符)。逐字符判断,不碰正则状态。 */
1058
+ const isSpaceChar = ch => ch === undefined || /[\s\u00ad\u200b\u200c\u200d\ufeff]/.test(ch)
1059
+
1060
+ /**
1061
+ * 忽略空白地在一段文本里定位原话,返回在**原文本**里的起止下标。
1062
+ *
1063
+ * 🔴 为什么绘制侧也需要它:PDF 档的文字层是逐词、逐字符的 span 拼出来的,行与行之间
1064
+ * **一个分隔符都没有**(每行是 display:block 的绝对定位元素),而 mark.quote 来自服务端
1065
+ * 的 group.text —— 那份在**行接缝补一个空格**。于是同一次拖选在两侧差着几个空格:
1066
+ * 实测 ResNet 第 2 页 `…problem by introducing…`(702 字)对 `…problem byintroducing…`
1067
+ * (693 字),`display.indexOf(quote)` 必然落空,划线画不出来。
1068
+ *
1069
+ * 做法:把两侧的空白都去掉再找,然后用一张「去空白后的下标 → 原文本下标」的表把结果
1070
+ * 换算回去。区间两端向外吸附到完整词元,避免高亮停在半个词上。
1071
+ *
1072
+ * @param {string} text 屏上显示文本(原样,含它自己的空白)
1073
+ * @param {string} quote 原话(可能带另一种空白)
1074
+ * @returns {{start: number, end: number}|null} 原文本里的区间;对不上返回 null
1075
+ */
1076
+ function locateQuoteIgnoringSpace(text, quote) {
1077
+ if (text === '' || quote === '') return null
1078
+ // squeezed 去掉空白,index 记录每个保留字符在原文本里的下标。
1079
+ let squeezed = ''
1080
+ const index = []
1081
+ for (let at = 0; at < text.length; at++) {
1082
+ if (isSpaceChar(text[at])) continue
1083
+ squeezed += text[at]
1084
+ index.push(at)
1085
+ }
1086
+ const target = quote.replace(spaceRun(), '')
1087
+ if (target === '' || squeezed === '') return null
1088
+ const hit = squeezed.indexOf(target)
1089
+ if (hit < 0) return null
1090
+ const start = index[hit]
1091
+ const end = index[hit + target.length - 1] + 1
1092
+ return { start, end }
1093
+ }
1094
+
1095
+ /** 行内公式的源码形态:`$…$`(不跨行)。两端锚定量词,避免跨段乱匹配。 */
1096
+ const formulaSource = () => /(\$[^$\n]+\$)/g
1097
+
1098
+ /**
1099
+ * 把原话按**行内公式**切成「文字段 / 公式段」,再把公式当**通配**去匹配显示文本。
1100
+ *
1101
+ * 🔴 为什么要这样:同一条划线在两侧的文字形态不同,公式是其中唯一的硬分界。
1102
+ * · 原文栏的显示文本里,公式是 KaTeX 渲染物被 {@link formulaSelectionText} 换回的
1103
+ * **LaTeX 源码**(`$\mathcal{H}(\mathbf{x})$`);
1104
+ * · PDF 档的显示文本里,公式是**渲染后的字形**(`H(x)`);
1105
+ * · 两边的**普通文字**逐字相同(只差空白)。
1106
+ *
1107
+ * 实测 ResNet 第 2 页 `p2-p2`:原话来自 PDF 字形,含 `H(x)`;原文栏那份是
1108
+ * `$\mathcal{H}(\mathbf{x})$`。整串逐字对不上,但公式**之间**的文字段四段全中
1109
+ * (0 / 254 / 316 / 353)。所以只要认定「这一段是公式」,两侧就能对齐 ——
1110
+ * 不必去猜公式该渲染成什么。
1111
+ *
1112
+ * 用户裁定:公式是**原子单位**——选区碰到公式的任何一部分,整个公式一起高亮。
1113
+ * 通配区间的两端就落在公式边界上,天然满足这条。
1114
+ *
1115
+ * @param {string} text 屏上显示文本(原样)
1116
+ * @param {string} quote 原话(公式是 `$…$` 源码形态)
1117
+ * @returns {{start: number, end: number}|null} 显示文本里的区间;对不上返回 null
1118
+ */
1119
+ /** 去掉空白,同时留一张「压缩下标 → 原文下标」的表。 */
1120
+ function squeezeWithIndex(text) {
1121
+ let squeezed = ''
1122
+ const index = []
1123
+ for (let at = 0; at < text.length; at++) {
1124
+ if (isSpaceChar(text[at])) continue
1125
+ squeezed += text[at]
1126
+ index.push(at)
1127
+ }
1128
+ return { squeezed, index }
1129
+ }
1130
+
1131
+ /**
1132
+ * 按 `$…$` 把一段文字切成「文字段 / 公式段」,返回**文字段**(公式段为 null)。
1133
+ * 奇数下标是公式。没有公式时返回 null —— 调用方据此判断这一侧能不能当模板。
1134
+ */
1135
+ function formulaSplit(text) {
1136
+ const pattern = formulaSource()
1137
+ if (!pattern.test(text)) return null
1138
+ // 🔴 正则**必须带捕获组**:String.split 在没有捕获组时会把分隔符整个丢掉,
1139
+ // 返回的只是文字段(['A ', ' B ', ' C']),公式位置根本没占位。
1140
+ // 旧实现用 map((p, i) => i % 2 === 0 ? p : null) 于是把下标 1 的**真文字**判成公式、
1141
+ // 三处公式全部丢失 —— 实测把 7 段切成 4 段,所有跨公式的划线定位失败。
1142
+ // 带捕获组后 split 返回 [文字, 公式, 文字, 公式, …],奇数位才是公式。
1143
+ return text.split(formulaSource()).map((piece, at) => at % 2 === 1 ? null : piece)
1144
+ }
1145
+
1146
+ /**
1147
+ * 一侧含行内公式、另一侧不含时,把**含公式的那侧**当模板切段,另一侧逐段定位。
1148
+ *
1149
+ * 🔴 方向是**双向**的,实测两种都真实存在:
1150
+ * · 划线取自 PDF 档 —— quote 是字形 `H(x)`(无 `$…$`),原文栏的 display 是
1151
+ * LaTeX 源码(3 处 `$…$`)。此时模板是 display。
1152
+ * · 划线取自原文栏 —— quote 带 `$…$` 源码,PDF 档的 display 是字形。此时模板是 quote。
1153
+ *
1154
+ * 先把模板的公式段换成通配,再用公式**之间**的文字段去另一侧依次定位;两侧都在
1155
+ * 压缩坐标(去空白)里走,最后换算回**目标文本**的原下标。
1156
+ *
1157
+ * 公式是原子单位(用户裁定):通配区间横跨整个公式,选区碰到哪一部分都整块高亮。
1158
+ *
1159
+ * @param {string} text 屏上显示文本(定位目标)
1160
+ * @param {string} quote 原话
1161
+ * @returns {{start: number, end: number}|null} 目标文本里的区间;对不上返回 null
1162
+ */
1163
+ function locateQuoteAcrossFormulas(text, quote) {
1164
+ if (text === '' || quote === '') return null
1165
+ const target = squeezeWithIndex(text)
1166
+ if (target.squeezed === '') return null
1167
+ // 两侧是否含 $…$。含公式的那一侧当**模板**切段,另一侧当**定位目标**。
1168
+ const quoteParts = formulaSplit(quote)
1169
+ const textParts = formulaSplit(text)
1170
+ if (quoteParts === null && textParts === null) return null
1171
+ const isText = piece => typeof piece === 'string' && piece !== ''
1172
+ const textPiecesOf = parts => parts.map(piece => piece === null ? null : piece.replace(spaceRun(), ''))
1173
+
1174
+ /**
1175
+ * 在 needle 里依次找 template 的各个文字段,返回覆盖到的**压缩坐标**区间。
1176
+ * 公式位不推进 —— 它只表示"这里跳过任意内容"。
1177
+ */
1178
+ const align = (needle, template) => {
1179
+ const wanted = textPiecesOf(template)
1180
+ const first = wanted.findIndex(isText)
1181
+ const last = wanted.length - 1 - [...wanted].reverse().findIndex(isText)
1182
+ if (first < 0) return null
1183
+ let cursor = needle.squeezed.indexOf(wanted[first])
1184
+ if (cursor < 0) return null
1185
+ const startAt = cursor
1186
+ cursor += wanted[first].length
1187
+ let endAt = cursor
1188
+ for (let at = first + 1; at <= last; at += 1) {
1189
+ const piece = wanted[at]
1190
+ if (piece === null) continue
1191
+ const found = needle.squeezed.indexOf(piece, cursor)
1192
+ if (found < 0) return null
1193
+ cursor = found + piece.length
1194
+ endAt = cursor
1195
+ }
1196
+ return { startAt, endAt }
1197
+ }
1198
+
1199
+ // 🔴 两种情形方向相反,必须分开写 —— 混用会让区间落在错误的坐标系上。
1200
+ let from
1201
+ let to
1202
+ if (textParts !== null && quoteParts === null) {
1203
+ // ① display 含公式、quote 不含(划线取自 PDF 档)。
1204
+ // quote 那侧的文字就是 display 文字段压缩后来的一份,先在 quote 里确认
1205
+ // 「这条划线覆盖到 display 的第几段」——对不上就说明不是同一段文字。
1206
+ const quoteTarget = squeezeWithIndex(quote)
1207
+ if (align(quoteTarget, textParts) === null) return null
1208
+ // 🔴 区间取 **display 自己**的范围:从第一段文字的开头到最后一段文字的结尾。
1209
+ // 中间那些公式段原样落在区间里,天然被整块包住 —— 这正是「公式是原子」
1210
+ // 要的效果,也不需要任何坐标换算(换算过一次,两次都算错)。
1211
+ // 带捕获组的 split 直接给出 [文字, 公式源码, 文字, …],按真实长度累加即可 ——
1212
+ // 不需要再猜公式段有多长。
1213
+ const shape = text.split(formulaSource())
1214
+ const isTextSeg = (piece, at) => at % 2 === 0 && piece !== ''
1215
+ const firstIdx = shape.findIndex(isTextSeg)
1216
+ const lastIdx = shape.length - 1 - [...shape].reverse().findIndex(isTextSeg)
1217
+ if (firstIdx < 0 || lastIdx < firstIdx) return null
1218
+ let cursorAt = 0
1219
+ let startPx = -1
1220
+ let endPx = -1
1221
+ for (let at = 0; at < shape.length; at += 1) {
1222
+ if (at === firstIdx) startPx = cursorAt
1223
+ cursorAt += shape[at].length
1224
+ if (at === lastIdx) { endPx = cursorAt; break }
1225
+ }
1226
+ if (startPx < 0 || endPx <= startPx) return null
1227
+ from = startPx
1228
+ to = endPx
1229
+ } else if (quoteParts !== null && textParts === null) {
1230
+ // ② quote 含公式、display 不含(划线取自原文栏)。
1231
+ // 用 quote 的文字段去 **display** 里定位,直接得到 display 区间。
1232
+ const hit = align(target, quoteParts)
1233
+ if (hit === null) return null
1234
+ from = target.index[hit.startAt]
1235
+ to = target.index[hit.endAt - 1] + 1
1236
+ // 🔴 划线**以公式开头/结尾**时,那个公式在 display 里是 KaTeX 渲染后的纯文本
1237
+ // (没有 `$…$`),所以 align 只能从公式**之后**的那段文字起算 —— 起点于是落在
1238
+ // 公式右边,公式本身永远进不了区间。实测 ResNet p2-p3:整段划线以
1239
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 开头,区间被算成 `[40,228)`,公式被排除在外。
1240
+ // 判据是模板的**首/尾段为空串**:空 = 划线是从那个公式开始的(结束的)。
1241
+ // 把区间扩到 display 的对应端点 —— 不猜长度,只是把「公式被当成光标位置」补回来。
1242
+ if (quoteParts[0] === '') from = 0
1243
+ if (quoteParts[quoteParts.length - 1] === '') to = text.length
1244
+ } else {
1245
+ return null
1246
+ }
1247
+ if (!(to > from)) return null
1248
+ // 🔴 **公式原子化**(用户裁定):选区碰到公式的任何一部分,整个公式一起高亮。
1249
+ for (let guard = 0; guard < 32; guard += 1) {
1250
+ let grown = false
1251
+ // 🔴 正则**必须在循环外建一次**:每次 new 一个带 g 的正则,lastIndex 永远从 0 起,
1252
+ // exec 每次都返回第一个匹配 —— 这是死循环(实测把测试跑成超时、日志 0 字节)。
1253
+ const pattern = formulaSource()
1254
+ let hit
1255
+ while ((hit = pattern.exec(text)) !== null) {
1256
+ const formulaFrom = hit.index
1257
+ const formulaTo = hit.index + hit[0].length
1258
+ if (!(formulaFrom < to && formulaTo > from)) continue
1259
+ if (formulaFrom < from) { from = formulaFrom; grown = true }
1260
+ if (formulaTo > to) { to = formulaTo; grown = true }
1261
+ }
1262
+ if (!grown) break
1263
+ }
1264
+ return { start: from, end: to }
1265
+ }
1266
+
1011
1267
  function quoteSpanPlan(mark, text) {
1012
1268
  if (mark === null || typeof mark !== 'object' || mark.anchor !== 'exact') return null
1013
1269
  const display = typeof text === 'string' ? text : ''
@@ -1020,7 +1276,22 @@
1020
1276
  const at = locateQuoteInText(display, candidate, prefix, suffix)
1021
1277
  if (at >= 0) return { quote: candidate, start: at, end: at + candidate.length }
1022
1278
  }
1023
- // 🔴 逐字都对不上再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1279
+ // 🔴 逐字对不上先试**忽略空白**:PDF 文字层的行接缝没有分隔符,而原话那份有空格,
1280
+ // 同一次拖选两侧差着几个空格。这一步只放宽空白,别的字仍然要逐字对上。
1281
+ for (const candidate of quoteCandidates(quote)) {
1282
+ const span = locateQuoteIgnoringSpace(display, candidate)
1283
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1284
+ }
1285
+ // 🔴 再试**公式通配**:同一条划线在两侧的文字形态不同 —— 原文栏把公式还原成 LaTeX
1286
+ // 源码($\mathcal{H}(\mathbf{x})$),PDF 档是渲染后的字形(H(x))。公式之间的普通文字
1287
+ // 逐字相同,所以只认「这一段是公式」、把它当通配,两侧就能对齐(见
1288
+ // {@link locateQuoteAcrossFormulas})。用户裁定公式是**原子单位**:选区碰到哪一部分,
1289
+ // 整个公式一起高亮。
1290
+ for (const candidate of quoteCandidates(quote)) {
1291
+ const span = locateQuoteAcrossFormulas(display, candidate)
1292
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1293
+ }
1294
+ // 🔴 再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1024
1295
  // 只有**长原话**才走这一步 —— 短原话的首尾两截谁都能对上,夹出来的区间没有意义。
1025
1296
  for (const candidate of quoteCandidates(quote)) {
1026
1297
  const span = bracketSpan(display, candidate)
@@ -1426,13 +1697,46 @@
1426
1697
  const range = new Range()
1427
1698
  if (!locate(row.node, target.start, false, range) || !locate(row.node, target.end, true, range)) continue
1428
1699
  const got = range.toString()
1429
- if (!got || (direct ? got !== direct.quote : got.trim() !== got)) continue
1700
+ // 🔴 终验:**普通文字逐字相等**;含公式时按 {@link formulaSelectionText} 的口径比。
1701
+ //
1702
+ // KaTeX 把公式摊成「TeX 源码 + 渲染字形」留在 textContent 里(实测
1703
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 是 34 字源码 + 5 字字形),与 `$…$` 形态的
1704
+ // quote 永远不可能逐字相等。用严格相等的话,凡覆盖公式的划线都被这道终验拒掉 ——
1705
+ // 实测区间已算对(`[0,228)` 覆盖公式)却 `painted = 0`,整条划线一个字都不画。
1706
+ // 折符号也**不行**(实测折完 190 vs 184:`\mathcal`/`\mathbf` 的命令名留在 DOM 里,
1707
+ // 而 quote 那侧只有符号)—— 唯一正确的口径是把公式还原成 `$…$` 再比。
1708
+ const matches = () => {
1709
+ if (!got) return false
1710
+ if (!direct) return got.trim() === got
1711
+ if (got === direct.quote) return true
1712
+ if (!formulaSource().test(direct.quote) && !formulaSource().test(got)) return false
1713
+ const contents = range.cloneContents?.()
1714
+ if (!contents) return false
1715
+ return formulaSelectionText(contents).trim() === direct.quote.trim()
1716
+ }
1717
+ if (!matches()) continue
1430
1718
  const name = 'dsh-paper-mark-' + color
1431
1719
  let entry = names.get(name)
1432
1720
  if (!entry) { entry = { ranges: [], hits: [] }; names.set(name, entry) }
1433
1721
  entry.ranges.push(range)
1434
1722
  entry.hits ??= []
1435
1723
  entry.hits.push({ range, markId: mark.id })
1724
+ // 🔴 **公式整块上色**(用户裁定:公式是原子单位,选区碰到哪一部分都整块亮)。
1725
+ //
1726
+ // KaTeX 把一个公式渲染成两条臂:`.katex-mathml`(`annotation` 里的 TeX 源码,
1727
+ // 被 clip 成 1×1 摆在屏幕外)与 `.katex-html`(真正看得见的字形)。实测
1728
+ // ResNet p2-p3 的 `$\mathcal{F}(\mathbf{x})+\mathbf{x}$`:mathml 臂占 34 个字符、
1729
+ // html 臂只有 5 个(`F(x)+x`)。划线的区间按 DOM 字符算,**整段都落在 mathml 臂上**,
1730
+ // 于是浏览器把颜色涂在那 1×1 的不可见区域 —— 用户看到的就是「公式没高亮」。
1731
+ //
1732
+ // 补法:凡区间碰到的 `.katex`,另给它的 `.katex-html` 加一条整块 Range。
1733
+ // 与 PDF 档 `pdfQuoteInText` 的口径一致,也不动定位逻辑一个字。
1734
+ for (const formula of katexArmsIn(row.node, range)) {
1735
+ const arm = new Range()
1736
+ arm.selectNodeContents(formula)
1737
+ entry.ranges.push(arm)
1738
+ entry.hits.push({ range: arm, markId: mark.id })
1739
+ }
1436
1740
  painted += 1
1437
1741
  completed.set(row.node, completed.get(row.node) + 1)
1438
1742
  }
@@ -1446,6 +1750,31 @@
1446
1750
  return painted
1447
1751
  }
1448
1752
 
1753
+ /**
1754
+ * 一段 Range 碰到的所有 KaTeX 公式,返回各自**可见臂**(`.katex-html`)的根节点。
1755
+ *
1756
+ * 🔴 KaTeX 的 `.katex` 里有两条臂:`.katex-mathml`(无障碍树,TeX 源码,被 clip 成
1757
+ * 1×1 摆在屏幕外)与 `.katex-html`(可见字形)。划线的区间按 DOM 字符算,落在
1758
+ * mathml 臂上时浏览器会把颜色涂在那不可见的 1×1 区域 —— 用户看到「公式没高亮」。
1759
+ * 这里把碰到的公式找出来,交给调用方补一条覆盖可见臂的 Range(公式整块上色)。
1760
+ *
1761
+ * @param {unknown} node 块节点
1762
+ * @param {Range} range 已定位好的区间
1763
+ * @returns {Element[]} 可见臂节点(不可用的公式跳过)
1764
+ */
1765
+ function katexArmsIn(node, range) {
1766
+ const formulas = typeof node?.querySelectorAll === 'function' ? node.querySelectorAll('.katex') : []
1767
+ const arms = []
1768
+ for (const formula of formulas) {
1769
+ const arm = typeof formula?.querySelector === 'function' ? formula.querySelector('.katex-html') : null
1770
+ if (!arm) continue
1771
+ // 只要区间**碰到**这个公式就整块亮(用户裁定:公式是原子单位)。
1772
+ let touches = true
1773
+ try { touches = typeof range?.intersectsNode === 'function' ? range.intersectsNode(formula) : true } catch { touches = true }
1774
+ if (touches) arms.push(arm)
1775
+ }
1776
+ return arms
1777
+ }
1449
1778
  // KaTeX 同时包含无障碍树与可视树。克隆后用公式源码替换,避免把两份文字一起引用。
1450
1779
  function formulaSelectionText(node) {
1451
1780
  const clone = node.cloneNode(true)
@@ -1612,6 +1941,33 @@
1612
1941
  }
1613
1942
  }
1614
1943
 
1944
+ /**
1945
+ * 图注这类**纯文本块**里出现的行内公式:只把 `$…$` 那几段交给渲染器,其余照旧字面显示。
1946
+ *
1947
+ * 🔴 为什么图注不走整段 Markdown(见 readerBlockNode):图注不成文,整段过 Markdown 会让
1948
+ * 下划线变斜体、星号变强调("Figure 3 * p<0.05" 会被吃掉一半)。但**同时**图注里确实
1949
+ * 夹着公式 —— 实测 STITCH 的 Figure 2 图注是
1950
+ * `Thematic Scope $( \sigma _ { t } ) .$`,纯文本渲染的结果就是满屏的 `$(\sigma_{t})$`。
1951
+ * 所以按**公式边界**切开:公式段原样送进 MarkdownText(KaTeX 会渲染它),文字段照旧
1952
+ * 按纯文本显示。既保住了「图注不做强调解析」,也让公式真的排出来。
1953
+ *
1954
+ * @param {unknown} value 图注原文
1955
+ * @returns {Array<{text: string, math: boolean}>} 按顺序切出的片段;没有公式时只有一片
1956
+ */
1957
+ function captionPieces(value) {
1958
+ const text = String(value ?? '')
1959
+ const formula = /\$\$[\s\S]+?\$\$|\$(?!\s)[^$\n]+?\$/g
1960
+ const pieces = []
1961
+ let at = 0
1962
+ for (const match of text.matchAll(formula)) {
1963
+ if (match.index > at) pieces.push({ text: text.slice(at, match.index), math: false })
1964
+ pieces.push({ text: match[0], math: true })
1965
+ at = match.index + match[0].length
1966
+ }
1967
+ if (at < text.length) pieces.push({ text: text.slice(at), math: false })
1968
+ return pieces.length === 0 ? [{ text, math: false }] : pieces
1969
+ }
1970
+
1615
1971
  function renderSelectionText(value) {
1616
1972
  const text = String(value ?? '')
1617
1973
  const formula = /\$\$[\s\S]+?\$\$|\$(?!\s)[^$\n]+?\$/g
@@ -1743,7 +2099,7 @@
1743
2099
  * 只脱**行内排版**标签的壳、保留里面的文字。用白名单而不是「把所有尖括号都删掉」:
1744
2100
  * markdown 的自动链接写作尖括号包 URL,把尖括号一律当标签会把链接吃掉。
1745
2101
  */
1746
- 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
2102
+ 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
1747
2103
  const mapChars = (value, table) => Array.from(String(value), ch => table[ch] ?? ch).join('')
1748
2104
  /**
1749
2105
  * 把正文里的行内 HTML 换成等价的可读字符(D150)。
@@ -2449,6 +2805,53 @@
2449
2805
  + '&page=' + encodeURIComponent(String(page)) + '&width=' + width + (crop ? '&crop=1' : '')
2450
2806
  }
2451
2807
 
2808
+ /**
2809
+ * 字形宽度的测量缓存(连续滚动的性能关键之一)。
2810
+ *
2811
+ * 🔴 **为什么必须缓存**:逐字符对齐要对每个字符调一次 `canvas.measureText`。
2812
+ * 真实论文实测:一篇 9 页的论文共 16,491 个字符 —— 每页一万六千次**同步**测量。
2813
+ * 单页时代这样建一次还能接受;连续滚动下窗口里同时挂三页,一次重建就是近五万次
2814
+ * `measureText`,那是主线程直接卡住半秒的量级(滚轮会一顿一顿)。
2815
+ *
2816
+ * 🔴 **为什么缓存有效率极高**:同一篇论文里出现的不同字符只有 85 个,字号虽随行高
2817
+ * 浮动,但量化到 0.1px 之后只有二十来档 —— 去重上界约 2,000 次,比逐次测量省 88%。
2818
+ * 字体固定是 serif(与 CSS 的 `.paper-pdf-word` 一致),所以"同一字号 + 同一字串"
2819
+ * 的宽度是确定的,缓存不会失真。
2820
+ *
2821
+ * 量化到 0.1px 是刻意的:字号算出来是浮点(行高 × 页高 / 1000),不量化则几乎每个
2822
+ * 词的 key 都不同,缓存命中率会掉到接近 0。0.1px 的差异在屏幕上不可见,而选区宽度
2823
+ * 只由 `letter-spacing` 的**差值**决定,缩放时也不会累积误差。
2824
+ */
2825
+ const glyphWidthCache = new Map()
2826
+ /** 缓存上界:一篇论文 85 个字符 × 三十档字号也到不了 5,000,超了说明用法出问题了。 */
2827
+ const GLYPH_CACHE_LIMIT = 5000
2828
+ /**
2829
+ * 量一个字符串在某个字号下的宽度(带缓存)。
2830
+ *
2831
+ * @param {CanvasRenderingContext2D|null} context 测量用的 2d 上下文
2832
+ * @param {number} size 字号(px)
2833
+ * @param {string} text 要量的字串
2834
+ * @returns {number|null} 宽度;上下文不可用是 null(调用方据此跳过对齐,不编一个宽度)
2835
+ */
2836
+ function glyphWidthOf(context, size, text) {
2837
+ if (context === null || context === undefined) return null
2838
+ const pixels = Number(size)
2839
+ if (!Number.isFinite(pixels) || pixels <= 0) return null
2840
+ // 量化到 0.1px —— 不量化则每个词的 key 都不同,缓存等于没有(见上面的说明)。
2841
+ const quantized = Math.round(pixels * 10) / 10
2842
+ const key = quantized + '|' + text
2843
+ const hit = glyphWidthCache.get(key)
2844
+ if (hit !== undefined) return hit
2845
+ context.font = quantized + 'px serif'
2846
+ const measured = context.measureText(text).width
2847
+ if (!Number.isFinite(measured)) return null
2848
+ // 满了就整片清掉而不是逐条淘汰:条目本身很便宜(数字 + 短串),
2849
+ // 而一篇论文的字符集是稳定的,清掉之后下一轮的命中率依然高。
2850
+ if (glyphWidthCache.size >= GLYPH_CACHE_LIMIT) glyphWidthCache.clear()
2851
+ glyphWidthCache.set(key, measured)
2852
+ return measured
2853
+ }
2854
+
2452
2855
  /**
2453
2856
  * bbox(0–1000 归一化坐标) → overlay 的百分比样式。
2454
2857
  *