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
test(pdf): cover the remaining viewer modules against real pdf.js
Elian Doran1b73a9cd2314
diff --git a/packages/pdfjs-viewer/src/annotations.spec.ts b/packages/pdfjs-viewer/src/annotations.spec.tsindex 23cb7866db..955ad3880b 100644--- a/packages/pdfjs-viewer/src/annotations.spec.ts+++ b/packages/pdfjs-viewer/src/annotations.spec.ts@@ -1,5 +1,16 @@-import { describe, expect, it } from "vitest";-import { processAnnotation, AnnotationType, rgbToHex } from "./annotations";+// @vitest-environment happy-dom+import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ AnnotationType,+ extractFromSavedData,+ processAnnotation,+ rgbToHex,+ setupAnnotationLiveUpdates,+ setupPdfAnnotations+} from "./annotations";+import { allFeaturesPdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";const SAMPLE_HIGHLIGHT = {annotationType: 9,@@ -79,3 +90,220 @@ describe("rgbToHex", () => {expect(rgbToHex([255, 255, 255])).toBe("#ffffff");});});++/**+ * The rest of the file drives the extraction against a real `PDFDocumentProxy`, so the+ * annotation objects, the page loop and the save round-trip are pdf.js' own rather than+ * hand-built stand-ins. See {@link ./test/fixture_pdf}.+ */+describe("extraction from a real document", () => {+ let viewer: InstalledViewer;++ afterEach(() => uninstallViewerApp());++ /** The two annotations the fixture expects to surface, in page order. */+ const EXPECTED = [+ expect.objectContaining({+ id: "5R",+ type: "highlight",+ contents: "A remark",+ author: "Alice",+ pageNumber: 1,+ color: "#ff0000"+ }),+ expect.objectContaining({+ id: "14R",+ type: "text",+ contents: "A sticky note",+ author: "Bob",+ pageNumber: 1,+ color: "#0000ff"+ })+ ];++ it("walks every page and keeps only the annotations worth showing", async () => {+ viewer = await installViewerApp(allFeaturesPdf());++ await setupPdfAnnotations();++ // Page 2 holds a link (wrong type) and a highlight with no comment or highlighted+ // text; neither should reach the sidebar, and the page loop still has to visit it.+ expect(viewer.lastMessageOfType("pdfjs-viewer-annotations").annotations).toEqual(EXPECTED);+ });++ it("lets editor state override the colour and comment of a stored annotation", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ // getEditor() is pinned as existing by the contract spec; its return is stubbed here+ // because populating a real editor needs the annotation-editing UI layer.+ vi.spyOn(viewer.pdfDocument.annotationStorage, "getEditor").mockImplementation((id: string) =>+ id === "5R" ? { color: "#00ff00", comment: { text: "Edited in the viewer" } } : null);++ await setupPdfAnnotations();++ const [ highlight ] = viewer.lastMessageOfType("pdfjs-viewer-annotations").annotations;+ expect(highlight).toMatchObject({ id: "5R", color: "#00ff00", contents: "Edited in the viewer" });+ });++ it("DEFECT: keeps the second of two consecutively deleted annotations", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.spyOn(viewer.pdfDocument.annotationStorage, "getEditor").mockReturnValue({ deleted: true });++ await setupPdfAnnotations();++ // `applyEditorOverrides` splices from the array it is iterating with `for...of`, so+ // removing an element shifts the next one into the consumed index and skips it. Both+ // fixture annotations are marked deleted, so the sidebar should end up empty — instead+ // the second survives and shows an annotation the user already removed. Pinned rather+ // than silently accepted; the fix is to build a filtered array instead of splicing.+ const { annotations } = viewer.lastMessageOfType("pdfjs-viewer-annotations");+ expect(annotations).toHaveLength(1);+ expect(annotations[0].id).toBe("14R");+ });++ it("reports an empty list when extraction fails", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.spyOn(console, "error").mockImplementation(() => {});+ vi.spyOn(viewer.pdfDocument, "getPage").mockRejectedValue(new Error("boom"));++ await setupPdfAnnotations();++ expect(viewer.lastMessageOfType("pdfjs-viewer-annotations")).toEqual({+ type: "pdfjs-viewer-annotations",+ annotations: []+ });+ });+});++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" }) ]);+ // 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;++ afterEach(() => {+ vi.useRealTimers();+ uninstallViewerApp();+ });++ it("chains onto an existing onSetModified and debounces the refresh", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ const storage = viewer.pdfDocument.annotationStorage as any;+ const previous = vi.fn();+ storage.onSetModified = previous;+ vi.useFakeTimers();++ setupAnnotationLiveUpdates();+ storage.onSetModified();+ storage.onSetModified();++ // The save flow installs its own onSetModified first; dropping it would stop the+ // parent being told the document is dirty.+ expect(previous).toHaveBeenCalledTimes(2);+ expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(0);++ await vi.advanceTimersByTimeAsync(500);+ expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(1);+ });++ it("also refreshes on editor parameter and editing state changes", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.useFakeTimers();+ setupAnnotationLiveUpdates();++ // Deletions and undo/redo surface only through these two events.+ viewer.eventBus.dispatch("annotationeditorparamschanged", { source: null });+ await vi.advanceTimersByTimeAsync(500);+ expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(1);++ viewer.eventBus.dispatch("editingstateschanged", { source: null, details: {} });+ await vi.advanceTimersByTimeAsync(500);+ expect(viewer.messagesOfType("pdfjs-viewer-annotations")).toHaveLength(2);+ });+});++describe("scrolling to an annotation", () => {+ let viewer: InstalledViewer;++ afterEach(() => uninstallViewerApp());++ /** Appends the element pdf.js would render for an annotation. */+ function renderAnnotation(id: string) {+ const el = document.createElement("div");+ el.setAttribute("data-annotation-id", id);+ viewer.viewerEl.append(el);+ return el;+ }++ it("scrolls straight to an annotation that is already rendered", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfAnnotations();+ renderAnnotation("5R");++ viewer.sendFromParent({ type: "trilium-scroll-to-annotation", annotationId: "5R", pageNumber: 1 });++ await vi.waitFor(() => expect(viewer.scrollRequests).toHaveBeenCalled());+ expect(viewer.scrollRequests).toHaveBeenCalledWith(expect.objectContaining({ behavior: "smooth" }));+ });++ it("jumps to the page and waits for an annotation that has not rendered yet", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfAnnotations();++ viewer.sendFromParent({ type: "trilium-scroll-to-annotation", annotationId: "14R", pageNumber: 2 });++ // Nothing to scroll to yet, so the viewer is asked to page there first.+ await vi.waitFor(() => expect(window.PDFViewerApplication?.pdfViewer.currentPageNumber).toBe(2));+ expect(viewer.scrollRequests).not.toHaveBeenCalled();++ // Once pdf.js renders the annotation, the observer picks it up.+ renderAnnotation("14R");+ await vi.waitFor(() => expect(viewer.scrollRequests).toHaveBeenCalled());+ });+});diff --git a/packages/pdfjs-viewer/src/attachments.spec.ts b/packages/pdfjs-viewer/src/attachments.spec.tsindex ada0cdf808..56d6f47b20 100644--- a/packages/pdfjs-viewer/src/attachments.spec.ts+++ b/packages/pdfjs-viewer/src/attachments.spec.ts@@ -1,6 +1,9 @@-import { describe, expect, it, vi } from "vitest";+// @vitest-environment happy-dom+import { afterEach, describe, expect, it, vi } from "vitest";-import { collectAttachments } from "./attachments";+import { collectAttachments, setupPdfAttachments } from "./attachments";+import { allFeaturesPdf, ATTACHMENT_TEXT, barePdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";/** Mirrors what pdf.js hands back since 6.1: a `Map`, with the content stripped from the entries. */function attachmentMap(...entries: [string, { filename?: string }][]) {@@ -46,3 +49,106 @@ describe("collectAttachments", () => {expect(getContent).not.toHaveBeenCalled();});});++/**+ * The `attachmentMap()` helper above encodes our belief about what pdf.js returns; these tests+ * check that belief against the real thing, which is where the 6.1 change to a `Map` slipped+ * through. See {@link ./test/fixture_pdf}.+ */+describe("against a real document", () => {+ let viewer: InstalledViewer;++ afterEach(() => uninstallViewerApp());++ it("reports the embedded file with the size pdf.js resolves for it", async () => {+ viewer = await installViewerApp(allFeaturesPdf());++ await setupPdfAttachments();++ expect(viewer.lastMessageOfType("pdfjs-viewer-attachments")).toEqual({+ type: "pdfjs-viewer-attachments",+ attachments: [ { id: "notes.txt", filename: "notes.txt", size: ATTACHMENT_TEXT.length } ]+ });+ });++ it("reports an empty list for a document with no attachments", async () => {+ viewer = await installViewerApp(barePdf());++ await setupPdfAttachments();++ expect(viewer.lastMessageOfType("pdfjs-viewer-attachments").attachments).toEqual([]);+ });++ it("still reports, with an empty list, when extraction throws", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.spyOn(console, "error").mockImplementation(() => {});+ vi.spyOn(viewer.pdfDocument, "getAttachments").mockRejectedValue(new Error("boom"));++ await setupPdfAttachments();++ // The sidebar waits for this message, so swallowing it would leave a spinner up.+ expect(viewer.lastMessageOfType("pdfjs-viewer-attachments").attachments).toEqual([]);+ });+});++describe("downloading an attachment", () => {+ let viewer: InstalledViewer;+ let click: ReturnType<typeof vi.spyOn>;++ afterEach(() => uninstallViewerApp());++ /** Captures the anchor the download path builds and clicks. */+ function captureDownload() {+ const anchors: HTMLAnchorElement[] = [];+ click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {+ anchors.push(this);+ });+ return anchors;+ }++ it("hands the real attachment bytes to the browser under its filename", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ const anchors = captureDownload();+ const createObjectURL = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:fixture");+ const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});+ await setupPdfAttachments();++ viewer.sendFromParent({ type: "trilium-download-attachment", id: "notes.txt" });+ await vi.waitFor(() => expect(click).toHaveBeenCalled());++ expect(anchors[0].download).toBe("notes.txt");+ expect(anchors[0].href).toContain("blob:fixture");++ // The blob must carry the bytes pdf.js actually stored, not a placeholder.+ const [ blob ] = createObjectURL.mock.calls[0];+ expect(await (blob as Blob).text()).toBe(ATTACHMENT_TEXT);+ // The URL is one-shot; leaving it alive pins the blob in memory for the session.+ expect(revokeObjectURL).toHaveBeenCalledWith("blob:fixture");+ });++ it("does nothing for an unknown attachment id", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ captureDownload();+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ await setupPdfAttachments();++ viewer.sendFromParent({ type: "trilium-download-attachment", id: "nope.txt" });+ await vi.waitFor(() => expect(error).toHaveBeenCalled());++ expect(click).not.toHaveBeenCalled();+ });++ it("ignores download requests from another origin", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ captureDownload();+ await setupPdfAttachments();++ window.dispatchEvent(new MessageEvent("message", {+ data: { type: "trilium-download-attachment", id: "notes.txt" },+ origin: "https://evil.example"+ }));+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(click).not.toHaveBeenCalled();+ });+});diff --git a/packages/pdfjs-viewer/src/pages.spec.ts b/packages/pdfjs-viewer/src/pages.spec.tsnew file mode 100644index 0000000000..c975b990a9--- /dev/null+++ b/packages/pdfjs-viewer/src/pages.spec.ts@@ -0,0 +1,143 @@+// @vitest-environment happy-dom+/**+ * Page reporting and thumbnail generation, driven against a real `PDFDocumentProxy` so the+ * page count and viewport geometry come from pdf.js. See {@link ./test/fixture_pdf}.+ *+ * Rasterisation itself is the one thing not exercised here: happy-dom has no 2D canvas+ * context, and pdf.js cannot render into `@napi-rs/canvas` (its `clip()` rejects the arguments+ * pdf.js passes). The tests below therefore cover the geometry and the render *call*, and+ * leave the pixels to the Playwright suite in `e2e/`.+ */+import { afterEach, describe, expect, it, vi } from "vitest";++import { setupPdfPages } from "./pages";+import { allFeaturesPdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";++let viewer: InstalledViewer;++afterEach(() => uninstallViewerApp());++describe("page reporting", () => {+ it("reports the page count as soon as a document is present", async () => {+ viewer = await installViewerApp(allFeaturesPdf());++ setupPdfPages();++ // The fixture has two pages, and the viewer starts on the first.+ expect(viewer.lastMessageOfType("pdfjs-viewer-page-info")).toEqual({+ type: "pdfjs-viewer-page-info",+ totalPages: 2,+ currentPage: 1+ });+ });++ it("re-reports once pdf.js has initialised the pages", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ setupPdfPages();++ viewer.eventBus.dispatch("pagesinit", { source: null });++ // `pagesinit` arrives after the viewer has laid the pages out, which is when the+ // current page number becomes meaningful.+ expect(viewer.messagesOfType("pdfjs-viewer-page-info")).toHaveLength(2);+ });++ it("forwards page changes as the user moves through the document", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ setupPdfPages();++ viewer.eventBus.dispatch("pagechanging", { source: null, pageNumber: 2 });++ expect(viewer.lastMessageOfType("pdfjs-viewer-current-page")).toEqual({+ type: "pdfjs-viewer-current-page",+ currentPage: 2+ });+ });++ it("pages the viewer when the parent asks to scroll", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ setupPdfPages();++ viewer.sendFromParent({ type: "trilium-scroll-to-page", pageNumber: 2 });++ await vi.waitFor(() => expect(window.PDFViewerApplication?.pdfViewer.currentPageNumber).toBe(2));+ });++ it("ignores commands from another origin", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ setupPdfPages();++ window.dispatchEvent(new MessageEvent("message", {+ data: { type: "trilium-scroll-to-page", pageNumber: 2 },+ origin: "https://evil.example"+ }));+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(window.PDFViewerApplication?.pdfViewer.currentPageNumber).toBe(1);+ });+});++describe("thumbnail generation", () => {+ /**+ * Stands in for the 2D canvas happy-dom does not provide. Only the DOM side is faked —+ * the page, its viewport and the `render()` call all remain pdf.js'.+ */+ function stubCanvas(dataUrl = "data:image/jpeg;base64,fixture") {+ const context = {};+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(context as never);+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(dataUrl);+ return context;+ }++ it("renders the page at thumbnail scale and returns it as a data URL", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ stubCanvas();+ const page = await viewer.pdfDocument.getPage(1);+ const render = vi.spyOn(page, "render").mockReturnValue({ promise: Promise.resolve() } as never);+ vi.spyOn(viewer.pdfDocument, "getPage").mockResolvedValue(page);+ setupPdfPages();++ viewer.sendFromParent({ type: "trilium-request-thumbnail", pageNumber: 1 });+ await vi.waitFor(() => expect(viewer.messagesOfType("pdfjs-viewer-thumbnail")).toHaveLength(1));++ // The canvas is sized from pdf.js' own viewport for the scale, so a change in how+ // getViewport() computes dimensions shows up here. The fixture page is 612x792, so+ // scale 0.2 gives 122.4x158.4 — which the canvas attributes truncate to whole pixels,+ // costing a sub-pixel sliver off the right and bottom edges of every thumbnail.+ const [ { canvas, viewport } ] = render.mock.calls[0];+ expect([ viewport.width, viewport.height ]).toEqual([ 122.4, 158.4 ]);+ expect([ canvas.width, canvas.height ]).toEqual([ 122, 158 ]);++ expect(viewer.lastMessageOfType("pdfjs-viewer-thumbnail")).toEqual({+ type: "pdfjs-viewer-thumbnail",+ pageNumber: 1,+ dataUrl: "data:image/jpeg;base64,fixture"+ });+ });++ it("gives up quietly when no 2D context is available", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ // happy-dom's own behaviour, and the same as a browser that has exhausted its canvas+ // budget: getContext() returns null and there is nothing to draw into.+ setupPdfPages();++ viewer.sendFromParent({ type: "trilium-request-thumbnail", pageNumber: 1 });+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(viewer.messagesOfType("pdfjs-viewer-thumbnail")).toHaveLength(0);+ });++ it("logs and sends nothing when the page cannot be loaded", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ stubCanvas();+ const error = vi.spyOn(console, "error").mockImplementation(() => {});+ vi.spyOn(viewer.pdfDocument, "getPage").mockRejectedValue(new Error("boom"));+ setupPdfPages();++ viewer.sendFromParent({ type: "trilium-request-thumbnail", pageNumber: 99 });+ await vi.waitFor(() => expect(error).toHaveBeenCalled());++ expect(viewer.messagesOfType("pdfjs-viewer-thumbnail")).toHaveLength(0);+ });+});diff --git a/packages/pdfjs-viewer/src/persistence.spec.ts b/packages/pdfjs-viewer/src/persistence.spec.tsindex 8dcdf95366..aa0b0403a3 100644--- a/packages/pdfjs-viewer/src/persistence.spec.ts+++ b/packages/pdfjs-viewer/src/persistence.spec.ts@@ -5,6 +5,8 @@ import { dirname, join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import interceptPersistence from "./persistence";+import { allFeaturesPdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";const SIGNATURE_KEY = "pdfjs.signature";const ENTRY = { description: "Mine", signatureData: "data-1" };@@ -45,6 +47,20 @@ function readRealStore(key: string) {return realGetItem.call(localStorage, key);}+/**+ * Reads through the currently installed interception, as pdf.js does.+ *+ * happy-dom's `localStorage` is a proxy that resolves `getItem` once and then caches it, so+ * after the first test in this file touches it, `localStorage.getItem` stays pinned to+ * whichever patch was installed at that moment and never sees a later one. In a real browser+ * there is no proxy and `localStorage.getItem` *is* `Storage.prototype.getItem`, so going+ * through the prototype here is equivalent to what the viewer actually does — and, unlike the+ * bare instance call, it reads the patch the test under way installed.+ */+function readThroughPatch(key: string) {+ return Storage.prototype.getItem.call(localStorage, key);+}+describe("signature-library interception", () => {it("serves the injected library and never touches real localStorage on read", () => {interceptPersistence();@@ -156,6 +172,71 @@ describe("real pdf.js SignatureStorage against the interception", () => {});});+describe("preferences and pass-through reads", () => {+ it("serves the injected viewer options and leaves other keys to the real store", () => {+ interceptPersistence({ disablePreferences: true, sidebarViewOnLoad: 0 });++ // pdf.js reads its preferences out of localStorage on boot; this is how the options+ // Trilium passes through the iframe URL reach it.+ expect(JSON.parse(readThroughPatch("pdfjs.preferences") ?? "null"))+ .toEqual({ disablePreferences: true, sidebarViewOnLoad: 0 });++ realSetItem.call(localStorage, "unrelated", "kept");+ expect(readThroughPatch("unrelated")).toBe("kept");+ expect(readThroughPatch("never-written")).toBeNull();+ });+});++describe("view-history persistence", () => {+ let viewer: InstalledViewer;++ afterEach(() => {+ vi.useRealTimers();+ uninstallViewerApp();+ });++ it("debounces bursts of writes and keeps only the current document's entry", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ // A real fingerprint from the real document — pdf.js derives it from the file's+ // contents, so hard-coding one here would drift the moment the fixture changed.+ const fingerprint = viewer.pdfDocument.fingerprints?.[0];+ expect(fingerprint).toBeTruthy();+ vi.useFakeTimers();+ interceptPersistence();++ const history = { files: [ { fingerprint, page: 3 }, { fingerprint: "some-other-document" } ] };+ localStorage.setItem("pdfjs.history", JSON.stringify({ files: [] }));+ localStorage.setItem("pdfjs.history", JSON.stringify(history));++ // pdf.js writes on every scroll, so nothing may be sent until the burst settles.+ expect(viewer.messagesOfType("pdfjs-viewer-save-view-history")).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(2_000);++ const sent = viewer.messagesOfType("pdfjs-viewer-save-view-history");+ expect(sent).toHaveLength(1);+ expect(sent[0]).toMatchObject({ noteId: "note-1", ntxId: "ntx-1" });+ // Entries for other documents would otherwise accumulate in this note's option+ // forever, since each note stores the whole history blob.+ expect(JSON.parse(sent[0].data).files).toEqual([ { fingerprint, page: 3 } ]);++ // And the real store never sees the key.+ expect(readRealStore("pdfjs.history")).toBeNull();+ });++ it("keeps every entry when no document is loaded to filter against", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ delete window.PDFViewerApplication;+ vi.useFakeTimers();+ interceptPersistence();++ localStorage.setItem("pdfjs.history", JSON.stringify({ files: [ { fingerprint: "a" } ] }));+ await vi.advanceTimersByTimeAsync(2_000);++ const [ sent ] = viewer.messagesOfType("pdfjs-viewer-save-view-history");+ expect(JSON.parse(sent.data).files).toEqual([ { fingerprint: "a" } ]);+ });+});+/*** Extracts the real `SignatureStorage` class from the vendored pdf.js viewer bundle and evaluates* it with its two module-private dependencies injected. pdf.js does not export this class (it livesdiff --git a/packages/pdfjs-viewer/src/test/fixture_pdf.ts b/packages/pdfjs-viewer/src/test/fixture_pdf.tsindex 1bbba2d806..7b15d7c716 100644--- a/packages/pdfjs-viewer/src/test/fixture_pdf.ts+++ b/packages/pdfjs-viewer/src/test/fixture_pdf.ts@@ -55,8 +55,9 @@ export function allFeaturesPdf(): Uint8Array {"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",// 3 — page 1, carrying both annotations."<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R 14 0 R] >>",- // 4 — page 2, target of the second outline entry.- "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",+ // 4 — page 2, target of the second outline entry, carrying the two annotations that+ // must be filtered out: a link (wrong type) and a highlight with nothing to show.+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [16 0 R 17 0 R] >>",// 5 — highlight annotation with a comment, author and colour."<< /Type /Annot /Subtype /Highlight /Rect [100 700 200 720] "+ "/Contents (A remark) /T (Alice) /C [1 0 0] "@@ -83,7 +84,12 @@ export function allFeaturesPdf(): Uint8Array {+ "/Contents (A sticky note) /T (Bob) /C [0 0 1] >>",// 15 — the attachment payload itself.`<< /Type /EmbeddedFile /Length ${ATTACHMENT_TEXT.length} >>\n`- + `stream\n${ATTACHMENT_TEXT}\nendstream`+ + `stream\n${ATTACHMENT_TEXT}\nendstream`,+ // 16 — a link annotation: a type the sidebar does not display.+ "<< /Type /Annot /Subtype /Link /Rect [50 50 150 70] /A << /S /URI /URI (https://example.com) >> >>",+ // 17 — a highlight with neither a comment nor highlighted text, so nothing to show.+ "<< /Type /Annot /Subtype /Highlight /Rect [200 200 300 220] "+ + "/QuadPoints [200 220 300 220 200 200 300 200] >>"]);}diff --git a/packages/pdfjs-viewer/src/test/viewer_app.ts b/packages/pdfjs-viewer/src/test/viewer_app.tsindex a6978e7076..dc88382ac5 100644--- a/packages/pdfjs-viewer/src/test/viewer_app.ts+++ b/packages/pdfjs-viewer/src/test/viewer_app.ts@@ -46,6 +46,10 @@ export interface InstalledViewer {sendFromParent(data: unknown): void;/** Scrolls the fake container, as the active-heading tracker observes it. */scrollTo(scrollTop: number): void;+ /** The `#viewer` element pdf.js renders pages into. */+ viewerEl: HTMLElement;+ /** Records `container.scrollTo` calls, since happy-dom does not scroll. */+ scrollRequests: Mock;}/**@@ -64,9 +68,18 @@ export async function installViewerApp(data: Uint8Array, pageGeometry: Record<nuconst container = document.createElement("div");container.style.height = "800px";+ // `#viewer` is where pdf.js appends rendered pages; `scrollToAnnotation` observes it for+ // annotations that have not been rendered yet, and throws outright if it is missing.+ const viewerEl = document.createElement("div");+ viewerEl.id = "viewer";+ container.append(viewerEl);document.body.append(container);// happy-dom leaves layout at zero; the tracker only needs a readable clientHeight.Object.defineProperty(container, "clientHeight", { value: 800, configurable: true });+ // happy-dom performs no scrolling, so record the requests instead. Positions asserted+ // against this will be zero-based, since getBoundingClientRect() is also flat.+ const scrollRequests = vi.fn();+ container.scrollTo = scrollRequests;const pdfLinkService = { goToDestination: vi.fn() };const messages: any[] = [];@@ -118,7 +131,9 @@ export async function installViewerApp(data: Uint8Array, pageGeometry: Record<nu},scrollTo: (scrollTop) => {container.scrollTop = scrollTop;- }+ },+ viewerEl,+ scrollRequests};}