An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Merge overlapping PDF text annotation rectangles https://github.com/siyuan-note/siyuan/issues/19310
Daniel61afc5e11d52
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.tsindex 046bbca589..c4b4d51392 100644--- a/app/src/asset/anno.ts+++ b/app/src/asset/anno.ts@@ -33,6 +33,7 @@ import {registerPdfInstance,} from "./annoRuntime";import {appendPdfAnnotationId} from "../editor/pdfAssetLink";+import {isPdfRectAnnotation, mergePdfTextAnnotationRects} from "./pdfTextAnnotation";export {destroyAnno, registerPdfInstance, unregisterPdfInstance} from "./annoRuntime";@@ -619,9 +620,8 @@ const hideToolbarMenu = (element: HTMLElement) => {element.querySelector(".pdf__util").classList.add("fn__none");};-const isRectAnnotationElement = (element: HTMLElement) => element.dataset.mode === "rect" ||- (element.dataset.mode === "" && element.childElementCount === 1 &&- /-P\d+-\d{14}-\w{7}$/.test(element.dataset.content));+const isRectAnnotationElement = (element: HTMLElement) =>+ isPdfRectAnnotation(element.dataset.mode, element.childElementCount, element.dataset.content);let rectElement: HTMLElement;const showToolbar = (element: HTMLElement, range: Range, target?: HTMLElement) => {@@ -731,30 +731,16 @@ const getHightlightCoordsByRange = (pdf: any, color: string) => {range.setEndAfter(getTextNode(startPage.textLayer.div, false));}- // push 入的是 convertToPdfPoint 拼接后的 4 元素数组,因此 startSelected 实际为 number[][]- const startSelected: number[][] = [];- mergeRects(range).forEach(function (r) {- startSelected.push(- startViewport.convertToPdfPoint(r.left - startPageRect.x,- r.top - startPageRect.y).concat(startViewport.convertToPdfPoint(r.right - startPageRect.x,- r.bottom - startPageRect.y)),- );- });+ const startSelected = getTextAnnotationCoords(range, startViewport, startPageRect);- const endSelected: number[][] = [];+ let endSelected: number[][] = [];if (startIndex !== endIndex) {focusByRange(cloneRange);const endPage = pdf.pdfViewer.getPageView(endIndex);const endPageRect = endPage.canvas.getClientRects()[0];const endViewport = endPage.viewport;cloneRange.setStart(getTextNode(endPage.textLayer.div, true), 0);- mergeRects(cloneRange).forEach(function (r) {- endSelected.push(- endViewport.convertToPdfPoint(r.left - endPageRect.x,- r.top - endPageRect.y).concat(endViewport.convertToPdfPoint(r.right - endPageRect.x,- r.bottom - endPageRect.y)),- );- });+ endSelected = getTextAnnotationCoords(cloneRange, endViewport, endPageRect);}const id = Lute.NewNodeID();@@ -878,23 +864,11 @@ const getHightlightCoordsByRect = (pdf: any, color: string, rectResizeElement: Hreturn result;};-const mergeRects = (range: Range) => {- const rects = range.getClientRects();- const mergedRects: { left: number, top: number, right: number, bottom: number }[] = [];- let lastTop: number = undefined;- Array.from(rects).forEach(item => {- if (item.height === 0 || item.width === 0) {- return;- }- if (typeof lastTop === "undefined" || Math.abs(lastTop - item.top) > 4) {- mergedRects.push({left: item.left, top: item.top, right: item.right, bottom: item.bottom});- lastTop = item.top;- } else {- mergedRects[mergedRects.length - 1].right = item.right;- }- });- return mergedRects;-};+const getTextAnnotationCoords = (range: Range, viewport: any, pageRect: DOMRect) =>+ mergePdfTextAnnotationRects(Array.from(range.getClientRects())+ .filter(rect => rect.width > 0 && rect.height > 0)+ .map(rect => viewport.convertToPdfPoint(rect.left - pageRect.x, rect.top - pageRect.y)+ .concat(viewport.convertToPdfPoint(rect.right - pageRect.x, rect.bottom - pageRect.y))));export const getPdfInstance = (element: HTMLElement) => {const registeredInstance = getRegisteredPdfInstance(element);@@ -971,13 +945,16 @@ const showHighlight = (selected: IPdfAnno, pdf: any, hl?: boolean) => {}// 使用 setAttribute 构建元素,避免将 .sya 中的数据拼接到 HTML 中 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fqpw-c3pj-w8g9const rectDiv = document.createElement("div");+ const isRectAnnotation = isPdfRectAnnotation(selected.mode, selected.coords.length, selected.content);rectDiv.className = "pdf__rect popover__block";rectDiv.setAttribute("data-node-id", selected.id);rectDiv.setAttribute("data-relations", selected.ids ? selected.ids.join(",") : "");- rectDiv.setAttribute("data-mode", selected.mode);+ rectDiv.setAttribute("data-mode", isRectAnnotation ? "rect" : (selected.mode || "text"));rectDiv.setAttribute("data-type", selected.type);rectDiv.style.setProperty("--pdf-annotation-color", selected.color);- selected.coords.forEach((rect) => {+ // 旧标注只在显示时合并矩形,保留文件中的原始坐标和矩形框选标注。+ const coords = isRectAnnotation ? selected.coords : mergePdfTextAnnotationRects(selected.coords);+ coords.forEach((rect) => {const rectChild = document.createElement("div");if (!setRectPosition(rectChild, page, rect, viewport)) {return;@@ -985,8 +962,7 @@ const showHighlight = (selected: IPdfAnno, pdf: any, hl?: boolean) => {rectDiv.append(rectChild);});rectDiv.setAttribute("data-content", selected.content);- if (isRectAnnotationElement(rectDiv)) {- rectDiv.dataset.mode = "rect";+ if (isRectAnnotation) {rectDiv.style.touchAction = "none";Array.from(rectDiv.children).forEach((rectChild: HTMLElement) => {["n", "e", "s", "w"].forEach(direction => {diff --git a/app/src/asset/pdfTextAnnotation.test.ts b/app/src/asset/pdfTextAnnotation.test.tsnew file mode 100644index 0000000000..ca4ed567a1--- /dev/null+++ b/app/src/asset/pdfTextAnnotation.test.ts@@ -0,0 +1,112 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {isPdfRectAnnotation, mergePdfTextAnnotationRects, mergeTextAnnotationRects} from "./pdfTextAnnotation";++describe("PDF text annotation rectangles", () => {+ it("removes nested rectangles and joins adjacent fragments modeled on the issue 19310 screenshot", () => {+ const coords = [+ [286, 190, 483, 244],+ [487, 190, 1119, 244],+ [487, 199, 1119, 234],+ [87, 259, 521, 312],+ [87, 268, 521, 302],+ [527, 259, 1119, 312],+ [527, 268, 1119, 302],+ [87, 327, 483, 381],+ [87, 336, 483, 371],+ [483, 327, 723, 381],+ ];+ const original = structuredClone(coords);+ const result = mergePdfTextAnnotationRects(coords);+ assert.deepEqual(result, [+ [286, 190, 1119, 244],+ [87, 259, 1119, 312],+ [87, 327, 723, 381],+ ]);+ assert.deepEqual(coords, original);+ assert.deepEqual(mergePdfTextAnnotationRects(result), result);+ });++ it("keeps the full bounds when duplicates and right-to-left fragments arrive out of order", () => {+ assert.deepEqual(mergePdfTextAnnotationRects([+ [30, 20, 60, 0],+ [60, 0, 30, 20],+ [0, 1, 35, 21],+ [5, 4, 20, 16],+ ]), [[0, 0, 60, 21]]);+ });++ it("rechecks earlier fragments when a connecting rectangle arrives last", () => {+ assert.deepEqual(mergePdfTextAnnotationRects([+ [0, 0, 10, 10],+ [20, 0, 30, 10],+ [10, 0, 20, 10],+ ]), [[0, 0, 30, 10]]);+ });++ it("preserves separate lines, columns and gaps wider than text fragment spacing", () => {+ const coords = [+ [0, 0, 30, 10],+ [0, 8, 30, 18],+ [0, 18, 30, 28],+ [50, 0, 80, 10],+ [84, 0, 94, 10],+ ];+ assert.deepEqual(mergePdfTextAnnotationRects(coords), coords);+ });++ it("joins the small fragment gaps modeled on the follow-up screenshot at every scale", () => {+ const coords = [+ [106, 34, 192, 56], [194, 34, 467, 56],+ [20, 64, 209, 86], [212, 64, 467, 86],+ [20, 94, 191, 116], [194, 94, 294, 116],+ ];+ const expected = [[106, 34, 467, 56], [20, 64, 467, 86], [20, 94, 294, 116]];+ [0.25, 0.5, 1, 2, 4].forEach(scale => {+ assert.deepEqual(mergePdfTextAnnotationRects(coords.map(rect => rect.map(value => value * scale))),+ expected.map(rect => rect.map(value => value * scale)));+ });+ });++ it("handles different text heights without losing the lower or left edge", () => {+ assert.deepEqual(mergePdfTextAnnotationRects([+ [20, 2, 50, 18],+ [0, 0, 30, 20],+ ]), [[0, 0, 50, 20]]);+ });++ it("produces the same geometry at different scales", () => {+ const coords = [[0, 0, 30, 20], [20, 1, 50, 21], [0, 30, 50, 50]];+ const expected = [[0, 0, 50, 21], [0, 30, 50, 50]];+ [0.25, 0.5, 1, 2, 4].forEach(scale => {+ assert.deepEqual(mergePdfTextAnnotationRects(coords.map(rect => rect.map(value => value * scale))),+ expected.map(rect => rect.map(value => value * scale)));+ });+ });++ it("preserves input reading order for scrolling to existing annotations", () => {+ assert.deepEqual(mergePdfTextAnnotationRects([+ [0, 100, 20, 120],+ [0, 50, 20, 70],+ [20, 100, 40, 120],+ ]), [[0, 100, 40, 120], [0, 50, 20, 70]]);+ });++ it("ignores empty and non-finite rectangles without changing valid input", () => {+ assert.deepEqual(mergePdfTextAnnotationRects([+ [0, 0, 0, 20], [0, 0, 20, 0], [0, 0, NaN, 10], [0, 0, Infinity, 10],+ [10, 20, 30, 40],+ ]), [[10, 20, 30, 40]]);+ assert.deepEqual(mergeTextAnnotationRects([]), []);+ });++ it("recognizes legacy rectangle annotations before text rectangles are merged", () => {+ const content = "example-P2-20260911123456-abcdefg";+ assert.equal(isPdfRectAnnotation("rect", 1, "custom name"), true);+ assert.equal(isPdfRectAnnotation("", 1, content), true);+ assert.equal(isPdfRectAnnotation(undefined, 1, content), true);+ assert.equal(isPdfRectAnnotation("", 2, content), false);+ assert.equal(isPdfRectAnnotation("text", 1, content), false);+ assert.equal(isPdfRectAnnotation("", 1, "selected text"), false);+ });+});diff --git a/app/src/asset/pdfTextAnnotation.ts b/app/src/asset/pdfTextAnnotation.tsnew file mode 100644index 0000000000..9b6b42b13e--- /dev/null+++ b/app/src/asset/pdfTextAnnotation.ts@@ -0,0 +1,59 @@+import type {RectBounds} from "./rectAnnotationResize";++export const isPdfRectAnnotation = (mode: string, rectCount: number, content: string) => mode === "rect" ||+ (!mode && rectCount === 1 && /-P\d+-\d{14}-\w{7}$/.test(content));++const contains = (outer: RectBounds, inner: RectBounds) => outer.left <= inner.left &&+ outer.top <= inner.top && outer.right >= inner.right && outer.bottom >= inner.bottom;++const canMerge = (a: RectBounds, b: RectBounds) => {+ if (contains(a, b) || contains(b, a)) {+ return true;+ }+ const minHeight = Math.min(a.bottom - a.top, b.bottom - b.top);+ const overlap = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);+ const centerDistance = Math.abs((a.top + a.bottom) - (b.top + b.bottom)) / 2;+ // 用文字高度判断同一行,避免缩放改变合并结果;保留行间和分栏中的空白。+ // 同行片段间允许四分之一文字高度的排版间距,避免在字间留下内部边框。+ return overlap >= minHeight * 0.8 && centerDistance <= minHeight * 0.25 &&+ Math.max(a.left, b.left) <= Math.min(a.right, b.right) + minHeight * 0.25;+};++export const mergeTextAnnotationRects = (rects: readonly RectBounds[]): RectBounds[] => {+ const result: RectBounds[] = [];+ rects.forEach(rect => {+ if (![rect.left, rect.top, rect.right, rect.bottom].every(Number.isFinite) ||+ rect.right <= rect.left || rect.bottom <= rect.top) {+ return;+ }+ let merged = {...rect};+ let insertAt = result.length;+ for (let i = 0; i < result.length;) {+ const previous = result[i];+ if (!canMerge(previous, merged)) {+ i++;+ continue;+ }+ merged = {+ left: Math.min(previous.left, merged.left),+ top: Math.min(previous.top, merged.top),+ right: Math.max(previous.right, merged.right),+ bottom: Math.max(previous.bottom, merged.bottom),+ };+ insertAt = Math.min(insertAt, i);+ result.splice(i, 1);+ // 合并后的边界可能包含前面的矩形,重新检查并保留原有选区顺序。+ i = 0;+ }+ result.splice(insertAt, 0, merged);+ });+ return result;+};++export const mergePdfTextAnnotationRects = (coords: readonly number[][]): number[][] =>+ mergeTextAnnotationRects(coords.map(rect => ({+ left: Math.min(rect[0], rect[2]),+ top: Math.min(rect[1], rect[3]),+ right: Math.max(rect[0], rect[2]),+ bottom: Math.max(rect[1], rect[3]),+ }))).map(rect => [rect.left, rect.top, rect.right, rect.bottom]);