Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(pdf): list annotations in the sidebar as soon as they are drawn
Elian Doran42ade8c5ac75
diff --git a/packages/pdfjs-viewer/e2e/annotation-sidebar.spec.ts b/packages/pdfjs-viewer/e2e/annotation-sidebar.spec.tsnew file mode 100644index 0000000000..676f7b1eac--- /dev/null+++ b/packages/pdfjs-viewer/e2e/annotation-sidebar.spec.ts@@ -0,0 +1,127 @@+import { expect, type FrameLocator, type Page, test } from "@playwright/test";++/**+ * Covers what the sidebar is told about the annotations in the document.+ *+ * The list is built from the loaded document, which is the file as it was opened — pdf.js keeps+ * what the reader draws in its editor layer until the file is written back. Annotations made in+ * this session therefore have to be merged in from the editor, or the panel stays empty however+ * much is annotated (#11059).+ */++test("lists an annotation as soon as it is drawn, with no save", async ({ page, context }) => {+ await context.route("**/sample.pdf", (route) => route.fulfill({+ body: textPdf(), contentType: "application/pdf"+ }));+ await recordAnnotationLists(page);+ const viewer = await openHarness(page);++ await enterHighlightMode(viewer);+ await highlightFirstWords(page, viewer);++ // No save has happened, and none is needed: the entry is in the editor, so it is in the list.+ await expect.poll(() => lastList(page)).toEqual([+ expect.objectContaining({ type: "highlight", pageNumber: 1 })+ ]);+ const [ entry ] = await lastList(page);++ // Its id is the editor's, which is the id of the element it renders — so the sidebar can+ // navigate to it. Nothing in the document carries a matching data-annotation-id yet.+ const frame = page.frame({ url: /viewer\.html/ });+ if (!frame) throw new Error("Viewer frame not found");+ expect(await frame.evaluate((id) => !!document.getElementById(id), entry.id)).toBe(true);+});++test("keeps listing it once the editing state changes again", async ({ page, context }) => {+ await context.route("**/sample.pdf", (route) => route.fulfill({+ body: textPdf(), contentType: "application/pdf"+ }));+ await recordAnnotationLists(page);+ const viewer = await openHarness(page);++ await enterHighlightMode(viewer);+ await highlightFirstWords(page, viewer);+ await expect.poll(() => lastList(page)).toHaveLength(1);++ // The list is rebuilt on every editing event. Rebuilt from the document alone it came back+ // empty, so an annotation appeared only in the gap between a save and the next edit.+ const frame = page.frame({ url: /viewer\.html/ });+ if (!frame) throw new Error("Viewer frame not found");+ await frame.evaluate(() => {+ (window as any).PDFViewerApplication.eventBus.dispatch("editingstateschanged", {+ source: null, details: { hasSomethingToUndo: true }+ });+ });++ await page.waitForTimeout(1000);+ expect(await lastList(page)).toHaveLength(1);+});++/** Records every annotation list the parent receives, as the Trilium client would. */+async function recordAnnotationLists(page: Page) {+ await page.addInitScript(() => {+ if (window.top !== window) return;+ (window as any).annotationLists = [];+ window.addEventListener("message", (event: any) => {+ if (event.data?.type === "pdfjs-viewer-annotations") {+ (window as any).annotationLists.push(event.data.annotations);+ }+ });+ });+}++function lastList(page: Page): Promise<any[]> {+ return page.evaluate(() => (window as any).annotationLists.at(-1) ?? []);+}++async function enterHighlightMode(viewer: FrameLocator) {+ await viewer.locator("#editorHighlightButton").click();+ await viewer.locator(".annotationEditorLayer").first().waitFor({ state: "attached" });+}++/** Drags across the page's only line of text, which pdf.js turns into a highlight. */+async function highlightFirstWords(page: Page, viewer: FrameLocator) {+ const span = viewer.locator(".textLayer span").first();+ const box = await span.boundingBox();+ if (!box) throw new Error("Text layer not rendered");++ await page.mouse.move(box.x + 2, box.y + box.height / 2);+ await page.mouse.down();+ await page.mouse.move(box.x + box.width - 2, box.y + box.height / 2, { steps: 12 });+ await page.mouse.up();+}++/** A one-page PDF with selectable text, so a highlight can be made over it. */+function textPdf(): Buffer {+ const stream = "BT /F1 24 Tf 72 700 Td (Hello highlight world) Tj ET\n";+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "+ + "/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",+ `<< /Length ${stream.length} >>\nstream\n${stream}endstream`,+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"+ ];++ let out = "%PDF-1.7\n";+ const offsets: number[] = [];+ objects.forEach((body, index) => {+ offsets.push(out.length);+ out += `${index + 1} 0 obj\n${body}\nendobj\n`;+ });+ const xrefOffset = out.length;+ out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ for (const offset of offsets) {+ out += `${String(offset).padStart(10, "0")} 00000 n \n`;+ }+ out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;+ return Buffer.from(out, "latin1");+}++async function openHarness(page: Page): Promise<FrameLocator> {+ await page.goto("/parent.html");+ const viewer = page.frameLocator("#viewer");+ await viewer.locator(".page canvas").first().waitFor({ state: "visible" });+ await page.waitForTimeout(1000);+ return viewer;+}diff --git a/packages/pdfjs-viewer/src/annotations.spec.ts b/packages/pdfjs-viewer/src/annotations.spec.tsindex de4bbce413..1813dfff34 100644--- a/packages/pdfjs-viewer/src/annotations.spec.ts+++ b/packages/pdfjs-viewer/src/annotations.spec.ts@@ -3,7 +3,6 @@ import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";import { afterEach, describe, expect, it, vi } from "vitest";import {AnnotationType,- extractFromSavedData,processAnnotation,rgbToHex,setupAnnotationLiveUpdates,@@ -233,6 +232,34 @@ describe("extraction from a real document", () => {expect(annotations.find((annotation: any) => annotation.id === "19R").color).toBeNull();});+ it("lists annotations that so far exist only in the editor", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ // What pdf.js holds for annotations drawn in this session: keyed by the editor's own id,+ // with `id` naming the document annotation it came from — null for one that is new.+ // Until the file is written back these are the only record of them, so a sidebar built+ // from the document alone stays empty however much the reader annotates (#11059).+ vi.spyOn(viewer.pdfDocument.annotationStorage, "serializable", "get").mockReturnValue({+ map: new Map<string, any>([+ [ "pdfjs_internal_editor_0", { annotationType: 9, id: null, pageIndex: 2, color: [ 255, 255, 152 ] } ],+ [ "pdfjs_internal_editor_1", { annotationType: 3, id: null, pageIndex: 0, color: [ 0, 0, 0 ], value: "typed words" } ],+ // An existing annotation being edited: already listed from the document.+ [ "pdfjs_internal_editor_2", { annotationType: 9, id: "5R", pageIndex: 0, color: [ 0, 255, 0 ] } ]+ ]),+ hash: "x",+ transfer: []+ } as any);++ await setupPdfAnnotations();++ const { annotations } = viewer.lastMessageOfType("pdfjs-viewer-annotations");+ expect(annotations.filter((annotation: any) => annotation.id.startsWith("pdfjs_internal_editor"))).toEqual([+ expect.objectContaining({ id: "pdfjs_internal_editor_0", type: "highlight", pageNumber: 3, color: "#ffff98" }),+ expect.objectContaining({ id: "pdfjs_internal_editor_1", type: "freetext", contents: "typed words", pageNumber: 1 })+ ]);+ // The document's own annotations are still there, and the edited one is not duplicated.+ expect(annotations.filter((annotation: any) => annotation.id === "5R")).toHaveLength(1);+ });+it("removes deleted annotations even when they are adjacent", async () => {viewer = await installViewerApp(allFeaturesPdf());vi.spyOn(viewer.pdfDocument.annotationStorage, "getEditor").mockReturnValue({ deleted: true });@@ -271,63 +298,6 @@ describe("extraction from a real document", () => {});});-describe("re-extraction from saved bytes", () => {- let viewer: InstalledViewer;-- afterEach(() => {- delete (globalThis as any).pdfjsLib;- uninstallViewerApp();- });-- it("reopens freshly saved bytes and tears the temporary document down", async () => {- viewer = await installViewerApp(allFeaturesPdf());- const saved = await viewer.pdfDocument.saveDocument();-- // The viewer exposes pdf.js on the global; hand it the real module so the temporary- // document is opened by the same code path that runs in the browser.- const destroy = vi.fn();- (globalThis as any).pdfjsLib = {- getDocument: (...args: any[]) => {- const task = (getDocument as any)(...args);- const teardown = task.destroy.bind(task);- task.destroy = () => {- destroy();- return teardown();- };- return task;- }- };-- await extractFromSavedData(saved);-- // Saving and reopening must not lose the annotations the sidebar is showing.- expect(viewer.lastMessageOfType("pdfjs-viewer-annotations").annotations)- .toEqual([- expect.objectContaining({ contents: "A remark" }),- expect.objectContaining({ contents: "A sticky note" }),- expect.objectContaining({ id: "17R", type: "highlight" }),- expect.objectContaining({ id: "18R", type: "ink" }),- expect.objectContaining({ id: "19R", type: "freetext", contents: "Typed in the box" }),- expect.objectContaining({ id: "20R", type: "highlight" })- ]);- // The temporary document owns a worker, so failing to destroy it leaks one per save.- expect(destroy).toHaveBeenCalledTimes(1);- });-- it("logs and gives up when the saved bytes cannot be reopened", async () => {- viewer = await installViewerApp(allFeaturesPdf());- const error = vi.spyOn(console, "error").mockImplementation(() => {});- (globalThis as any).pdfjsLib = { getDocument };-- // Real pdf.js rejecting real garbage, rather than a stand-in that throws on cue —- // which also keeps the loading task real, so the `finally` teardown is exercised.- await extractFromSavedData(new Uint8Array([ 1, 2, 3 ]));-- expect(error).toHaveBeenCalled();- expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(0);- });-});-describe("live updates", () => {let viewer: InstalledViewer;@@ -396,6 +366,22 @@ describe("scrolling to an annotation", () => {expect(viewer.scrollRequests).toHaveBeenCalledWith(expect.objectContaining({ behavior: "smooth" }));});+ it("scrolls to an annotation that only exists in the editor", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfAnnotations();+ // pdf.js gives an editor no data-annotation-id — it is not in the document yet — so the+ // element carries the editor's own id and that is what the sidebar entry holds.+ const editorEl = document.createElement("div");+ editorEl.id = "pdfjs_internal_editor_0";+ viewer.viewerEl.append(editorEl);++ viewer.sendFromParent({+ type: "trilium-scroll-to-annotation", annotationId: "pdfjs_internal_editor_0", pageNumber: 1+ });++ await vi.waitFor(() => expect(viewer.scrollRequests).toHaveBeenCalled());+ });+it("jumps to the page and waits for an annotation that has not rendered yet", async () => {viewer = await installViewerApp(allFeaturesPdf());await setupPdfAnnotations();diff --git a/packages/pdfjs-viewer/src/annotations.ts b/packages/pdfjs-viewer/src/annotations.tsindex c39bc8c6b1..6f157a175b 100644--- a/packages/pdfjs-viewer/src/annotations.ts+++ b/packages/pdfjs-viewer/src/annotations.ts@@ -112,35 +112,15 @@ export function setupAnnotationLiveUpdates() {async function extractAndSendAnnotations() {const app = window.PDFViewerApplication;try {+ const storage = app.pdfDocument.annotationStorage;const annotations = await extractFromDocument(app.pdfDocument);- sendAnnotations(applyEditorOverrides(annotations, app.pdfDocument.annotationStorage));+ sendAnnotations([ ...applyEditorOverrides(annotations, storage), ...unsavedAnnotations(storage) ]);} catch (error) {console.error("Error extracting annotations:", error);sendAnnotations([]);}}-/**- * Re-extract annotations from freshly saved PDF bytes.- * Opens a temporary document to read the latest data (including- * newly created highlights with their overlaidText), then closes it.- */-export async function extractFromSavedData(data: ArrayBuffer | Uint8Array) {- let loadingTask: any;- try {- loadingTask = (globalThis as any).pdfjsLib.getDocument({ data });- const tempDoc = await loadingTask.promise;- const annotations = await extractFromDocument(tempDoc);- sendAnnotations(annotations);- } catch (error) {- console.error("Error extracting annotations from saved data:", error);- } finally {- // PDFDocumentProxy.destroy() was removed in pdf.js v6; tear the temporary- // document (and its worker) down via the loading task instead.- await loadingTask?.destroy();- }-}-async function extractFromDocument(pdfDocument: any): Promise<PdfAnnotationInfo[]> {const numPages = pdfDocument.numPages;const annotations: PdfAnnotationInfo[] = [];@@ -188,6 +168,49 @@ function applyEditorOverrides(annotations: PdfAnnotationInfo[], storage: any): Preturn remaining;}+/**+ * Sidebar entries for annotations that exist only in the editor so far.+ *+ * pdf.js keeps what the reader draws out of the loaded document until the file is written back,+ * and {@link applyEditorOverrides} can only amend what the document already holds — so a sidebar+ * built from the document alone stays empty however much is annotated, until the note is reopened+ * (#11059). `annotationStorage.serializable` is the same view `saveDocument()` writes from: keyed+ * by the editor's own id, which is also the id of the element it renders, so an entry built here+ * is one {@link scrollToAnnotation} can navigate to.+ */+function unsavedAnnotations(storage: any): PdfAnnotationInfo[] {+ const unsaved: PdfAnnotationInfo[] = [];++ for (const [ id, serialized ] of storage?.serializable?.map ?? []) {+ // `id` names the document annotation an editor was built from; the entry for one of those+ // is already in the list, carrying the text and author only the document knows.+ if (serialized.id || serialized.deleted) {+ continue;+ }+ const type = TYPE_NAMES[serialized.annotationType];+ if (!type) {+ continue;+ }++ unsaved.push({+ id,+ type,+ // A free-text box serializes the words it was given; nothing else carries text. A+ // highlight's overlaidText is derived from the file's glyphs, so it only appears once+ // the document has been written back.+ contents: typeof serialized.value === "string" ? serialized.value : "",+ highlightedText: "",+ author: "",+ pageNumber: (serialized.pageIndex ?? 0) + 1,+ color: serialized.color ? rgbToHex(serialized.color) : null,+ creationDate: null,+ modificationDate: null+ });+ }++ return unsaved;+}+function sendAnnotations(annotations: PdfAnnotationInfo[]) {window.parent.postMessage({type: "pdfjs-viewer-annotations",@@ -211,8 +234,15 @@ function scrollToAnnotation(annotationId: string, pageNumber: number) {});}+ // An annotation the document holds renders with its id in an attribute; one that so far+ // exists only in the editor renders as an element carrying the editor id directly.+ function findRendered() {+ return document.querySelector(`[data-annotation-id="${CSS.escape(annotationId)}"]`)+ ?? document.getElementById(annotationId);+ }+// Try to find the element directly (nearby pages are pre-rendered)- const el = document.querySelector(`[data-annotation-id="${CSS.escape(annotationId)}"]`);+ const el = findRendered();if (el) {scrollToEl(el);return;@@ -221,7 +251,7 @@ function scrollToAnnotation(annotationId: string, pageNumber: number) {// Element not in DOM yet — jump to the page and wait for it to renderapp.pdfViewer.currentPageNumber = pageNumber;const observer = new MutationObserver(() => {- const el = document.querySelector(`[data-annotation-id="${CSS.escape(annotationId)}"]`);+ const el = findRendered();if (el) {observer.disconnect();scrollToEl(el);diff --git a/packages/pdfjs-viewer/src/bootstrap.spec.ts b/packages/pdfjs-viewer/src/bootstrap.spec.tsindex 0a825bd89b..7b6fb4215b 100644--- a/packages/pdfjs-viewer/src/bootstrap.spec.ts+++ b/packages/pdfjs-viewer/src/bootstrap.spec.ts@@ -366,10 +366,6 @@ describe("producing the saved document", () => {expect(blob.data.length).toBeGreaterThan(0);// The bytes must be a real PDF the viewer can reopen, not a partial write.await expect(getDocument({ data: blob.data }).promise).resolves.toBeTruthy();-- // Newly created highlights only get their overlaidText once written out, so the- // sidebar is refreshed from the saved bytes.- await vi.waitFor(() => expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(1));});it("does not save on a request from another origin", async () => {diff --git a/packages/pdfjs-viewer/src/bootstrap.ts b/packages/pdfjs-viewer/src/bootstrap.tsindex ae57d90996..8ded75234d 100644--- a/packages/pdfjs-viewer/src/bootstrap.ts+++ b/packages/pdfjs-viewer/src/bootstrap.ts@@ -3,7 +3,7 @@ import { extractAndSendToc, setupScrollToHeading, setupActiveHeadingTracking } fimport { setupPdfPages } from "./pages";import { setupPdfAttachments } from "./attachments";import { setupPdfLayers } from "./layers";-import { setupPdfAnnotations, setupAnnotationLiveUpdates, extractFromSavedData } from "./annotations";+import { setupPdfAnnotations, setupAnnotationLiveUpdates } from "./annotations";import { commitPendingAnnotationEdits, isAnnotationEditingActive, setAnnotationEditorUIManager, suppressViewerUnloadPrompt } from "./editing";export async function main() {@@ -210,9 +210,6 @@ export function manageSave() {ntxId: window.TRILIUM_NTX_ID,noteId: window.TRILIUM_NOTE_ID} satisfies PdfDocumentBlobResultMessage, window.location.origin);- // Re-extract annotations from the saved data so new- // highlights get their overlaidText populated.- extractFromSavedData(data);}});