@li-canghai/dsh-paper 0.8.2 → 0.8.6

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.
@@ -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,所以不能再让
@@ -1897,6 +1941,33 @@
1897
1941
  }
1898
1942
  }
1899
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
+
1900
1971
  function renderSelectionText(value) {
1901
1972
  const text = String(value ?? '')
1902
1973
  const formula = /\$\$[\s\S]+?\$\$|\$(?!\s)[^$\n]+?\$/g
@@ -2028,7 +2099,7 @@
2028
2099
  * 只脱**行内排版**标签的壳、保留里面的文字。用白名单而不是「把所有尖括号都删掉」:
2029
2100
  * markdown 的自动链接写作尖括号包 URL,把尖括号一律当标签会把链接吃掉。
2030
2101
  */
2031
- 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
2032
2103
  const mapChars = (value, table) => Array.from(String(value), ch => table[ch] ?? ch).join('')
2033
2104
  /**
2034
2105
  * 把正文里的行内 HTML 换成等价的可读字符(D150)。
@@ -2584,9 +2655,100 @@
2584
2655
  // 写不进去就算了:下次打开退回默认值,不该为此打断阅读。
2585
2656
  }
2586
2657
  }
2587
- /** 排版偏好(字号 / 行距)。 */
2658
+ /**
2659
+ * 字体族清单。**按语言分开两份**(用户裁定:原文是英文,不该被中文字体名接管)。
2660
+ *
2661
+ * 🔴 为什么要分:界面上那三个按钮改的是**当前档位**那一套排版,而双语/并排档里
2662
+ * 原文段与译文段同时在场。共用一份清单时,中文档选的「宋体」会原样落到英文段上 ——
2663
+ * 宋体没有拉丁字形,浏览器只能回退,读者的选择于是看起来「没生效」。
2664
+ *
2665
+ * 🔴 「系统默认」是**栈本身**为空,不是名字叫 'system-ui':空栈表示不写 font-family,
2666
+ * 由浏览器用自己那套默认字体渲染(Chrome 在中文 Windows 上是宋体 / 雅黑)。
2667
+ * 写死 system-ui 反而会剥夺用户改浏览器默认字体的能力,那是另一回事。
2668
+ *
2669
+ * 固定清单,不给自由输入 —— 允许任意字符串等于允许读者把正文变成豆腐块,
2670
+ * 而浏览器又不提供"列出系统字体"的接口(字体枚举要用户授权且各浏览器行为不一)。
2671
+ */
2672
+ const SRC_FONT_FAMILIES = Object.freeze([
2673
+ Object.freeze({ value: 'system', label: '系统默认', stack: '' }),
2674
+ Object.freeze({ value: 'serif', label: '衬线', stack: "Georgia,'Times New Roman',Times,'Source Serif Pro',Charter,serif" }),
2675
+ Object.freeze({ value: 'sans', label: '无衬线', stack: "'Helvetica Neue',Helvetica,Arial,'Segoe UI',system-ui,sans-serif" }),
2676
+ Object.freeze({ value: 'mono', label: '等宽', stack: "'JetBrains Mono','SF Mono',Consolas,'Liberation Mono',Menlo,monospace" }),
2677
+ Object.freeze({ value: 'kai', label: '手写', stack: "'Iowan Old Style',Charter,'Segoe Print','Bradley Hand',cursive" }),
2678
+ ])
2679
+ const ZH_FONT_FAMILIES = Object.freeze([
2680
+ Object.freeze({ value: 'system', label: '系统默认', stack: '' }),
2681
+ Object.freeze({ value: 'serif', label: '宋体', stack: "'Noto Serif SC','Source Han Serif SC','Songti SC',SimSun,Georgia,serif" }),
2682
+ Object.freeze({ value: 'sans', label: '黑体', stack: "'Noto Sans SC','Source Han Sans SC','PingFang SC','Microsoft YaHei',system-ui,sans-serif" }),
2683
+ // ⚠️ 楷体在 Windows 上的注册名是 STKaiti(simkai.ttf 实际注册的族名),
2684
+ // 'Kaiti SC' 是 macOS 的写法;两个都列,再补中文名兜底。
2685
+ Object.freeze({ value: 'kai', label: '楷体', stack: "'Kaiti SC','STKaiti',KaiTi,'楷体','Noto Serif SC',serif" }),
2686
+ ])
2687
+ /** 某一侧的字体清单。side 是 'src' / 'zh'。 */
2688
+ function fontFamiliesOf(side) {
2689
+ return side === 'src' ? SRC_FONT_FAMILIES : ZH_FONT_FAMILIES
2690
+ }
2691
+ /**
2692
+ * 把存下来的 family 解析成某一侧真正要用的栈。**每侧各用各的清单**:
2693
+ * 旧数据里译文存的 'serif' 拿到原文那侧仍然叫 'serif',但栈换成了拉丁字体。
2694
+ * 认不出的值回落该侧的第一项(系统默认)—— 与"缺字段回默认"同一口径。
2695
+ */
2696
+ function fontStackOf(side, value) {
2697
+ const list = fontFamiliesOf(side)
2698
+ const entry = list.find(item => item.value === value)
2699
+ return (entry === undefined ? list[0] : entry).stack
2700
+ }
2701
+ /** 字体族取值校验。认不出的回落该侧的默认档 —— 每侧清单不同,校验也要按侧来。 */
2702
+ function fontOf(side, value) {
2703
+ return fontFamiliesOf(side).some(entry => entry.value === value) ? value : fontFamiliesOf(side)[0].value
2704
+ }
2705
+
2706
+ /**
2707
+ * 排版偏好(字号 / 行距 / 字体族),**原文与译文各一套**。
2708
+ *
2709
+ * 🔴 **全局一份、不按论文分**(D152 原意不变):它答的是"我习惯怎么读",不是"这一篇怎么看"。
2710
+ *
2711
+ * 🔴 **旧格式要能读**。拆包之前存的是 `{ size, height }`(只有一套),读者机器上可能就躺着
2712
+ * 这么一个对象。读成"译文那套",原文整组用默认值 —— 升级不丢读者已经调好的字号。
2713
+ * 反过来说:把旧字段直接丢弃、整块回落默认,等于悄悄把人家调了半天的字号重置掉。
2714
+ *
2715
+ * @returns {{src: {size: number, height: number, family: string}, zh: {size: number, height: number, family: string}}}
2716
+ */
2588
2717
  function readTypePref() { return readPref(TYPE_PREF_KEY) }
2589
- function writeTypePref(size, height) { writePref(TYPE_PREF_KEY, { size, height }) }
2718
+ function typePref() {
2719
+ const raw = readTypePref()
2720
+ const pick = (side, group, fallback) => {
2721
+ const source = group !== null && typeof group === 'object' ? group : null
2722
+ // 旧格式没有 src/zh 分组,size/height 直接躺在顶层。
2723
+ const legacy = source === null && fallback === 'legacy' ? raw : null
2724
+ const sizeOf = value => clampType(value, MIN_FONT_SIZE, MAX_FONT_SIZE, DEFAULT_FONT_SIZE)
2725
+ const heightOf = value => clampType(value, MIN_LINE_HEIGHT, MAX_LINE_HEIGHT, DEFAULT_LINE_HEIGHT)
2726
+ if (legacy !== null) {
2727
+ // 旧数据没有 family 字段。原文那侧回「系统默认」,译文那侧回宋体 ——
2728
+ // 两侧清单不同,同一个字面量在两边指向的不是同一套字体。
2729
+ return { size: sizeOf(legacy.size), height: heightOf(legacy.height), family: side === 'src' ? 'system' : 'serif' }
2730
+ }
2731
+ return {
2732
+ size: sizeOf(source?.size),
2733
+ height: heightOf(source?.height),
2734
+ family: fontOf(side, source?.family),
2735
+ }
2736
+ }
2737
+ return {
2738
+ src: pick('src', raw?.src, 'default'),
2739
+ // 🔴 顶层旧字段只喂给译文那套:它是拆包前唯一存在的那一套。
2740
+ zh: pick('zh', raw?.zh, 'legacy'),
2741
+ }
2742
+ }
2743
+ /**
2744
+ * 写一套排版偏好。
2745
+ *
2746
+ * 🔴 **每次都要写全**,不能只写改动的那一组:`writePref` 是整键覆盖,
2747
+ * 只写 `{zh}` 会把 `src` 从磁盘上抹掉 —— 读者改完译文再刷新,原文那套就没了。
2748
+ *
2749
+ * @param {object} next 完整的三组值。
2750
+ */
2751
+ function writeTypePref(next) { writePref(TYPE_PREF_KEY, next) }
2590
2752
  /**
2591
2753
  * 视图档位的取值校验(D152)。只认下拉里真有的档 —— 手改过的 localStorage 不该让选择框
2592
2754
  * 落在一个不存在的值上(那时正文按 zh 渲染、选择框却显示别的,看着像「设置没生效」)。
@@ -2734,6 +2896,53 @@
2734
2896
  + '&page=' + encodeURIComponent(String(page)) + '&width=' + width + (crop ? '&crop=1' : '')
2735
2897
  }
2736
2898
 
2899
+ /**
2900
+ * 字形宽度的测量缓存(连续滚动的性能关键之一)。
2901
+ *
2902
+ * 🔴 **为什么必须缓存**:逐字符对齐要对每个字符调一次 `canvas.measureText`。
2903
+ * 真实论文实测:一篇 9 页的论文共 16,491 个字符 —— 每页一万六千次**同步**测量。
2904
+ * 单页时代这样建一次还能接受;连续滚动下窗口里同时挂三页,一次重建就是近五万次
2905
+ * `measureText`,那是主线程直接卡住半秒的量级(滚轮会一顿一顿)。
2906
+ *
2907
+ * 🔴 **为什么缓存有效率极高**:同一篇论文里出现的不同字符只有 85 个,字号虽随行高
2908
+ * 浮动,但量化到 0.1px 之后只有二十来档 —— 去重上界约 2,000 次,比逐次测量省 88%。
2909
+ * 字体固定是 serif(与 CSS 的 `.paper-pdf-word` 一致),所以"同一字号 + 同一字串"
2910
+ * 的宽度是确定的,缓存不会失真。
2911
+ *
2912
+ * 量化到 0.1px 是刻意的:字号算出来是浮点(行高 × 页高 / 1000),不量化则几乎每个
2913
+ * 词的 key 都不同,缓存命中率会掉到接近 0。0.1px 的差异在屏幕上不可见,而选区宽度
2914
+ * 只由 `letter-spacing` 的**差值**决定,缩放时也不会累积误差。
2915
+ */
2916
+ const glyphWidthCache = new Map()
2917
+ /** 缓存上界:一篇论文 85 个字符 × 三十档字号也到不了 5,000,超了说明用法出问题了。 */
2918
+ const GLYPH_CACHE_LIMIT = 5000
2919
+ /**
2920
+ * 量一个字符串在某个字号下的宽度(带缓存)。
2921
+ *
2922
+ * @param {CanvasRenderingContext2D|null} context 测量用的 2d 上下文
2923
+ * @param {number} size 字号(px)
2924
+ * @param {string} text 要量的字串
2925
+ * @returns {number|null} 宽度;上下文不可用是 null(调用方据此跳过对齐,不编一个宽度)
2926
+ */
2927
+ function glyphWidthOf(context, size, text) {
2928
+ if (context === null || context === undefined) return null
2929
+ const pixels = Number(size)
2930
+ if (!Number.isFinite(pixels) || pixels <= 0) return null
2931
+ // 量化到 0.1px —— 不量化则每个词的 key 都不同,缓存等于没有(见上面的说明)。
2932
+ const quantized = Math.round(pixels * 10) / 10
2933
+ const key = quantized + '|' + text
2934
+ const hit = glyphWidthCache.get(key)
2935
+ if (hit !== undefined) return hit
2936
+ context.font = quantized + 'px serif'
2937
+ const measured = context.measureText(text).width
2938
+ if (!Number.isFinite(measured)) return null
2939
+ // 满了就整片清掉而不是逐条淘汰:条目本身很便宜(数字 + 短串),
2940
+ // 而一篇论文的字符集是稳定的,清掉之后下一轮的命中率依然高。
2941
+ if (glyphWidthCache.size >= GLYPH_CACHE_LIMIT) glyphWidthCache.clear()
2942
+ glyphWidthCache.set(key, measured)
2943
+ return measured
2944
+ }
2945
+
2737
2946
  /**
2738
2947
  * bbox(0–1000 归一化坐标) → overlay 的百分比样式。
2739
2948
  *
@@ -5,16 +5,31 @@
5
5
  // 🔴 与编号制最大的差别是**没有唯一键**。"姓氏 + 年份"在 AI 领域经常撞车(同一作者同年
6
6
  // 多篇),所以索引是一对多:命中几条就全列,由读者自己判断。宁可显示两条让人选,也不要
7
7
  // 挑一条赌对 —— 猜错时读者无从知道错。
8
- /** `(Surname et al., 2020)` / `(Surname & Other, 2020)` / `(Surname, 2020)`。 */
9
- const AUTHOR_YEAR =
10
- /\(\s*([\p{Lu}][\p{L}'-]+)(?:\s+et\s+al\.?|\s*(?:&|and)\s*[\p{Lu}][\p{L}'-]+)?\s*,\s*(\d{4})[a-z]?\s*\)/gu
11
- // 🔴 三个正则都**必须带 u flag**:`\p{Lu}` / `\p{L}` 是 Unicode 属性转义,没有 u 时
8
+ //
9
+ // 🔴 参考文献有**两种排版**,两种都得认(实测一篇 AAAI 式论文 27 条全灭):
10
+ // · CS 式 `Zhang, Y. Title. 2020.` —— 姓在前,后面跟逗号
11
+ // · AAAI 式 `Parth Sarthi, Salman Abdullah, …, and Christopher D. Manning. 2024.`
12
+ // —— 名在前姓在后,年份在整串作者**之后**
13
+ // 所以不再拿正则硬抠"姓 + 逗号",改成**先按年份切开、再从作者串里取第一个人的最后一个词**。
14
+ /** 整个括号。**不**要求里面只有一条引用:`(A et al., 2024; B et al., 2025)` 是常态。 */
15
+ const AUTHOR_YEAR = /\(([^()]{1,240})\)/gu
16
+ // 🔴 下面的正则都**必须带 u flag**:`\p{Lu}` / `\p{L}` 是 Unicode 属性转义,没有 u 时
12
17
  // 会被当成字面量 p / L / u,正则永远匹配不上而**不报错** —— 表现为索引恒为空、悬停全无反应。
13
18
  // 这条踩过一次(首版漏了 u,4 条作者-年份用例全挂)。
14
- /** 参考文献条目开头的姓:surname, Initial. */
15
- const REFERENCE_SURNAME = /^\s*(?:\[\s*\d{1,3}\s*\]\s*)?([\p{Lu}][\p{L}'-]+)\s*,/u
16
- /** 条目里出现的第一个四位数年份。 */
17
- const REFERENCE_YEAR = /\b(\d{4})\b/
19
+ /** `e.g.,` / `i.e.,` / `cf.` / `see` 这些前缀不属于引用本身,逐条匹配前先剥掉。 */
20
+ const CITE_PREFIX = /^\s*(?:e\.g\.|i\.e\.|cf\.|see|also)\s*,?\s*/i
21
+ /** 并列里的一条:`Surname, 2020` / `Surname et al., 2020` / `Surname and Other, 2020`。 */
22
+ const CITE_ITEM =
23
+ /^\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
24
+ /**
25
+ * 条目里第一个年份。
26
+ *
27
+ * 🔴 尾巴上的年份后缀要一起吃掉:`\b\d{4}\b` 匹配不了 `2024a`,那种条目会整条掉出索引。
28
+ * 以 `19` / `20` 开头也顺带挡掉了页码 `1234` 之类误判。
29
+ */
30
+ const REFERENCE_YEAR = /\b((?:19|20)\d{2})[a-z]?\b/
31
+ /** 作者串里一个像姓的词。`O'Brien` / `Gutiérrez` / `Liu-Lin` 都要能过。 */
32
+ const NAME_WORD = /^[\p{Lu}][\p{L}'-]*$/u
18
33
 
19
34
  /** 匹配键:姓氏折叠成小写 + 年份。作者大小写与变音符号不在这一层处理。 */
20
35
  function authorYearKey(surname, year) {
@@ -23,10 +38,59 @@
23
38
  : ''
24
39
  }
25
40
 
41
+ /**
42
+ * 参考文献条目 → 第一作者的姓。
43
+ *
44
+ * 两步,顺序不能反:
45
+ * 1. **先按年份切开**。年份之后是标题、期刊、卷号,里面全是首字母大写的词 ——
46
+ * 不先切掉就会取到 `Cognition` / `Psychological` 这种,索引里凭空多出一条假条目。
47
+ * 2. 再从作者串里取**第一个人的最后一个词**。第一个人的边界是 `and` / `&` / 逗号 ——
48
+ * 三种排版都用它们分隔作者。
49
+ *
50
+ * 逗号在两种排版里含义不同(`Smith, John` 是"姓, 名",而 `Ge Bai, Jie Liu` 是作者分隔),
51
+ * 但两种情况下第一个逗号之前都正好是第一作者的姓氏串,所以先切逗号两边都对。
52
+ *
53
+ * @param {unknown} source 参考文献原文。
54
+ * @returns {string} 姓氏;认不出时为空串(那条引用只是悬停没反应,不会错配到别人)。
55
+ */
56
+ function referenceSurname(source) {
57
+ const lead = String(source ?? '').replace(/^\s*\[\s*\d{1,5}\s*\]\s*/, '')
58
+ if (lead === '') return ''
59
+ const year = REFERENCE_YEAR.exec(lead)
60
+ const authors = year === null ? lead : lead.slice(0, year.index)
61
+ const pick = zone => {
62
+ const first = zone.split(/\s+(?:and|&)\s+|,/)[0]
63
+ // 🔴 尾部句点必须剥掉:`Leonard Talmy.` 里 `Talmy.` 带点,不剥就过不了 NAME_WORD,
64
+ // 于是只剩 `Leonard` 当姓 —— 索引里多出一个"Leonard 1975",正文的 `Talmy, 1975` 全落空。
65
+ const words = first.trim().replace(/[.,;:]+$/, '').split(/\s+/).filter(word => NAME_WORD.test(word))
66
+ return words.length === 0 ? '' : words[words.length - 1]
67
+ }
68
+ // 年份在最前(极少数期刊把年份编进卷首)时作者串是空的,退回整条开头再试一次。
69
+ return pick(authors) || pick(lead)
70
+ }
71
+
72
+ /**
73
+ * 一个括号里解析出的全部引用。`;` 分隔并列,逐条剥掉 `e.g.,` 之类前缀。
74
+ *
75
+ * 🔴 任一条认不出就**整段作废**,与编号制同一口径(那个编号不在本篇就整段按纯文本):
76
+ * 只标出认得的一半,读者会以为括号里只有那一半。
77
+ *
78
+ * @param {string} inner 括号内部(不含两侧圆括号)。
79
+ * @returns {Array<{surname: string, year: string}>} 一条都认不出时为空数组。
80
+ */
81
+ function authorYearItems(inner) {
82
+ const items = []
83
+ for (const chunk of String(inner).split(';')) {
84
+ const match = CITE_ITEM.exec(chunk.replace(CITE_PREFIX, ''))
85
+ if (match === null) return []
86
+ items.push({ surname: match[1], year: match[2] })
87
+ }
88
+ return items
89
+ }
90
+
26
91
  /**
27
92
  * 从参考文献块建「姓氏|年份 → 块」的一对多索引。
28
93
  *
29
- * 姓氏取条目开头(可带 `[n]` 前缀)的第一个大写词,年份取条目里第一个四位数 ——
30
94
  * 学术期刊格式千差万别,这是**启发式**而不是解析器。认不出来的条目直接跳过:
31
95
  * 索引里少一条只是那条引用悬停没反应,不会错配到别的条目上。
32
96
  *
@@ -39,10 +103,10 @@
39
103
  if (block === null || typeof block !== 'object' || typeof block.id !== 'string') continue
40
104
  if (readerKindOf(block) !== 'references') continue
41
105
  const source = typeof block.sourceText === 'string' ? block.sourceText : ''
42
- const surname = REFERENCE_SURNAME.exec(source)
106
+ const surname = referenceSurname(source)
43
107
  const year = REFERENCE_YEAR.exec(source)
44
- if (surname === null || year === null) continue
45
- const key = authorYearKey(surname[1], year[1])
108
+ if (surname === '' || year === null) continue
109
+ const key = authorYearKey(surname, year[1])
46
110
  if (key === '') continue
47
111
  const entry = { blockId: block.id, text: source.replace(REFERENCE_LEAD, '').trim() }
48
112
  const list = index.get(key)
@@ -58,11 +122,15 @@
58
122
  * 只产出**索引里真有**的标记:查不到的括号原样留在文本里。这一条与编号制同一口径 ——
59
123
  * 点了没反应/悬停了没内容,比没有标记更坏。
60
124
  *
61
- * 标记带 `ambiguous`:命中多条时为真,渲染层据此提示"共 N 条可能匹配"。
125
+ * 括号里并列多条时,**整段合成一个标记**(而不是拆成几个可点区域):读者看到的是
126
+ * 一个括号,悬停展开全部条目才符合直觉;拆开还会让"哪几个字属于同一条引用"变得无法判断。
127
+ * 标记上带 `items`(每条的 `姓氏|年份` 键),形状与编号制的多标号一致。
128
+ *
129
+ * 标记带 `ambiguous`:全部条目命中总数 > 1 时为真,渲染层据此提示"共 N 条可能匹配"。
62
130
  *
63
131
  * @param {unknown} text 段落文本。
64
132
  * @param {unknown} index {@link authorYearIndex} 的产物。
65
- * @returns {Array<{type: string, value: string, surname: string, year: string, ambiguous?: boolean, count?: number} | {type: 'text', text: string}>}
133
+ * @returns {Array<{type: string, value: string, surname?: string, year?: string, items?: string[], ambiguous?: boolean, count?: number} | {type: 'text', text: string}>}
66
134
  */
67
135
  function inlineAuthors(text, index) {
68
136
  if (typeof text !== 'string' || text === '' || !(index instanceof Map) || index.size === 0) return []
@@ -75,18 +143,37 @@
75
143
  let cursor = 0
76
144
  AUTHOR_YEAR.lastIndex = 0
77
145
  for (let match = AUTHOR_YEAR.exec(text); match !== null; match = AUTHOR_YEAR.exec(text)) {
78
- const key = authorYearKey(match[1], match[2])
79
- const hits = key === '' ? undefined : index.get(key)
80
- if (hits === undefined || hits.length === 0) continue
146
+ const items = authorYearItems(match[1])
147
+ if (items.length === 0) continue
148
+ // 先确认**每一条**都查得到,再决定要不要出标记:查到一半就放弃,才不会出现
149
+ // "括号里两条、只标了一条"这种让人误解的部分标记。
150
+ const keys = []
151
+ let total = 0
152
+ let known = true
153
+ for (const item of items) {
154
+ const key = authorYearKey(item.surname, item.year)
155
+ const hits = key === '' ? undefined : index.get(key)
156
+ if (hits === undefined || hits.length === 0) { known = false; break }
157
+ keys.push(key)
158
+ total += hits.length
159
+ }
160
+ if (!known) continue
81
161
  plain += text.slice(cursor, match.index)
82
162
  flush()
83
- parts.push({
84
- type: 'author',
85
- value: match[0],
86
- surname: match[1],
87
- year: match[2],
88
- ...(hits.length > 1 ? { ambiguous: true, count: hits.length } : {}),
89
- })
163
+ const single = items.length === 1
164
+ const part = { type: 'author', value: match[0] }
165
+ // 单条的字段形状**保持不变**:既有 4 条用例按字段全等断言,多一个字段就红。
166
+ if (single) {
167
+ part.surname = items[0].surname
168
+ part.year = items[0].year
169
+ } else {
170
+ part.items = keys
171
+ }
172
+ if (total > 1) {
173
+ part.ambiguous = true
174
+ part.count = total
175
+ }
176
+ parts.push(part)
90
177
  cursor = match.index + match[0].length
91
178
  }
92
179
  plain += text.slice(cursor)
@@ -0,0 +1,97 @@
1
+ // ---- PDF 原页页栈(连续滚动)----
2
+ /**
3
+ * 一篇论文的页身份键:`文档|页|裁边档`。
4
+ *
5
+ * 🔴 **裁边是身份的一部分**:同一页裁与不裁拿到的坐标不是一套(宿主 readPdfPage 按满页口径
6
+ * 缓存、cropPdfGroups 在读出后换算),拿裁边的文字层去配整页的位图,选字框会整片偏出页面。
7
+ * 所以 key 里必须带它,改 key 就等于换一份数据,与旧实现在 pdfData.cropped 上做的判定同源。
8
+ *
9
+ * @param {unknown} documentId 本篇 documentId
10
+ * @param {unknown} page 页码(1 起)
11
+ * @param {unknown} crop 是否裁边
12
+ * @returns {string} 空串 = 这个身份不成立(文档 id 为空或页码不是正整数)
13
+ */
14
+ function pdfStackKey(documentId, page, crop) {
15
+ const id = typeof documentId === 'string' ? documentId : ''
16
+ const number = Number(page)
17
+ if (id === '' || !Number.isSafeInteger(number) || number < 1) return ''
18
+ return id + '|' + number + '|' + (crop ? '1' : '0')
19
+ }
20
+
21
+ /**
22
+ * 该挂载哪几页:当前页 ± radius,并夹在 [1, pageCount] 里。
23
+ *
24
+ * 🔴 **这是连续滚动唯一的性能闸门**。一页的文字层约 4300 个 DOM 节点(逐字符对齐的代价,
25
+ * 见 client.js 里 pdfPageView 的说明),12 页全挂就是 5 万个节点 —— 滚动与重涂都会被拖死。
26
+ * 只挂「当前页 ± 半径」把常驻节点数钉在 (2·radius+1) 页的量级,滚出窗口的页整页卸载。
27
+ *
28
+ * radius = 1 是**滑动手感**的下限:滚到一页底部时下一页必须已经在 DOM 里,否则会先看到
29
+ * 一屏骨架再等 JSON。再大只是白烧节点,滚一页用不到第三页。
30
+ *
31
+ * @param {unknown} page 当前页
32
+ * @param {unknown} pageCount 总页数
33
+ * @param {unknown} radius 前后各挂几页
34
+ * @returns {number[]} 升序页码;参数不成立时空数组(**不编一圈默认页**)
35
+ */
36
+ function pdfPageWindow(page, pageCount, radius = 1) {
37
+ const current = Number(page)
38
+ const total = Number(pageCount)
39
+ if (!Number.isSafeInteger(current) || current < 1) return []
40
+ if (!Number.isSafeInteger(total) || total < 1) return []
41
+ const span = Number.isSafeInteger(Number(radius)) && Number(radius) >= 0 ? Number(radius) : 1
42
+ const from = Math.max(1, current - span)
43
+ const to = Math.min(total, current + span)
44
+ const pages = []
45
+ for (let number = from; number <= to; number++) pages.push(number)
46
+ return pages
47
+ }
48
+
49
+ /**
50
+ * 页框宽高比,**按 CSS `aspect-ratio` 的口径给(宽 / 高)**(纯函数)。
51
+ *
52
+ * 🔴 为什么可以篇内统一:实测同一篇论文各页尺寸逐页相同(PDF 页面框固定),所以一篇之内
53
+ * 用同一个比例不会让任何一页变形;换来的是**不必等每页位图加载完就能定高度** ——
54
+ * 否则滚动条会随着每一页加载完毕而跳动,而连续滚动最刺眼的就是这种跳。
55
+ *
56
+ * 🔴 方向别搞反:CSS 的 `aspect-ratio` 写的是**宽 / 高**。给成高 / 宽时,
57
+ * A4 那种竖版页会被排成横版(0.77 与 1.29 差了 67%),整篇高度全错。
58
+ * 换算不出正数时返回 null,调用方退回「按图片自然尺寸」而不是编一个比例。
59
+ *
60
+ * @param {unknown} width 页面宽(PDF 点)
61
+ * @param {unknown} height 页面高(PDF 点)
62
+ * @returns {number|null} 宽 / 高;无效是 null
63
+ */
64
+ function pdfPageAspectOf(width, height) {
65
+ const w = Number(width)
66
+ const h = Number(height)
67
+ if (!Number.isFinite(w) || !Number.isFinite(h) || !(w > 0) || !(h > 0)) return null
68
+ return w / h
69
+ }
70
+
71
+ /**
72
+ * 从滚动位置反推"现在是第几页"(纯函数)。
73
+ *
74
+ * 🔴 用**页顶坐标**而不是"视口中心落在谁身上":连续滚动下用户可能正停在两页交界处,
75
+ * 中心判据在那一瞬间会来回跳(页码跟着闪),而"最后一个页顶已经滚过视口上沿的页"
76
+ * 单调、稳定,滚过一页才前进一页。
77
+ *
78
+ * @param {number[]} tops 各页页顶的 scrollTop 偏移(升序)
79
+ * @param {unknown} pages 与 tops 一一对应的页码
80
+ * @param {unknown} scrollTop 当前滚动位置
81
+ * @returns {number|null} 页码;参数不成立是 null
82
+ */
83
+ function pdfPageAt(tops, pages, scrollTop) {
84
+ if (!Array.isArray(tops) || !Array.isArray(pages) || tops.length !== pages.length) return null
85
+ if (tops.length === 0) return null
86
+ const position = Number(scrollTop)
87
+ if (!Number.isFinite(position)) return null
88
+ // 留 2px 容差:滚动容器的 scrollTop 是整数化的,页顶算出来可能带小数,
89
+ // 差这一线就会让"刚滚到下一页"判成还在上一页。
90
+ let found = Number(pages[0])
91
+ for (let index = 0; index < tops.length; index++) {
92
+ if (Number(tops[index]) <= position + 2) found = Number(pages[index])
93
+ else break
94
+ }
95
+ return Number.isSafeInteger(found) && found > 0 ? found : null
96
+ }
97
+