@li-canghai/dsh-paper 0.8.1 → 0.8.2

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.
@@ -1008,6 +1008,218 @@
1008
1008
  * 相反,译文上划的线(offset = -1)照样能在 zhText 里精确定位。围栏内容整段跳过 ——
1009
1009
  * 高亮 Range 落进代码块没有视觉语义,还会把行号 / 高亮会话搅乱。
1010
1010
  */
1011
+ /** 空白字符集:行接缝的补空格、软连字符、零宽字符。与宿主 pdfQuoteInText 同口径。 */
1012
+ const spaceRun = () => /[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu
1013
+ /** 单个字符是不是空白(含软连字符、零宽字符)。逐字符判断,不碰正则状态。 */
1014
+ const isSpaceChar = ch => ch === undefined || /[\s\u00ad\u200b\u200c\u200d\ufeff]/.test(ch)
1015
+
1016
+ /**
1017
+ * 忽略空白地在一段文本里定位原话,返回在**原文本**里的起止下标。
1018
+ *
1019
+ * 🔴 为什么绘制侧也需要它:PDF 档的文字层是逐词、逐字符的 span 拼出来的,行与行之间
1020
+ * **一个分隔符都没有**(每行是 display:block 的绝对定位元素),而 mark.quote 来自服务端
1021
+ * 的 group.text —— 那份在**行接缝补一个空格**。于是同一次拖选在两侧差着几个空格:
1022
+ * 实测 ResNet 第 2 页 `…problem by introducing…`(702 字)对 `…problem byintroducing…`
1023
+ * (693 字),`display.indexOf(quote)` 必然落空,划线画不出来。
1024
+ *
1025
+ * 做法:把两侧的空白都去掉再找,然后用一张「去空白后的下标 → 原文本下标」的表把结果
1026
+ * 换算回去。区间两端向外吸附到完整词元,避免高亮停在半个词上。
1027
+ *
1028
+ * @param {string} text 屏上显示文本(原样,含它自己的空白)
1029
+ * @param {string} quote 原话(可能带另一种空白)
1030
+ * @returns {{start: number, end: number}|null} 原文本里的区间;对不上返回 null
1031
+ */
1032
+ function locateQuoteIgnoringSpace(text, quote) {
1033
+ if (text === '' || quote === '') return null
1034
+ // squeezed 去掉空白,index 记录每个保留字符在原文本里的下标。
1035
+ let squeezed = ''
1036
+ const index = []
1037
+ for (let at = 0; at < text.length; at++) {
1038
+ if (isSpaceChar(text[at])) continue
1039
+ squeezed += text[at]
1040
+ index.push(at)
1041
+ }
1042
+ const target = quote.replace(spaceRun(), '')
1043
+ if (target === '' || squeezed === '') return null
1044
+ const hit = squeezed.indexOf(target)
1045
+ if (hit < 0) return null
1046
+ const start = index[hit]
1047
+ const end = index[hit + target.length - 1] + 1
1048
+ return { start, end }
1049
+ }
1050
+
1051
+ /** 行内公式的源码形态:`$…$`(不跨行)。两端锚定量词,避免跨段乱匹配。 */
1052
+ const formulaSource = () => /(\$[^$\n]+\$)/g
1053
+
1054
+ /**
1055
+ * 把原话按**行内公式**切成「文字段 / 公式段」,再把公式当**通配**去匹配显示文本。
1056
+ *
1057
+ * 🔴 为什么要这样:同一条划线在两侧的文字形态不同,公式是其中唯一的硬分界。
1058
+ * · 原文栏的显示文本里,公式是 KaTeX 渲染物被 {@link formulaSelectionText} 换回的
1059
+ * **LaTeX 源码**(`$\mathcal{H}(\mathbf{x})$`);
1060
+ * · PDF 档的显示文本里,公式是**渲染后的字形**(`H(x)`);
1061
+ * · 两边的**普通文字**逐字相同(只差空白)。
1062
+ *
1063
+ * 实测 ResNet 第 2 页 `p2-p2`:原话来自 PDF 字形,含 `H(x)`;原文栏那份是
1064
+ * `$\mathcal{H}(\mathbf{x})$`。整串逐字对不上,但公式**之间**的文字段四段全中
1065
+ * (0 / 254 / 316 / 353)。所以只要认定「这一段是公式」,两侧就能对齐 ——
1066
+ * 不必去猜公式该渲染成什么。
1067
+ *
1068
+ * 用户裁定:公式是**原子单位**——选区碰到公式的任何一部分,整个公式一起高亮。
1069
+ * 通配区间的两端就落在公式边界上,天然满足这条。
1070
+ *
1071
+ * @param {string} text 屏上显示文本(原样)
1072
+ * @param {string} quote 原话(公式是 `$…$` 源码形态)
1073
+ * @returns {{start: number, end: number}|null} 显示文本里的区间;对不上返回 null
1074
+ */
1075
+ /** 去掉空白,同时留一张「压缩下标 → 原文下标」的表。 */
1076
+ function squeezeWithIndex(text) {
1077
+ let squeezed = ''
1078
+ const index = []
1079
+ for (let at = 0; at < text.length; at++) {
1080
+ if (isSpaceChar(text[at])) continue
1081
+ squeezed += text[at]
1082
+ index.push(at)
1083
+ }
1084
+ return { squeezed, index }
1085
+ }
1086
+
1087
+ /**
1088
+ * 按 `$…$` 把一段文字切成「文字段 / 公式段」,返回**文字段**(公式段为 null)。
1089
+ * 奇数下标是公式。没有公式时返回 null —— 调用方据此判断这一侧能不能当模板。
1090
+ */
1091
+ function formulaSplit(text) {
1092
+ const pattern = formulaSource()
1093
+ if (!pattern.test(text)) return null
1094
+ // 🔴 正则**必须带捕获组**:String.split 在没有捕获组时会把分隔符整个丢掉,
1095
+ // 返回的只是文字段(['A ', ' B ', ' C']),公式位置根本没占位。
1096
+ // 旧实现用 map((p, i) => i % 2 === 0 ? p : null) 于是把下标 1 的**真文字**判成公式、
1097
+ // 三处公式全部丢失 —— 实测把 7 段切成 4 段,所有跨公式的划线定位失败。
1098
+ // 带捕获组后 split 返回 [文字, 公式, 文字, 公式, …],奇数位才是公式。
1099
+ return text.split(formulaSource()).map((piece, at) => at % 2 === 1 ? null : piece)
1100
+ }
1101
+
1102
+ /**
1103
+ * 一侧含行内公式、另一侧不含时,把**含公式的那侧**当模板切段,另一侧逐段定位。
1104
+ *
1105
+ * 🔴 方向是**双向**的,实测两种都真实存在:
1106
+ * · 划线取自 PDF 档 —— quote 是字形 `H(x)`(无 `$…$`),原文栏的 display 是
1107
+ * LaTeX 源码(3 处 `$…$`)。此时模板是 display。
1108
+ * · 划线取自原文栏 —— quote 带 `$…$` 源码,PDF 档的 display 是字形。此时模板是 quote。
1109
+ *
1110
+ * 先把模板的公式段换成通配,再用公式**之间**的文字段去另一侧依次定位;两侧都在
1111
+ * 压缩坐标(去空白)里走,最后换算回**目标文本**的原下标。
1112
+ *
1113
+ * 公式是原子单位(用户裁定):通配区间横跨整个公式,选区碰到哪一部分都整块高亮。
1114
+ *
1115
+ * @param {string} text 屏上显示文本(定位目标)
1116
+ * @param {string} quote 原话
1117
+ * @returns {{start: number, end: number}|null} 目标文本里的区间;对不上返回 null
1118
+ */
1119
+ function locateQuoteAcrossFormulas(text, quote) {
1120
+ if (text === '' || quote === '') return null
1121
+ const target = squeezeWithIndex(text)
1122
+ if (target.squeezed === '') return null
1123
+ // 两侧是否含 $…$。含公式的那一侧当**模板**切段,另一侧当**定位目标**。
1124
+ const quoteParts = formulaSplit(quote)
1125
+ const textParts = formulaSplit(text)
1126
+ if (quoteParts === null && textParts === null) return null
1127
+ const isText = piece => typeof piece === 'string' && piece !== ''
1128
+ const textPiecesOf = parts => parts.map(piece => piece === null ? null : piece.replace(spaceRun(), ''))
1129
+
1130
+ /**
1131
+ * 在 needle 里依次找 template 的各个文字段,返回覆盖到的**压缩坐标**区间。
1132
+ * 公式位不推进 —— 它只表示"这里跳过任意内容"。
1133
+ */
1134
+ const align = (needle, template) => {
1135
+ const wanted = textPiecesOf(template)
1136
+ const first = wanted.findIndex(isText)
1137
+ const last = wanted.length - 1 - [...wanted].reverse().findIndex(isText)
1138
+ if (first < 0) return null
1139
+ let cursor = needle.squeezed.indexOf(wanted[first])
1140
+ if (cursor < 0) return null
1141
+ const startAt = cursor
1142
+ cursor += wanted[first].length
1143
+ let endAt = cursor
1144
+ for (let at = first + 1; at <= last; at += 1) {
1145
+ const piece = wanted[at]
1146
+ if (piece === null) continue
1147
+ const found = needle.squeezed.indexOf(piece, cursor)
1148
+ if (found < 0) return null
1149
+ cursor = found + piece.length
1150
+ endAt = cursor
1151
+ }
1152
+ return { startAt, endAt }
1153
+ }
1154
+
1155
+ // 🔴 两种情形方向相反,必须分开写 —— 混用会让区间落在错误的坐标系上。
1156
+ let from
1157
+ let to
1158
+ if (textParts !== null && quoteParts === null) {
1159
+ // ① display 含公式、quote 不含(划线取自 PDF 档)。
1160
+ // quote 那侧的文字就是 display 文字段压缩后来的一份,先在 quote 里确认
1161
+ // 「这条划线覆盖到 display 的第几段」——对不上就说明不是同一段文字。
1162
+ const quoteTarget = squeezeWithIndex(quote)
1163
+ if (align(quoteTarget, textParts) === null) return null
1164
+ // 🔴 区间取 **display 自己**的范围:从第一段文字的开头到最后一段文字的结尾。
1165
+ // 中间那些公式段原样落在区间里,天然被整块包住 —— 这正是「公式是原子」
1166
+ // 要的效果,也不需要任何坐标换算(换算过一次,两次都算错)。
1167
+ // 带捕获组的 split 直接给出 [文字, 公式源码, 文字, …],按真实长度累加即可 ——
1168
+ // 不需要再猜公式段有多长。
1169
+ const shape = text.split(formulaSource())
1170
+ const isTextSeg = (piece, at) => at % 2 === 0 && piece !== ''
1171
+ const firstIdx = shape.findIndex(isTextSeg)
1172
+ const lastIdx = shape.length - 1 - [...shape].reverse().findIndex(isTextSeg)
1173
+ if (firstIdx < 0 || lastIdx < firstIdx) return null
1174
+ let cursorAt = 0
1175
+ let startPx = -1
1176
+ let endPx = -1
1177
+ for (let at = 0; at < shape.length; at += 1) {
1178
+ if (at === firstIdx) startPx = cursorAt
1179
+ cursorAt += shape[at].length
1180
+ if (at === lastIdx) { endPx = cursorAt; break }
1181
+ }
1182
+ if (startPx < 0 || endPx <= startPx) return null
1183
+ from = startPx
1184
+ to = endPx
1185
+ } else if (quoteParts !== null && textParts === null) {
1186
+ // ② quote 含公式、display 不含(划线取自原文栏)。
1187
+ // 用 quote 的文字段去 **display** 里定位,直接得到 display 区间。
1188
+ const hit = align(target, quoteParts)
1189
+ if (hit === null) return null
1190
+ from = target.index[hit.startAt]
1191
+ to = target.index[hit.endAt - 1] + 1
1192
+ // 🔴 划线**以公式开头/结尾**时,那个公式在 display 里是 KaTeX 渲染后的纯文本
1193
+ // (没有 `$…$`),所以 align 只能从公式**之后**的那段文字起算 —— 起点于是落在
1194
+ // 公式右边,公式本身永远进不了区间。实测 ResNet p2-p3:整段划线以
1195
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 开头,区间被算成 `[40,228)`,公式被排除在外。
1196
+ // 判据是模板的**首/尾段为空串**:空 = 划线是从那个公式开始的(结束的)。
1197
+ // 把区间扩到 display 的对应端点 —— 不猜长度,只是把「公式被当成光标位置」补回来。
1198
+ if (quoteParts[0] === '') from = 0
1199
+ if (quoteParts[quoteParts.length - 1] === '') to = text.length
1200
+ } else {
1201
+ return null
1202
+ }
1203
+ if (!(to > from)) return null
1204
+ // 🔴 **公式原子化**(用户裁定):选区碰到公式的任何一部分,整个公式一起高亮。
1205
+ for (let guard = 0; guard < 32; guard += 1) {
1206
+ let grown = false
1207
+ // 🔴 正则**必须在循环外建一次**:每次 new 一个带 g 的正则,lastIndex 永远从 0 起,
1208
+ // exec 每次都返回第一个匹配 —— 这是死循环(实测把测试跑成超时、日志 0 字节)。
1209
+ const pattern = formulaSource()
1210
+ let hit
1211
+ while ((hit = pattern.exec(text)) !== null) {
1212
+ const formulaFrom = hit.index
1213
+ const formulaTo = hit.index + hit[0].length
1214
+ if (!(formulaFrom < to && formulaTo > from)) continue
1215
+ if (formulaFrom < from) { from = formulaFrom; grown = true }
1216
+ if (formulaTo > to) { to = formulaTo; grown = true }
1217
+ }
1218
+ if (!grown) break
1219
+ }
1220
+ return { start: from, end: to }
1221
+ }
1222
+
1011
1223
  function quoteSpanPlan(mark, text) {
1012
1224
  if (mark === null || typeof mark !== 'object' || mark.anchor !== 'exact') return null
1013
1225
  const display = typeof text === 'string' ? text : ''
@@ -1020,7 +1232,22 @@
1020
1232
  const at = locateQuoteInText(display, candidate, prefix, suffix)
1021
1233
  if (at >= 0) return { quote: candidate, start: at, end: at + candidate.length }
1022
1234
  }
1023
- // 🔴 逐字都对不上再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1235
+ // 🔴 逐字对不上先试**忽略空白**:PDF 文字层的行接缝没有分隔符,而原话那份有空格,
1236
+ // 同一次拖选两侧差着几个空格。这一步只放宽空白,别的字仍然要逐字对上。
1237
+ for (const candidate of quoteCandidates(quote)) {
1238
+ const span = locateQuoteIgnoringSpace(display, candidate)
1239
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1240
+ }
1241
+ // 🔴 再试**公式通配**:同一条划线在两侧的文字形态不同 —— 原文栏把公式还原成 LaTeX
1242
+ // 源码($\mathcal{H}(\mathbf{x})$),PDF 档是渲染后的字形(H(x))。公式之间的普通文字
1243
+ // 逐字相同,所以只认「这一段是公式」、把它当通配,两侧就能对齐(见
1244
+ // {@link locateQuoteAcrossFormulas})。用户裁定公式是**原子单位**:选区碰到哪一部分,
1245
+ // 整个公式一起高亮。
1246
+ for (const candidate of quoteCandidates(quote)) {
1247
+ const span = locateQuoteAcrossFormulas(display, candidate)
1248
+ if (span !== null) return { quote: display.slice(span.start, span.end), start: span.start, end: span.end }
1249
+ }
1250
+ // 🔴 再试括号法:公式段的选区串是 KaTeX 两条渲染臂拼的,永远逐字对不上。
1024
1251
  // 只有**长原话**才走这一步 —— 短原话的首尾两截谁都能对上,夹出来的区间没有意义。
1025
1252
  for (const candidate of quoteCandidates(quote)) {
1026
1253
  const span = bracketSpan(display, candidate)
@@ -1426,13 +1653,46 @@
1426
1653
  const range = new Range()
1427
1654
  if (!locate(row.node, target.start, false, range) || !locate(row.node, target.end, true, range)) continue
1428
1655
  const got = range.toString()
1429
- if (!got || (direct ? got !== direct.quote : got.trim() !== got)) continue
1656
+ // 🔴 终验:**普通文字逐字相等**;含公式时按 {@link formulaSelectionText} 的口径比。
1657
+ //
1658
+ // KaTeX 把公式摊成「TeX 源码 + 渲染字形」留在 textContent 里(实测
1659
+ // `$\mathcal{F}(\mathbf{x})+\mathbf{x}$` 是 34 字源码 + 5 字字形),与 `$…$` 形态的
1660
+ // quote 永远不可能逐字相等。用严格相等的话,凡覆盖公式的划线都被这道终验拒掉 ——
1661
+ // 实测区间已算对(`[0,228)` 覆盖公式)却 `painted = 0`,整条划线一个字都不画。
1662
+ // 折符号也**不行**(实测折完 190 vs 184:`\mathcal`/`\mathbf` 的命令名留在 DOM 里,
1663
+ // 而 quote 那侧只有符号)—— 唯一正确的口径是把公式还原成 `$…$` 再比。
1664
+ const matches = () => {
1665
+ if (!got) return false
1666
+ if (!direct) return got.trim() === got
1667
+ if (got === direct.quote) return true
1668
+ if (!formulaSource().test(direct.quote) && !formulaSource().test(got)) return false
1669
+ const contents = range.cloneContents?.()
1670
+ if (!contents) return false
1671
+ return formulaSelectionText(contents).trim() === direct.quote.trim()
1672
+ }
1673
+ if (!matches()) continue
1430
1674
  const name = 'dsh-paper-mark-' + color
1431
1675
  let entry = names.get(name)
1432
1676
  if (!entry) { entry = { ranges: [], hits: [] }; names.set(name, entry) }
1433
1677
  entry.ranges.push(range)
1434
1678
  entry.hits ??= []
1435
1679
  entry.hits.push({ range, markId: mark.id })
1680
+ // 🔴 **公式整块上色**(用户裁定:公式是原子单位,选区碰到哪一部分都整块亮)。
1681
+ //
1682
+ // KaTeX 把一个公式渲染成两条臂:`.katex-mathml`(`annotation` 里的 TeX 源码,
1683
+ // 被 clip 成 1×1 摆在屏幕外)与 `.katex-html`(真正看得见的字形)。实测
1684
+ // ResNet p2-p3 的 `$\mathcal{F}(\mathbf{x})+\mathbf{x}$`:mathml 臂占 34 个字符、
1685
+ // html 臂只有 5 个(`F(x)+x`)。划线的区间按 DOM 字符算,**整段都落在 mathml 臂上**,
1686
+ // 于是浏览器把颜色涂在那 1×1 的不可见区域 —— 用户看到的就是「公式没高亮」。
1687
+ //
1688
+ // 补法:凡区间碰到的 `.katex`,另给它的 `.katex-html` 加一条整块 Range。
1689
+ // 与 PDF 档 `pdfQuoteInText` 的口径一致,也不动定位逻辑一个字。
1690
+ for (const formula of katexArmsIn(row.node, range)) {
1691
+ const arm = new Range()
1692
+ arm.selectNodeContents(formula)
1693
+ entry.ranges.push(arm)
1694
+ entry.hits.push({ range: arm, markId: mark.id })
1695
+ }
1436
1696
  painted += 1
1437
1697
  completed.set(row.node, completed.get(row.node) + 1)
1438
1698
  }
@@ -1446,6 +1706,31 @@
1446
1706
  return painted
1447
1707
  }
1448
1708
 
1709
+ /**
1710
+ * 一段 Range 碰到的所有 KaTeX 公式,返回各自**可见臂**(`.katex-html`)的根节点。
1711
+ *
1712
+ * 🔴 KaTeX 的 `.katex` 里有两条臂:`.katex-mathml`(无障碍树,TeX 源码,被 clip 成
1713
+ * 1×1 摆在屏幕外)与 `.katex-html`(可见字形)。划线的区间按 DOM 字符算,落在
1714
+ * mathml 臂上时浏览器会把颜色涂在那不可见的 1×1 区域 —— 用户看到「公式没高亮」。
1715
+ * 这里把碰到的公式找出来,交给调用方补一条覆盖可见臂的 Range(公式整块上色)。
1716
+ *
1717
+ * @param {unknown} node 块节点
1718
+ * @param {Range} range 已定位好的区间
1719
+ * @returns {Element[]} 可见臂节点(不可用的公式跳过)
1720
+ */
1721
+ function katexArmsIn(node, range) {
1722
+ const formulas = typeof node?.querySelectorAll === 'function' ? node.querySelectorAll('.katex') : []
1723
+ const arms = []
1724
+ for (const formula of formulas) {
1725
+ const arm = typeof formula?.querySelector === 'function' ? formula.querySelector('.katex-html') : null
1726
+ if (!arm) continue
1727
+ // 只要区间**碰到**这个公式就整块亮(用户裁定:公式是原子单位)。
1728
+ let touches = true
1729
+ try { touches = typeof range?.intersectsNode === 'function' ? range.intersectsNode(formula) : true } catch { touches = true }
1730
+ if (touches) arms.push(arm)
1731
+ }
1732
+ return arms
1733
+ }
1449
1734
  // KaTeX 同时包含无障碍树与可视树。克隆后用公式源码替换,避免把两份文字一起引用。
1450
1735
  function formulaSelectionText(node) {
1451
1736
  const clone = node.cloneNode(true)