@ggboy123/dsh-paper-reader 1.12.0 → 1.12.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
@@ -7,7 +7,7 @@
7
7
 
8
8
  **English**: [README_EN.md](README_EN.md)
9
9
 
10
- [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.12.0**。
10
+ [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.12.1**。
11
11
 
12
12
  > 💬 **QQ 交流群:1127244508** —— 安装/使用问题、功能建议、bug 反馈都欢迎来聊。
13
13
 
package/dist/translate.js CHANGED
@@ -198,6 +198,14 @@ export async function restartTranslation(ref, dataDir, endpoint, hooks = {}, opt
198
198
  }
199
199
  /** 驱动脚本:包装 babeldoc(加结构化进度事件 + 解除单次请求的输出长度限制)。 */
200
200
  const DRIVER_PATH = fileURLToPath(new URL('../runtime/babeldoc-driver.py', import.meta.url));
201
+ /** babeldoc 报「Scanned PDF detected」时附带的处理指引(issue #26):
202
+ * 扫描件没有文字层,babeldoc 拒绝翻译属预期行为;插件不自带 OCR,
203
+ * 如实告诉用户先 OCR 再来,而不是只甩一行英文错误。 */
204
+ function scannedHint(tail) {
205
+ return /scanned pdf/i.test(tail)
206
+ ? '。这份 PDF 是扫描件(没有文字层):插件不自带 OCR,请先用 OCR 工具(如 pdfcraft、ocrmypdf)生成带文字层的版本后再翻译'
207
+ : '';
208
+ }
201
209
  /** babeldoc 的阶段名 → 中文(进度条上给人看)。 */
202
210
  const STAGE_LABELS = {
203
211
  'Parse PDF and Create Intermediate Representation': '解析 PDF',
@@ -473,7 +481,7 @@ async function launch(ref, dataDir, endpoint, bin, task, options) {
473
481
  if (error || code !== 0) {
474
482
  const detail = (tail.trim() || error?.message || '').slice(-MAX_TAIL_CHARS);
475
483
  console.error('[dsh-paper-reader] babeldoc failed:', detail);
476
- setTaskBusy(ref, task, { error: `babeldoc 执行失败: ${detail || `退出码 ${code}`}` });
484
+ setTaskBusy(ref, task, { error: `babeldoc 执行失败: ${detail || `退出码 ${code}`}${scannedHint(tail)}` });
477
485
  resolveDone();
478
486
  return;
479
487
  }
@@ -489,7 +497,7 @@ async function launch(ref, dataDir, endpoint, bin, task, options) {
489
497
  }
490
498
  if (!existsSync(zhPdfPath(ref)) && !existsSync(dualPdfPath(ref))) {
491
499
  const why = tail.trim().split('\n').pop() ?? '';
492
- setTaskBusy(ref, task, { error: `babeldoc 未产出译文 PDF${why ? `:${why}` : ''}` });
500
+ setTaskBusy(ref, task, { error: `babeldoc 未产出译文 PDF${why ? `:${why}` : ''}${scannedHint(tail)}` });
493
501
  resolveDone();
494
502
  return;
495
503
  }
package/lib/client.js CHANGED
@@ -190,6 +190,18 @@ window.__ModuleLoader__.load({
190
190
  const h = React.createElement
191
191
 
192
192
  const NS = 'dsh-paper-reader'
193
+
194
+ // 阅读器路由基址:由当前页面 URL 派生,不能写死 '/paper-reader'。
195
+ // 反向代理把 dsh web 挂到子路径时(如 fnOS 应用中心的 /app/fn-deepseek-harness),
196
+ // 以域名根为基准的绝对路径会打到代理根、被别的应用接管并返回 HTML ⇒
197
+ // fetch 的 r.json() 解析失败、文献库静默空白、上传 403。
198
+ // 本模块跑在宿主页面里,没有 <base> 可用,只能自己从 pathname 里截出前缀。
199
+ // 直连(/paper-reader/... 或根路径)时前缀为空,行为与原来一致。
200
+ function dprBase() {
201
+ const m = /^(.*\/)?paper-reader(\/|$)/.exec(location.pathname)
202
+ const prefix = m && m[1] ? m[1].replace(/\/$/, '') : ''
203
+ return prefix + '/paper-reader'
204
+ }
193
205
  const zh = {
194
206
  library: '文献库', refresh: '刷新',
195
207
  empty: '文献库为空', hint: '新建专题或上传 PDF 开始', newTopic: '新建专题',
@@ -489,7 +501,7 @@ window.__ModuleLoader__.load({
489
501
  }
490
502
 
491
503
  async function api(path, opts) {
492
- const r = await fetch('/paper-reader/api' + path, opts)
504
+ const r = await fetch(dprBase() + '/api' + path, opts)
493
505
  if (!r.ok) {
494
506
  const body = await r.json().catch(() => ({}))
495
507
  // 机器可读码/下一步端点统一挂到 Error 上(见顶层 dprApiError):调用方按 code 分支
@@ -652,7 +664,7 @@ window.__ModuleLoader__.load({
652
664
  postMessage `{type:'dpr:open', topic, name, page?, q?}` 让阅读器原地 openPaper。
653
665
  阅读器载完回 `{type:'dpr:ready'}` 握手;没握手(首开/回退)或原地换失败
654
666
  (回 `{type:'dpr:open-failed'}`)时退回「改 src 整页导航」的旧路径,保证一定切得过去。 */
655
- const readerSrcOf = (c) => `/paper-reader/?topic=${encodeURIComponent(c.topic)}&name=${encodeURIComponent(c.name)}${c.page ? '&page=' + c.page : ''}${c.q ? '&q=' + encodeURIComponent(c.q) : ''}`
667
+ const readerSrcOf = (c) => `${dprBase()}/?topic=${encodeURIComponent(c.topic)}&name=${encodeURIComponent(c.name)}${c.page ? '&page=' + c.page : ''}${c.q ? '&q=' + encodeURIComponent(c.q) : ''}`
656
668
  function sendReaderOpen(c) {
657
669
  const win = readerIframeEl && readerIframeEl.contentWindow
658
670
  if (!win) return false
@@ -751,6 +763,9 @@ window.__ModuleLoader__.load({
751
763
  // overlay 测量的暂态),按 lastSeen 加 1500ms(=切换护栏窗口宽)迟滞,免得换位
752
764
  // 撤钉又回钉,闪回当初修掉的整屏闪。
753
765
  const setStyle = (el, prop, val) => { if (el.style[prop] !== val) el.style[prop] = val }
766
+ // macOS 桌面端判定(红绿灯避让用,见 applySwap 尾部):浏览器与 Win/Linux 桌面端
767
+ // 左上角没有原生窗口控件,不该有任何行为变化。
768
+ const macElectron = /Electron/.test(navigator.userAgent) && /^Mac/.test(navigator.platform || '')
754
769
  let lastPdfTabAt = 0
755
770
  const applySwap = () => {
756
771
  const col = document.querySelector('[data-rightbar-col]')
@@ -791,6 +806,30 @@ window.__ModuleLoader__.load({
791
806
  const dockLayer = parseFloat(getComputedStyle(panel).getPropertyValue('--dsh-dockkit-dock-layer')) || 10
792
807
  setStyle(readerIframeEl, 'zIndex', frame.hasAttribute('data-rightbar-fullscreen') ? String(dockLayer + 2) : '10')
793
808
  }
809
+ // macOS 桌面端红绿灯避让(issue #22 追问实测定位):换位生效 + 侧栏收起时,右栏
810
+ // 页签条被钉到窗口最左上(实测 left=1/top=0),原生红绿灯(≈x 0..70)直接浮在
811
+ // 「论文 PDF」页签文字上;宿主自己的左上浮动控件(leadingSeat:收起侧栏的开关等,
812
+ // 实测 x 88..152)已经为红绿灯让位,但没料到页签条会被换位到左缘。
813
+ // 这里量页签条实际位置:贴近窗口左上才补 padding-left 腾出「红绿灯 + 浮动控件」
814
+ // 区,让位目标取 leadingSeat 右缘(与宿主自己的避让对齐),找不到该元素回落 76px;
815
+ // 侧栏展开(页签条远离左缘)或撤换位时自动清掉。纯量位置、不猜侧栏状态,
816
+ // 宿主以后改布局也自愈。
817
+ if (macElectron) {
818
+ try {
819
+ const hdr = col.querySelector('[class*="tabHostHeader"]')
820
+ if (hdr) {
821
+ let clear = 76
822
+ const seat = document.querySelector('[class*="leadingSeat"]')
823
+ if (seat) {
824
+ const sr = seat.getBoundingClientRect()
825
+ if (sr.top < 40 && sr.left < 120 && sr.width > 0) clear = Math.max(clear, Math.ceil(sr.right) + 6)
826
+ }
827
+ const hr = hdr.getBoundingClientRect()
828
+ const pad = eff && hr.top < 40 && hr.left < clear ? String(clear - Math.floor(hr.left)) + 'px' : ''
829
+ setStyle(hdr, 'paddingLeft', pad)
830
+ }
831
+ } catch { /* 宿主结构变了就维持现状(页签被红绿灯盖),不影响换位本身 */ }
832
+ }
794
833
  }
795
834
  let lastGood = false
796
835
  const tick = () => {
@@ -1647,7 +1686,7 @@ window.__ModuleLoader__.load({
1647
1686
  const file = e.target.files?.[0]
1648
1687
  e.target.value = ''
1649
1688
  if (!file) return
1650
- await fetch('/paper-reader/api/library/upload', {
1689
+ await fetch(dprBase() + '/api/library/upload', {
1651
1690
  method: 'POST',
1652
1691
  // header 值只允许 ISO-8859-1:中文专题名/文件名必须先编码,否则 fetch 在发请求前就抛错
1653
1692
  headers: { 'x-dpr-topic': encodeURIComponent(uploadTopic.current), 'x-dpr-name': encodeURIComponent(file.name), 'content-type': 'application/pdf' },
@@ -2139,7 +2178,7 @@ window.__ModuleLoader__.load({
2139
2178
  })
2140
2179
  }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
2141
2180
  }, [props.path])
2142
- useEffect(load, [load])
2181
+ useEffect(() => { void load() }, [load])
2143
2182
  const sourceText = !cfg ? '' : { file: t('setSourceFile'), profile: t('setSourceProfile'), env: t('setSourceEnv'), none: t('setSourceNone') }[cfg.source] || ''
2144
2183
  const save = async () => {
2145
2184
  setBusy(true); setMsg(null)
@@ -2206,7 +2245,7 @@ window.__ModuleLoader__.load({
2206
2245
  function TranslateProviderIcon({ provider, size = 22 }) {
2207
2246
  if (!provider.icon) return provider.mark || '+'
2208
2247
  return h('img', {
2209
- src: '/paper-reader/vendor/' + provider.icon, alt: '', 'aria-hidden': 'true',
2248
+ src: dprBase() + '/vendor/' + provider.icon, alt: '', 'aria-hidden': 'true',
2210
2249
  'data-dpr-provider-icon': provider.id,
2211
2250
  style: { width: size, height: size, objectFit: 'contain', display: 'block', background: '#fff', borderRadius: 4 },
2212
2251
  })
@@ -2247,7 +2286,7 @@ window.__ModuleLoader__.load({
2247
2286
  setDeleteArmed(false)
2248
2287
  }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
2249
2288
  }, [])
2250
- useEffect(load, [load])
2289
+ useEffect(() => { void load() }, [load])
2251
2290
 
2252
2291
  const chooseProvider = (id) => {
2253
2292
  modelRequest.current += 1
@@ -2525,7 +2564,7 @@ window.__ModuleLoader__.load({
2525
2564
  api('/theme/config').then((d) => { setCfg(d); writeThemeMirror(d) })
2526
2565
  .catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
2527
2566
  }, [])
2528
- useEffect(load, [load])
2567
+ useEffect(() => { void load() }, [load])
2529
2568
  const save = async (patch) => {
2530
2569
  setBusy(true); setMsg(null)
2531
2570
  try {
@@ -2574,6 +2613,13 @@ window.__ModuleLoader__.load({
2574
2613
  )
2575
2614
  }
2576
2615
 
2616
+ /* 卸载契约(设置分区切走即卸载):本面板里所有 `useEffect` 的回调必须返回 **undefined 或清理函数**。
2617
+ React 会把 effect 的返回值当清理函数保存,切走分区卸载卡片时直接调用它。
2618
+ TranslateSettingsCard 的 load() 返回 api(...) 的 Promise;写成 `useEffect(load, [load])`
2619
+ 等于把 Promise 存成 destroy,卸载时 React 调用它 → `TypeError: … is not a function`。
2620
+ 提交阶段的错误越过本卡片的 SlotErrorBoundary,冒到 `sidebar.settings` 外壳,
2621
+ 外壳按 single 槽 abdicate ⇒ 设置弹窗自动关闭 + 左下角账号/设置入口消失(刷新才恢复)。
2622
+ 其余 load() 目前是块体(返回 undefined),仍统一包一层,避免以后加 `return` 时再踩。 */
2577
2623
  function SettingsPanel() {
2578
2624
  return h('div', { style: { maxWidth: '560px' }, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-surface': 'settings-modal' },
2579
2625
  h(EndpointCard, {
@@ -2612,7 +2658,7 @@ window.__ModuleLoader__.load({
2612
2658
  })
2613
2659
  }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
2614
2660
  }, [])
2615
- useEffect(load, [load])
2661
+ useEffect(() => { void load() }, [load])
2616
2662
  const sourceText = !cfg ? '' : { file: t('setSourceFile'), profile: t('setSourceProfile'), env: t('setSourceEnv'), none: t('setSourceNone') }[cfg.source] || ''
2617
2663
  const payload = () => ({
2618
2664
  mode: form.mode,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ggboy123/dsh-paper-reader",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "DeepSeek Harness 插件:论文伴读工作台 — PDF 转录 / 检索 / 原生对话伴读 + 内置阅读器页面。",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/reader/index.html CHANGED
@@ -678,6 +678,39 @@
678
678
 
679
679
  <script>
680
680
  'use strict';
681
+ /* 资源与接口基址:/paper-reader 挂在什么路径下由部署环境决定,不能写死到域名根。
682
+ 反向代理把 dsh web 挂到子路径时(如 fnOS 应用中心的 /app/fn-deepseek-harness),
683
+ 以域名根为基准的绝对路径会打到代理根、被别的应用接管并返回 HTML,后果有二:
684
+ · 接口请求拿到 HTML,r.json() 解析失败 ⇒ 文献库静默空白、上传 403
685
+ · pdf.js 的 ES 模块拿不到 JS ⇒ 浏览器按 MIME 拒绝,报
686
+ Failed to fetch dynamically imported module
687
+ 后者尤其隐蔽:反代注入的 fetch/XHR/属性改写钩子**改不到**原生模块动态 import
688
+ 与 Worker 的 workerSrc(它们不经过 fetch),只能在这里自己算对。
689
+
690
+ PR_ASSET_BASE 由当前页面 URL 派生,直连与子路径反代两种部署都对。
691
+ <link>/<script> 保持绝对路径不动:它们在解析期就被反代改写过,
692
+ 且 test/reader-script.mjs 约定本页只有一个 <script> 块,基址只能定义在这里。
693
+
694
+ 降级链(与文件其余部分同风格:绝不因环境缺失抛错):
695
+ ① location.href 可解析 → 由它派生(浏览器与 jsdom 都是这条)
696
+ ② 否则退回 '/paper-reader/' 拼绝对 URL(老 vm 测试沙箱只给了 location.search)
697
+ 绝不假设 URL 全局存在——顶层抛 ReferenceError 会让整页脚本停摆,比路径错更糟。 */
698
+ const PR_ASSET_BASE = (() => {
699
+ const fallback = '/paper-reader/';
700
+ try {
701
+ const href = typeof location !== 'undefined' && location.href;
702
+ if (typeof href !== 'string' || !href) return fallback;
703
+ const u = new URL(href); // ② 无 URL 时进 catch
704
+ if (!u.pathname.endsWith('/')) u.pathname += '/'; // 兼容 /paper-reader 无尾斜杠
705
+ u.search = '';
706
+ u.hash = '';
707
+ return u.href;
708
+ } catch (e) {
709
+ return fallback;
710
+ }
711
+ })();
712
+ const PR_API_BASE = PR_ASSET_BASE + 'api';
713
+
681
714
  /* 深色首帧判定(方案 §A2.2 的四级降级链 + §A2.5「朝亮色回退」)——必须在首帧**之前**同步完成,
682
715
  否则会出现「先白后黑」的白闪(Firefox/pdf.js #18680 同款公开案例)。放在模块脚本最前面:
683
716
  解析期同步执行、早于首帧,且**不新增第二个 <script> 块**(test/reader-script.mjs 的提取约定)。
@@ -735,7 +768,7 @@ const iconHtml = (name) => `<svg class="ic${name === 'spin' ? ' spin' : ''}" vie
735
768
  // 静态按钮按 data-icon 注入一次;动态按钮(翻译/重翻/模式切换)在状态变化时用同一函数换图标
736
769
  // #pager:翻页条挪到阅读区底部(#main 内)后也要扫到,否则上一页/下一页图标空白
737
770
  document.querySelectorAll('#bar [data-icon], #pager [data-icon], #find-window [data-icon], #note-window [data-icon]').forEach((b) => b.insertAdjacentHTML('afterbegin', iconHtml(b.dataset.icon)));
738
- const api = (p, opts) => fetch('/paper-reader/api' + p, opts).then(async (r) => {
771
+ const api = (p, opts) => fetch(PR_API_BASE + p, opts).then(async (r) => {
739
772
  if (!r.ok) {
740
773
  // 服务端错误体有两种:{error}(参数/权限)与 {reason}(zh/generate 的未启动原因,带完整说明)
741
774
  const body = await r.json().catch(() => ({}));
@@ -969,7 +1002,7 @@ function pdfUrl(variant) {
969
1002
  const q = `topic=${encodeURIComponent(current.topic)}&name=${encodeURIComponent(current.name)}`;
970
1003
  // 不带 t=Date.now():/api/pdf 已有 ETag(文件 mtime+size),浏览器会 304 复用;
971
1004
  // 重新翻译后 ETag 自动变化,不会拿到旧译文。
972
- return `/paper-reader/api/pdf?${q}${variant ? '&variant=' + variant : ''}`;
1005
+ return `${PR_API_BASE}/pdf?${q}${variant ? '&variant=' + variant : ''}`;
973
1006
  }
974
1007
 
975
1008
  function syncTranscribeButton() {
@@ -2672,7 +2705,7 @@ function cfgProviderIcon(provider) {
2672
2705
  }
2673
2706
  const img = document.createElement('img');
2674
2707
  img.className = 'cfg-icon' + (provider.mono ? ' mono' : '');
2675
- img.src = '/paper-reader/vendor/' + provider.icon;
2708
+ img.src = PR_ASSET_BASE + 'vendor/' + provider.icon;
2676
2709
  img.alt = '';
2677
2710
  img.setAttribute('aria-hidden', 'true');
2678
2711
  img.dataset.cfgProviderIcon = provider.id;
@@ -2968,15 +3001,15 @@ $('cfg-save-new').onclick = () => saveCfg(true);
2968
3001
  let pdfjsReadyP = null;
2969
3002
  function ensurePdfjs() {
2970
3003
  if (!pdfjsReadyP) {
2971
- pdfjsReadyP = import('/paper-reader/vendor/pdf.min.mjs').then(
3004
+ pdfjsReadyP = import(PR_ASSET_BASE + 'vendor/pdf.min.mjs').then(
2972
3005
  (m) => {
2973
3006
  window.pdfjsLib = m;
2974
- m.GlobalWorkerOptions.workerSrc = '/paper-reader/vendor/pdf.worker.min.mjs';
3007
+ m.GlobalWorkerOptions.workerSrc = PR_ASSET_BASE + 'vendor/pdf.worker.min.mjs';
2975
3008
  return m;
2976
3009
  },
2977
3010
  (e) => {
2978
3011
  pdfjsReadyP = null; // 失败后清缓存:瞬时故障不至于让本页签永久坏掉,下次 loadPdf 重试
2979
- throw new Error('pdf.js 加载失败(/paper-reader/vendor/pdf.min.mjs):' + (e && e.message ? e.message : e));
3012
+ throw new Error(`pdf.js 加载失败(${PR_ASSET_BASE}vendor/pdf.min.mjs):` + (e && e.message ? e.message : e));
2980
3013
  },
2981
3014
  );
2982
3015
  }
@@ -4383,28 +4416,41 @@ function showAskPop(o) {
4383
4416
 
4384
4417
  document.addEventListener('mousedown', (e) => { downPt = { x: e.clientX, y: e.clientY }; }, true);
4385
4418
 
4386
- /* 三击选中整段(issue #22-3):文本层没有段落语义,原生三击会选中整个 textLayer(≈整页)。
4387
- 行盒分组版:先把 span 按 top 归并成「行」(行盒 = 成员并集),再从命中行向上下扩——
4388
- 同列(水平区间有重叠,双栏左右栏因此自然断开)且行间竖直间隙 ≤ 0.45×行高的连续行算同段。
4389
- pdf.js 的 span 高度≈字号而非行距,行间间隙明显小于段间距,这个阈值分得开两种间隙。
4390
- 上一版按 span 连通 + 「分量占全页 60% 就放弃」的守卫会在单栏满页段落上误判成「只选一行」,
4391
- 已换成绝对行数封顶(>60 行视为整页误并,退回命中行)。设好选区后走同一条
4392
- mouseup →「选中即问」链路,不另接气泡。 */
4419
+ /* 三击序列的首击落点(见 dprPickParagraph 处的三击 handler):双击弹出的提问气泡可能
4420
+ 恰好盖住原位置,第 3 击的 target 就成了气泡 div 而非 textLayer——三击选段会静默失效
4421
+ (退回原生行为,实测选中一个词)。handler 在 detail≥3 且 target 不在 textLayer 时,
4422
+ 用这里记下的首击落点回退(要求近距离 + 短间隔,只 reinterpret 同一次连击)。 */
4423
+ let dprLastTlHit = null;
4393
4424
  document.addEventListener('mousedown', (e) => {
4394
- if (e.detail < 3) return;
4395
4425
  const tl = e.target && e.target.closest ? e.target.closest('.textLayer') : null;
4396
- if (!tl || !tl.isConnected) return;
4397
- const items = Array.from(tl.querySelectorAll('span'))
4398
- .filter((s) => (s.textContent || '').trim())
4399
- .map((s) => { const r = s.getBoundingClientRect(); return { s, l: r.left, r2: r.right, t: r.top, b: r.bottom }; })
4400
- .filter((r) => r.r2 > r.l && r.b > r.t)
4401
- .sort((a, b) => a.t - b.t || a.l - b.l);
4402
- if (!items.length) return;
4403
- // 1) 归行:top 相差 ≤2px 的 span 属于同一行
4426
+ if (tl && tl.isConnected) dprLastTlHit = { x: e.clientX, y: e.clientY, at: Date.now(), tl };
4427
+ }, true);
4428
+
4429
+ /* 三击选中整段(issue #22-3,#22 追加反馈修复跨栏误并):文本层没有段落语义,原生三击会
4430
+ 选中整个 textLayer(≈整页)。核心算法在 dprPickParagraph(纯函数,可测),事件层只做
4431
+ DOM 度量与选区落地。设好选区后走同一条 mouseup →「选中即问」链路,不另接气泡。 */
4432
+ /* 行盒分组版,两处与初版不同的关键点(都是双栏/对照版的真实教训,见 issue #22 追加反馈):
4433
+ · 归行不能只看 top:双栏论文同一行的左右栏、babeldoc 对照版的原文块与译文块 top 相同,
4434
+ 只按 top 归并会得到一条横贯全页的「行」,它和谁都水平重叠 ⇒ 扩段整页串联 ⇒ 撞行数
4435
+ 上限退回单行——「有时候一行 / 有时候超长一段 / 对照版三击没用」三个症状同一根因。
4436
+ 现在加水平相邻判据:同行还得间隙 ≤ gapX(词距并入、栏沟断开)。
4437
+ · 扩段不能只看数组相邻行:正确分行后,(t,l) 排序里双栏相邻项恰是**另一栏**,逐相邻扩
4438
+ 会在跨栏处立刻断掉 ⇒ 永远只选一行。现在按「竖直间隙小 + 与段落栏区间有重叠」在
4439
+ 附近行里扫描跳过异栏行;栏区间每并一行取**交集**,防止居中标题把区间 creep 到另一栏。
4440
+ 阈值依据(真浏览器实测 GFS 双栏 + babeldoc 对照版的 textLayer 盒):行内词距(含两端对齐
4441
+ 拉伸)≤ 2×行高(≈2% 页宽),双栏栏沟 ≈ 4% 页宽(GFS 在 1368px 页宽下 54px),对照版栏沟
4442
+ ≥ 27% 页宽。gapX = max(2×行高, 3% 页宽) 落在词距与栏沟之间;比它更宽的词距偶发拆行也无害——
4443
+ 同 top 的两个碎片在扩段时竖直间隙为负、水平与栏区间重叠,会立即并回。
4444
+ 竖直方向 pdf.js 的 span 高度≈字号而非行距,行间间隙明显小于段间距,0.45×行高分得开。 */
4445
+ function dprPickParagraph(items, x, y, pageW) {
4446
+ // items: [{s, l, r2, t, b}](已按 t,l 排序的 span 盒);返回 {first, last, hit} 或 null
4447
+ // 1) 归行:top 相差 ≤2px 且水平相邻(间隙 ≤ gapX)
4404
4448
  const lines = [];
4405
4449
  for (const it of items) {
4406
4450
  const ln = lines[lines.length - 1];
4407
- if (ln && Math.abs(ln.t - it.t) <= 2) {
4451
+ const h = Math.max(1, it.b - it.t);
4452
+ const gapX = Math.max(2 * h, pageW * 0.03);
4453
+ if (ln && Math.abs(ln.t - it.t) <= 2 && it.l - ln.r2 <= gapX) {
4408
4454
  ln.b = Math.max(ln.b, it.b); ln.l = Math.min(ln.l, it.l); ln.r2 = Math.max(ln.r2, it.r2);
4409
4455
  ln.items.push(it);
4410
4456
  } else {
@@ -4412,21 +4458,60 @@ document.addEventListener('mousedown', (e) => {
4412
4458
  }
4413
4459
  }
4414
4460
  // 2) 命中行(±3px 容差)
4415
- const idx = lines.findIndex((x) => e.clientY >= x.t - 3 && e.clientY <= x.b + 3 && e.clientX >= x.l - 3 && e.clientX <= x.r2 + 3);
4416
- if (idx < 0) return;
4417
- e.preventDefault(); // 替换原生三击(整页全选)
4418
- // 3) 向上下扩段:同列 + 竖直间隙小
4461
+ const idx = lines.findIndex((r) => y >= r.t - 3 && y <= r.b + 3 && x >= r.l - 3 && x <= r.r2 + 3);
4462
+ if (idx < 0) return null;
4463
+ // 3) 向上下扩段:竖直间隙 ≤ 0.45×行高 且 与栏区间有水平重叠(跳过异栏行继续扫)
4419
4464
  const lh = Math.max(5, lines[idx].b - lines[idx].t);
4420
4465
  const gapY = lh * 0.45;
4421
- const colOver = (a, b) => Math.min(a.r2, b.r2) - Math.max(a.l, b.l) > 0;
4422
- let lo = idx, hi = idx;
4423
- while (lo > 0 && lines[lo].t - lines[lo - 1].b <= gapY && colOver(lines[lo], lines[lo - 1])) lo--;
4424
- while (hi < lines.length - 1 && lines[hi + 1].t - lines[hi].b <= gapY && colOver(lines[hi], lines[hi + 1])) hi++;
4425
- if (hi - lo + 1 > 60) lo = hi = idx; // 整页误并:退回命中行,宁可少选不多选
4426
- const first = lines[lo].items[0].s; // 段首 = 首行最左
4427
- const last = lines[hi].items[lines[hi].items.length - 1].s; // 段尾 = 末行最右
4466
+ const up = [], down = [];
4467
+ let boxL = lines[idx].l, boxR = lines[idx].r2;
4468
+ let curT = lines[idx].t, curB = lines[idx].b;
4469
+ for (let i = idx - 1; i >= 0; i--) {
4470
+ const c = lines[i];
4471
+ if (curT - c.b > gapY) break; // 行按 t 升序,往上间隙只增不减
4472
+ if (Math.min(boxR, c.r2) - Math.max(boxL, c.l) <= 0) continue; // 异栏:跳过继续找同栏
4473
+ up.push(c);
4474
+ curT = c.t;
4475
+ const nl = Math.max(boxL, c.l), nr = Math.min(boxR, c.r2);
4476
+ if (nr - nl > 0) { boxL = nl; boxR = nr; } // 栏区间取交集,防 creep
4477
+ }
4478
+ for (let i = idx + 1; i < lines.length; i++) {
4479
+ const c = lines[i];
4480
+ if (c.t - curB > gapY) break;
4481
+ if (Math.min(boxR, c.r2) - Math.max(boxL, c.l) <= 0) continue;
4482
+ down.push(c);
4483
+ curB = c.b;
4484
+ const nl = Math.max(boxL, c.l), nr = Math.min(boxR, c.r2);
4485
+ if (nr - nl > 0) { boxL = nl; boxR = nr; }
4486
+ }
4487
+ const members = [...up.reverse(), lines[idx], ...down];
4488
+ if (members.length > 60) return { first: lines[idx].items[0].s, last: lines[idx].items[lines[idx].items.length - 1].s, hit: lines[idx] };
4489
+ return { first: members[0].items[0].s, last: members[members.length - 1].items[members[members.length - 1].items.length - 1].s, hit: lines[idx] };
4490
+ }
4491
+ document.addEventListener('mousedown', (e) => {
4492
+ if (e.detail < 3) return;
4493
+ const tl = e.target && e.target.closest ? e.target.closest('.textLayer') : null;
4494
+ let px = e.clientX, py = e.clientY, tlEl = tl;
4495
+ if (!tlEl || !tlEl.isConnected) {
4496
+ // 第 3 击被双击弹出的气泡挡住:回退到同一次连击的首击落点(近距离 + 短间隔才认)
4497
+ const h = dprLastTlHit;
4498
+ if (!h || !h.tl || !h.tl.isConnected || Date.now() - h.at > 600
4499
+ || Math.abs(h.x - e.clientX) + Math.abs(h.y - e.clientY) > 8) return;
4500
+ px = h.x; py = h.y; tlEl = h.tl;
4501
+ }
4502
+ const tlRect = tlEl.getBoundingClientRect();
4503
+ const items = Array.from(tlEl.querySelectorAll('span'))
4504
+ .filter((s) => (s.textContent || '').trim())
4505
+ .map((s) => { const r = s.getBoundingClientRect(); return { s, l: r.left, r2: r.right, t: r.top, b: r.bottom }; })
4506
+ .filter((r) => r.r2 > r.l && r.b > r.t)
4507
+ .sort((a, b) => a.t - b.t || a.l - b.l);
4508
+ const pick = dprPickParagraph(items, px, py, tlRect.width);
4509
+ if (!pick) return;
4510
+ e.preventDefault(); // 替换原生三击(整页全选)
4511
+ const first = pick.first; // 段首 = 首行最左
4512
+ const last = pick.last; // 段尾 = 末行最右
4428
4513
  // 端点必须落在**文本节点**上(setStart(spanEl, 0) 会得到元素端点):笔记锚定的
4429
- // noteAnchorFromSelection → offsetOf 只认文本节点,元素端点会让笔记画不出波浪线
4514
+ // noteAnchorFromSelection → offsetOf 只认文本节点,元素端点会让笔记画不出虚线框
4430
4515
  // (实测教训:选区正常、气泡正常,唯独笔记锚定失败)。
4431
4516
  const firstText = (sp) => { for (let n = sp.firstChild; n; n = n.nextSibling) if (n.nodeType === 3 && n.nodeValue) return n; return null; };
4432
4517
  const lastText = (sp) => { for (let n = sp.lastChild; n; n = n.previousSibling) if (n.nodeType === 3 && n.nodeValue) return n; return null; };