@li-canghai/dsh-paper 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  选文件或文件夹 → 解析(已有的直接复用)→ 连同结果收进插件存储,库自此自包含;
8
8
  读的时候有章节目录、块级续读、划线、AI 边注、逐块中英对照、原页拖选提问,
9
+ 引用标记悬停即见该条参考文献原文(`[41]` 与 `(Zhang et al., 2020)` 都认),
9
10
  还能把同一篇并排开两格(左英文右译文、滚动联动);
10
11
  写完有书目补全、BibTeX / RIS / CSL-JSON 互通与 GB/T 7714 等引用样式。
11
12
  另有两条不进库的旁路:把结果存一份到论文文件夹,或直接把一篇 PDF 解成 md + `images`。
@@ -132,6 +133,18 @@ HTTP 分发只做三件事:`repositoryReady`、同源检查、按阶段转发
132
133
  - 改 `sourceHashOf` 的口径时记得:哈希若仍按原串算,已经存下来的坏译文会被一直跳过、永远修不回来。
133
134
  - 部署面只剩 `desktop`;`npm audit` 必须显式给 `--registry=https://registry.npmjs.org`
134
135
  (本机默认镜像不实现审计端点);`package-lock.json` 只能在干净目录生成。
136
+ - **测试 CI**:[`dsh-paper-ci.yml`](../../.github/workflows/dsh-paper-ci.yml) 随插件改动自动运行、也可手动触发。
137
+ Windows 跑 `npm run check` 全量测试(额外安装与宿主镜像同版的测试工具包),Ubuntu 24.04 跑 PDF/选区跨平台回归,
138
+ 并用真正的 PDFium + Chromium 逐字测坐标、逐像素检查**同一行蓝色选区不留白**、核对真实鼠标拖选;
139
+ 截图作为 Actions artifact 保存 7 天。两者都跑 `npm run smoke`。测试 CI 不发布 npm 包。
140
+ - **发版**见 [.agents/skills/dsh-paper-npm-release](../../.agents/skills/dsh-paper-npm-release/SKILL.md):
141
+ **改 `package.json` 的 version 并推到 main 就发版**,其余提交不触发。
142
+ `dsh-paper-release.yml` 盯着 `Plugins/dsh-paper/package.json` 这条路,先查 npm 判断该版本
143
+ 是否已存在(幂等),过发布闸门,**自己打 tag `dsh-paper-v<版本>`**,再用 OIDC 发布 ——
144
+ tag 是产物不是输入,所以它恒等于实际发出去的版本,也不存在「忘了打 tag 就静默不发」。
145
+ 一键等效操作:`node scripts/release.mjs <版本号>`(过闸门 → 改版本号与 lockfile → 提交 → 推 HEAD)。
146
+ 任何 npm 写操作都要显式 `--registry=https://registry.npmjs.org` —— 本机全局是镜像,
147
+ 而 `npm publish`、`npm trust` 都**不读** scope 级 registry 配置。
135
148
  - 宿主接口一有变化,先看 [PITFALLS.md](docs/PITFALLS.md) 里有没有对应的旧坑,
136
149
  再去改 [ARCHITECTURE.md](docs/ARCHITECTURE.md) 的不变量一节。
137
150
 
@@ -426,14 +426,26 @@
426
426
  return { tex, tag: typeof block.math?.tag === 'string' ? block.math.tag : '' }
427
427
  }
428
428
 
429
- /** 行内片段的稳定 key:块 id + 下标就够定位,同一块的两段各自的片段也不会撞。 */
429
+ /**
430
+ * 行内片段的稳定 key:块 id + 下标就够定位,同一块的两段各自的片段也不会撞。
431
+ *
432
+ * 🔴 **必须把 raw / items 原样带过来**:这两个字段由 {@link inlineRefs} 给多标号
433
+ * (`[41, 44, 13, 16]`)产出好后,这一层是通往悬停预览的**唯一通道**。
434
+ * 早先只复制 key/type/value/text,它们在这里被静默丢掉 —— 下游 {@link paintCiteSpans}
435
+ * 于是退回用 value 拼 `[41,44,13,16]`(无空格)去正文里找,而页面上真实的字带空格,
436
+ * 结果单编号 `[23]` 能悬停、多标号一律没反应。丢字段不报错,所以肉眼查不出来。
437
+ */
430
438
  function inlinePart(part, index, at) {
431
- return {
439
+ const shape = {
432
440
  key: `${index}-${at}-${part.type}-${part.value ?? ''}`,
433
441
  type: part.type,
434
442
  value: part.value ?? '',
435
443
  text: part.text ?? '',
436
444
  }
445
+ // 单编号不带这两项时**不补空值**:既有断言按字段全等,多一个 raw: undefined 也会红。
446
+ if (part.raw !== undefined) shape.raw = part.raw
447
+ if (part.items !== undefined) shape.items = part.items
448
+ return shape
437
449
  }
438
450
 
439
451
  // 阅读器布局(D46 + D75):右栏未展开 —— 或读不到展开状态 —— 恒定单栏,这时宽度再大也不并排;
@@ -610,6 +622,60 @@
610
622
  * @returns {Map<string, object[]>} blockId → 该块的划线,按面板顺序。
611
623
  */
612
624
 
625
+ /**
626
+ * 将 PDF 原生字形宽度和后继词的物理空隙分别映射到 CSS。
627
+ * 不能把 (字框 + gap) 一起分摊给字形:这会把本词最后一个字母推向下一个词,
628
+ * 而浏览器的选区、插入光标又按实际字形推进量走,最终表现为蓝色选区水平偏移。
629
+ *
630
+ * 有尾空格时,letter-spacing 也会作用于这个空格,所以 word-spacing 必须减掉它。
631
+ * 返回的长度遵循:字形 = wordWidth;字形 + 尾空格 = wordWidth + gap。
632
+ */
633
+ function pdfWordMetrics(text, wordWidth, gap, measure) {
634
+ const raw = String(text ?? '')
635
+ const glyphs = raw.replace(/\s+$/, '')
636
+ const count = Array.from(glyphs).length
637
+ if (!(wordWidth > 0) || count === 0 || typeof measure !== 'function') return null
638
+ const glyphWidth = measure(glyphs)
639
+ const trailingWidth = measure(raw) - glyphWidth
640
+ if (!Number.isFinite(glyphWidth) || !Number.isFinite(trailingWidth)) return null
641
+ const letterSpacing = (wordWidth - glyphWidth) / count
642
+ return {
643
+ letterSpacing,
644
+ wordSpacing: glyphs.length !== raw.length ? gap - trailingWidth - letterSpacing : 0,
645
+ }
646
+ }
647
+
648
+ /**
649
+ * 将 PDFium 原生字符的每个起点转换成浏览器可渲染的字符推进宽度。
650
+ * 单词字体、字重、连字均不可假定等于浏览器 serif,所以不能再让
651
+ * 所有字母平分整词宽差。非法、倒序、叠字或不匹配的字符回退整词布局。
652
+ */
653
+ function pdfGlyphAdvances(word, scale) {
654
+ const raw = String(word?.text ?? '')
655
+ const core = raw.replace(/\s+$/, '')
656
+ const trailing = raw.slice(core.length)
657
+ const chars = word?.chars
658
+ const box = word?.bbox
659
+ if (!Array.isArray(chars) || chars.length === 0 || !Array.isArray(box) || !(scale > 0)
660
+ || (trailing !== '' && trailing !== ' ')
661
+ || !chars.every(char => typeof char?.text === 'string'
662
+ && Array.from(char.text).length === 1 && Array.isArray(char.bbox)
663
+ && char.bbox.length === 4 && char.bbox.every(Number.isFinite))
664
+ || chars.map(char => char.text).join('') !== core) return null
665
+ const left = box[0], right = box[2]
666
+ if (!Number.isFinite(left) || !Number.isFinite(right) || !(right > left)
667
+ || Math.abs(chars[0].bbox[0] - left) > 0.1) return null
668
+ const spans = []
669
+ for (let i = 0; i < chars.length; i++) {
670
+ const start = chars[i].bbox[0]
671
+ const end = i + 1 < chars.length ? chars[i + 1].bbox[0] : right
672
+ if (start < left - 0.1 || end > right + 0.1 || end - start < 0.01) return null
673
+ spans.push({ text: chars[i].text, advance: (end - start) * scale })
674
+ }
675
+ if (trailing) spans.push({ text: ' ', advance: Math.max(0, Number(word.gap) || 0) * scale })
676
+ return spans
677
+ }
678
+
613
679
  function selectionCount(text) {
614
680
  const source = String(text ?? '')
615
681
  const characters = (source.match(/\p{Script=Han}/gu) ?? []).length
@@ -1853,11 +1919,54 @@
1853
1919
  // 引用编号挂 data-ref,公式编号挂 data-eq。只认"本篇里真的存在的编号":引用编号来自参考
1854
1920
  // 文献块开头的 [n](条目正文里的年份括号不算),公式编号来自 math 块的 tag。认不出、或编号
1855
1921
  // 不在集合里,一律原样留在纯文本里 —— 不猜、不改写正文。
1856
- const REF_NUMBER = /\[(\d{1,3})\]/g
1922
+ // 🔴 一次引用多篇(`[42, 43]`、`[40–41]`)在真实论文里很常见(实测 ResNet 一篇就有
1923
+ // `[42, 43]` 3 次、`[40, 41]` 2 次)。旧版正则只认 `[41]` 这一种形态,多标号会整段落回
1924
+ // 纯文本 —— 那是缺口,不是刻意省略。现在把**连编号带分隔符**的整段一起捕获,再由
1925
+ // {@link refItemsOf} 摊成单个编号。
1926
+ //
1927
+ // 仍然要求方括号内**以数字开头**:`[.5, .95]` 这类置信区间因此天然不匹配(实测同一篇里
1928
+ // 出现 7 次),不需要额外的黑白名单。
1929
+ // 🔴 编号位数不能写死 3 位:实测一篇综述有 1411 条参考文献,正文里出现 `[841, 1141]`、
1930
+ // `[1211, 1372]` 这类四位数编号(`\d{1,3}` 会把它们整段挡掉,界面上就是"悬停没反应")。
1931
+ // 上限给到 5 位足以覆盖任何真实文献表,同时仍挡掉更长的方括号噪声。
1932
+ const REF_NUMBER = /\[(\d{1,5}(?:\s*[,,、–—-]\s*\d{1,5})*)\]/g
1857
1933
  // 公式号不加单词边界:词边界只对拉丁字母成立,中文的"式 (4)"加了就永远匹配不上。
1858
1934
  const EQUATION_NUMBER = /(?:\bEquations?\b|\bEqs?\.|式)\s*\(?\s*(\d{1,3})\)?/g
1859
1935
  /** 引用条目开头的方括号编号;条目正文里的年份括号不会被当成编号。 */
1860
- const REFERENCE_LEAD = /^\[\s*(\d{1,3})\s*\]/
1936
+ const REFERENCE_LEAD = /^\[\s*(\d{1,5})\s*\]/
1937
+ /** 连字符区间的最大展开跨度;超过它的一律不当作引用区间。 */
1938
+ const REF_RANGE_MAX = 200
1939
+
1940
+ /**
1941
+ * 把一个引用标记的内部文本摊成单个编号字符串。
1942
+ *
1943
+ * 逗号/顿号分隔 = 并列,原样列出;连字符/短破折号/长破折号分隔 = 区间,展开。
1944
+ * 任何一个成分认不出来(例如 `4a`、小数、空段)**整段作废**返回空数组:
1945
+ * 只认得出的那几个编号不算数 —— 显示半截引用比不显示更坏,读者会以为那就是全部。
1946
+ *
1947
+ * 区间跨度过大也整段作废:那不是引用区间,是解析事故。
1948
+ *
1949
+ * @param {unknown} inner 方括号内部的文本(不含两侧方括号)。
1950
+ * @returns {string[]} 单个编号,按出现顺序;空数组表示"这不是引用标记"。
1951
+ */
1952
+ function refItemsOf(inner) {
1953
+ if (typeof inner !== 'string' || inner === '') return []
1954
+ const items = []
1955
+ for (const chunk of inner.split(/[,,、]/)) {
1956
+ const range = /^\s*(\d{1,5})\s*[–—-]\s*(\d{1,5})\s*$/.exec(chunk)
1957
+ if (range !== null) {
1958
+ const start = Number(range[1])
1959
+ const end = Number(range[2])
1960
+ if (end < start || end - start > REF_RANGE_MAX) return []
1961
+ for (let value = start; value <= end; value += 1) items.push(String(value))
1962
+ continue
1963
+ }
1964
+ const single = /^\s*(\d{1,5})\s*$/.exec(chunk)
1965
+ if (single === null) return []
1966
+ items.push(single[1])
1967
+ }
1968
+ return items
1969
+ }
1861
1970
 
1862
1971
  /**
1863
1972
  * 把段落切成"文字段 + 标记"的有序片段。标记是结构化对象({"type":"ref"|"eq", value}),
@@ -1866,9 +1975,15 @@
1866
1975
  * 两个模式都带 g,lastIndex 在换模式时不会被重置,所以每次 exec 前按 cursor 重新定位;
1867
1976
  * 空匹配(两个正则都不可能产生)原地踏步时按一个字符推进,保证一定会终止。
1868
1977
  *
1978
+ * `ref` 片段一次引用多篇时带 {@link items}:正文**原样**保留(`[42, 43]` 不拆成两段),
1979
+ * 悬停预览再逐条展开。单编号时不带 `items` —— 与旧行为逐字段相同,既有断言不受影响。
1980
+ *
1981
+ * 多标号里只要有一个编号不在本篇集合内,整段按纯文本处理(同 {@link refItemsOf} 的口径):
1982
+ * 显示半截引用会让读者以为那就是全部。
1983
+ *
1869
1984
  * @param {unknown} text 段落文本。
1870
1985
  * @param {unknown} known {refs: Set, eqs: Set},本篇真实存在的编号。
1871
- * @returns {Array<{type: string, value: string} | {type: 'text', text: string}>}
1986
+ * @returns {Array<{type: string, value: string, items?: string[]} | {type: 'text', text: string}>}
1872
1987
  */
1873
1988
  function inlineRefs(text, known) {
1874
1989
  if (typeof text !== 'string' || text === '') return []
@@ -1890,9 +2005,21 @@
1890
2005
  if (hit === null) break
1891
2006
  const match = hit === 'ref' ? ref : eq
1892
2007
  plain += text.slice(cursor, match.index)
1893
- if ((hit === 'ref' ? refs : eqs).has(match[1])) {
2008
+ if (hit === 'ref') {
2009
+ const items = refItemsOf(match[1])
2010
+ if (items.length > 0 && items.every(number => refs.has(number))) {
2011
+ flush()
2012
+ // 单编号不带 raw/items:与旧的 {type, value} 逐字段相同,既有断言照旧通过。
2013
+ // 多标号必须带 raw —— 渲染时按它原样输出(`[42,43]` 不能变成 `[42, 43]`)。
2014
+ parts.push(items.length === 1
2015
+ ? { type: 'ref', value: items[0] }
2016
+ : { type: 'ref', value: items.join(','), items, raw: match[0] })
2017
+ } else {
2018
+ plain += match[0]
2019
+ }
2020
+ } else if (eqs.has(match[1])) {
1894
2021
  flush()
1895
- parts.push({ type: hit, value: match[1] })
2022
+ parts.push({ type: 'eq', value: match[1] })
1896
2023
  } else {
1897
2024
  plain += match[0]
1898
2025
  }
@@ -1911,6 +2038,27 @@
1911
2038
  return lead === null ? '' : lead[1]
1912
2039
  }
1913
2040
 
2041
+ /**
2042
+ * 编号 → 该条参考文献的**原文**(去掉开头的 `[n]` 与两侧空白)。
2043
+ *
2044
+ * 悬停预览要给人看的是条目文字本身,不是块 id —— 所以与 {@link referenceIndex} 分开:
2045
+ * 那个给"跳到哪一段"用,这个给"显示什么"用。两者同一口径地只认参考文献块**开头**的编号。
2046
+ *
2047
+ * @param {unknown} blocks 阅读器的块列表。
2048
+ * @returns {Map<string, {blockId: string, text: string}>}
2049
+ */
2050
+ function referenceTexts(blocks) {
2051
+ const texts = new Map()
2052
+ for (const block of Array.isArray(blocks) ? blocks : []) {
2053
+ if (block === null || typeof block !== 'object' || typeof block.id !== 'string') continue
2054
+ const number = refNumbersOf(block)
2055
+ if (number === '' || texts.has(number)) continue
2056
+ const source = typeof block.sourceText === 'string' ? block.sourceText : ''
2057
+ texts.set(number, { blockId: block.id, text: source.replace(REFERENCE_LEAD, '').trim() })
2058
+ }
2059
+ return texts
2060
+ }
2061
+
1914
2062
  /** 全文真实的编号集合。非数组入参按没有编号处理,不抛错。 */
1915
2063
  function numbersOf(values, pick) {
1916
2064
  const numbers = new Set()
@@ -1922,11 +2070,18 @@
1922
2070
  return numbers
1923
2071
  }
1924
2072
 
1925
- /** 本篇真实存在的编号:refs 来自参考文献块,eqs 来自 math 块的 tag。 */
2073
+ /**
2074
+ * 本篇真实存在的编号:refs 来自参考文献块,eqs 来自 math 块的 tag。
2075
+ *
2076
+ * 编号制整篇一条都没识别出来时**才**建作者-年份索引:那套索引要解析每一条参考文献的
2077
+ * 姓氏与年份,对编号制论文是纯浪费(实测 4128 个 ref_text 块,建一次不便宜)。
2078
+ */
1926
2079
  function readerNumbers(blocks) {
2080
+ const refs = numbersOf(blocks, refNumbersOf)
1927
2081
  return {
1928
- refs: numbersOf(blocks, refNumbersOf),
2082
+ refs,
1929
2083
  eqs: numbersOf(blocks, block => (typeof block?.math?.tag === 'string' ? block.math.tag : '')),
2084
+ authorYears: refs.size > 0 ? new Map() : authorYearIndex(blocks),
1930
2085
  }
1931
2086
  }
1932
2087
  /**
@@ -0,0 +1,95 @@
1
+ // ---- 作者-年份制引用(T25b,纯函数) ----
2
+ // 很多论文的参考文献**不带编号**(实测抽查 4 篇里有 2 篇),正文改用 `(Zhang et al., 2020)`。
3
+ // 这条链路独立于编号制:编号制未命中时才启用,两套规则不互相干扰。
4
+ //
5
+ // 🔴 与编号制最大的差别是**没有唯一键**。"姓氏 + 年份"在 AI 领域经常撞车(同一作者同年
6
+ // 多篇),所以索引是一对多:命中几条就全列,由读者自己判断。宁可显示两条让人选,也不要
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 时
12
+ // 会被当成字面量 p / L / u,正则永远匹配不上而**不报错** —— 表现为索引恒为空、悬停全无反应。
13
+ // 这条踩过一次(首版漏了 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/
18
+
19
+ /** 匹配键:姓氏折叠成小写 + 年份。作者大小写与变音符号不在这一层处理。 */
20
+ function authorYearKey(surname, year) {
21
+ return typeof surname === 'string' && surname !== '' && /^\d{4}$/.test(String(year))
22
+ ? surname.toLowerCase() + '|' + year
23
+ : ''
24
+ }
25
+
26
+ /**
27
+ * 从参考文献块建「姓氏|年份 → 块」的一对多索引。
28
+ *
29
+ * 姓氏取条目开头(可带 `[n]` 前缀)的第一个大写词,年份取条目里第一个四位数 ——
30
+ * 学术期刊格式千差万别,这是**启发式**而不是解析器。认不出来的条目直接跳过:
31
+ * 索引里少一条只是那条引用悬停没反应,不会错配到别的条目上。
32
+ *
33
+ * @param {unknown} blocks 阅读器的块列表。
34
+ * @returns {Map<string, Array<{blockId: string, text: string}>>}
35
+ */
36
+ function authorYearIndex(blocks) {
37
+ const index = new Map()
38
+ for (const block of Array.isArray(blocks) ? blocks : []) {
39
+ if (block === null || typeof block !== 'object' || typeof block.id !== 'string') continue
40
+ if (readerKindOf(block) !== 'references') continue
41
+ const source = typeof block.sourceText === 'string' ? block.sourceText : ''
42
+ const surname = REFERENCE_SURNAME.exec(source)
43
+ const year = REFERENCE_YEAR.exec(source)
44
+ if (surname === null || year === null) continue
45
+ const key = authorYearKey(surname[1], year[1])
46
+ if (key === '') continue
47
+ const entry = { blockId: block.id, text: source.replace(REFERENCE_LEAD, '').trim() }
48
+ const list = index.get(key)
49
+ if (list === undefined) index.set(key, [entry])
50
+ else if (!list.some(item => item.blockId === block.id)) list.push(entry)
51
+ }
52
+ return index
53
+ }
54
+
55
+ /**
56
+ * 把段落切成「文字段 + 作者-年份标记」。
57
+ *
58
+ * 只产出**索引里真有**的标记:查不到的括号原样留在文本里。这一条与编号制同一口径 ——
59
+ * 点了没反应/悬停了没内容,比没有标记更坏。
60
+ *
61
+ * 标记带 `ambiguous`:命中多条时为真,渲染层据此提示"共 N 条可能匹配"。
62
+ *
63
+ * @param {unknown} text 段落文本。
64
+ * @param {unknown} index {@link authorYearIndex} 的产物。
65
+ * @returns {Array<{type: string, value: string, surname: string, year: string, ambiguous?: boolean, count?: number} | {type: 'text', text: string}>}
66
+ */
67
+ function inlineAuthors(text, index) {
68
+ if (typeof text !== 'string' || text === '' || !(index instanceof Map) || index.size === 0) return []
69
+ const parts = []
70
+ let plain = ''
71
+ const flush = () => {
72
+ if (plain !== '') parts.push({ type: 'text', text: plain })
73
+ plain = ''
74
+ }
75
+ let cursor = 0
76
+ AUTHOR_YEAR.lastIndex = 0
77
+ 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
81
+ plain += text.slice(cursor, match.index)
82
+ 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
+ })
90
+ cursor = match.index + match[0].length
91
+ }
92
+ plain += text.slice(cursor)
93
+ flush()
94
+ return parts
95
+ }