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 viewer message protocol and the sidebar panels
Elian Doran93fb4520efa0
diff --git a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsxindex 191d57bb28..11cab555e1 100644--- a/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx+++ b/apps/client/src/widgets/sidebar/pdf/PdfAnnotations.spec.tsx@@ -9,7 +9,7 @@ import PdfAnnotations, { isDark } from "./PdfAnnotations";// arrive through hooks that need the whole app context, so they are handed over directly here.const shown = vi.hoisted(() => ({note: null as FNote | null,- annotations: null as { annotations: PdfAnnotationInfo[]; scrollToAnnotation: () => void } | null+ annotations: null as { annotations: PdfAnnotationInfo[]; scrollToAnnotation: (id: string, page: number) => void } | null}));// i18next is not initialised for client specs, so t() would render every label as an empty// string. Echoing the key and its interpolations instead keeps the assertions about which@@ -45,14 +45,14 @@ function annotation(overrides: Partial<PdfAnnotationInfo>): PdfAnnotationInfo {};}-function renderPanel(annotations: PdfAnnotationInfo[]) {+function renderPanel(annotations: PdfAnnotationInfo[], scrollToAnnotation: (id: string, page: number) => void = () => {}) {// The surrounding RightPanelWidget reads which panels the user collapsed from the options.options.set("rightPaneCollapsedItems", JSON.stringify([]));const container = document.createElement("div");document.body.append(container);shown.note = pdfNote();- shown.annotations = { annotations, scrollToAnnotation: () => {} };+ shown.annotations = { annotations, scrollToAnnotation };render(<PdfAnnotations />, container);return container;}@@ -64,6 +64,44 @@ describe("PdfAnnotations", () => {shown.annotations = null;});+ it("renders nothing for a note that is not a PDF, or one with no annotations", () => {+ // The panel hides itself rather than showing an empty section: nothing to list means no+ // Annotations heading in the sidebar.+ const empty = renderPanel([]);+ expect(empty.querySelector("#pdf-annotations, .pdf-annotations-list")).toBeNull();++ options.set("rightPaneCollapsedItems", JSON.stringify([]));+ shown.note = { type: "text", mime: "text/html" } as unknown as FNote;+ shown.annotations = { annotations: [ annotation({}) ], scrollToAnnotation: () => {} };+ const notPdf = document.createElement("div");+ document.body.append(notPdf);+ render(<PdfAnnotations />, notPdf);+ expect(notPdf.querySelector(".pdf-annotations-list")).toBeNull();+ });++ it("navigates to an annotation when its row is clicked", () => {+ const scrollTo = vi.fn();+ const container = renderPanel([ annotation({ id: "5R", pageNumber: 3, contents: "A remark", author: "Alice" }) ], scrollTo);++ const row = container.querySelector(".pdf-annotation-item") as HTMLElement;+ expect(row.querySelector(".pdf-annotation-author")?.textContent).toBe("Alice");+ row.click();+ expect(scrollTo).toHaveBeenCalledWith("5R", 3);+ });++ it("falls back to a generic label and icon for a kind it has no specific ones for", () => {+ // A sticky note with no text is named a note; a kind the sidebar has no icon for gets the+ // generic comment icon rather than none.+ const container = renderPanel([+ annotation({ id: "14R", type: "text", pageNumber: 2 }),+ annotation({ id: "99R", type: "unknown", pageNumber: 5 })+ ]);++ const rows = [ ...container.querySelectorAll(".pdf-annotation-item") ];+ expect(rows[0].querySelector(".pdf-annotation-untitled")?.textContent).toBe(`pdf.annotation_note({"pageNumber":2})`);+ expect(rows[1].querySelector(".tn-icon")?.className).toContain("bx-comment");+ });+it("names annotations that carry no text of their own by kind and page", () => {// A free-hand highlight is stored as ink and never has text; before #11059 it was// dropped, taking the whole panel with it when nothing else was annotated.diff --git a/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx b/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsxnew file mode 100644index 0000000000..97aa9785e5--- /dev/null+++ b/apps/client/src/widgets/sidebar/pdf/PdfPages.spec.tsx@@ -0,0 +1,124 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type NoteContext from "../../../components/note_context";+import FNote from "../../../entities/fnote";+import options from "../../../services/options";+import PdfPages from "./PdfPages";++// The panel reads the note being displayed and the page data the viewer iframe published; both+// arrive through hooks that need the whole app context, so they are handed over directly here.+const shown = vi.hoisted(() => ({+ note: null as FNote | null,+ noteContext: null as NoteContext | null,+ pages: null as { totalPages: number; currentPage: number; scrollToPage: (page: number) => void; requestThumbnail: (page: number) => void } | null+}));+// react-window virtualises rows off the container's laid-out height, which happy-dom does not+// have; and under vitest it resolves a second copy of the hooks and cannot render at all. What the+// panel puts in a row is what matters here, so a stand-in list renders every row.+vi.mock("react-window", () => ({+ List: ({ rowComponent: Row, rowCount, rowProps }: { rowComponent: any; rowCount: number; rowProps: object }) => (+ <div>{Array.from({ length: rowCount }, (_, index) => <Row key={index} index={index} style={{}} {...rowProps} />)}</div>+ )+}));+vi.mock("../../../services/i18n", () => ({+ t: (key: string, options?: Record<string, unknown>) => `${key}(${JSON.stringify(options ?? {})})`+}));+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useActiveNoteContext: () => ({ note: shown.note, noteContext: shown.noteContext }),+ useNoteProperty: (_note: FNote, property: string) => (shown.note as any)?.[property],+ useGetContextData: () => shown.pages+}));++/** happy-dom lays nothing out, so the list gets its height from a stand-in observer. */+const LIST_HEIGHT = 400;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("ResizeObserver", class {+ constructor(private readonly callback: (entries: { contentRect: { height: number } }[]) => void) {}+ observe() {+ this.callback([ { contentRect: { height: LIST_HEIGHT } } ]);+ }+ disconnect() {}+ });+ // The surrounding RightPanelWidget reads which panels the user collapsed from the options.+ options.set("rightPaneCollapsedItems", JSON.stringify([]));++ shown.note = { noteId: "note-1", type: "file", mime: "application/pdf" } as unknown as FNote;+ shown.noteContext = { ntxId: "ntx-1" } as NoteContext;+ shown.pages = { totalPages: 3, currentPage: 2, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };++ container = document.createElement("div");+ document.body.append(container);+});++afterEach(() => {+ act(() => render(null, container));+ container.remove();+ vi.unstubAllGlobals();+ shown.note = null;+ shown.noteContext = null;+ shown.pages = null;+});++function renderPanel() {+ act(() => render(<PdfPages />, container));+}++/** Delivers a thumbnail the way Pdf.tsx relays one from the viewer iframe. */+function thumbnailArrives(detail: { ntxId: string; pageNumber: number; dataUrl: string }) {+ act(() => {+ window.dispatchEvent(new CustomEvent("pdf-thumbnail", { detail }));+ });+}++describe("PdfPages", () => {+ it("lists every page, marks the current one, and asks the viewer for each thumbnail", () => {+ renderPanel();++ const cells = [ ...container.querySelectorAll(".pdf-page-item") ];+ expect(cells.map((cell) => cell.querySelector(".pdf-page-number")?.textContent)).toEqual([ "1", "2", "3" ]);+ expect(cells.map((cell) => cell.classList.contains("active"))).toEqual([ false, true, false ]);+ // Nothing has arrived yet, so every cell is a placeholder and each page was requested once.+ expect(container.querySelectorAll(".pdf-page-loading")).toHaveLength(3);+ expect(shown.pages?.requestThumbnail).toHaveBeenCalledTimes(3);++ (cells[2] as HTMLElement).click();+ expect(shown.pages?.scrollToPage).toHaveBeenCalledWith(3);+ });++ it("shows a thumbnail rendered for its own context, and ignores another viewer's", () => {+ renderPanel();++ // A second open PDF relays its thumbnails onto the same window; painting one of those into+ // this document's page list would show a page from a different file.+ thumbnailArrives({ ntxId: "ntx-2", pageNumber: 1, dataUrl: "data:image/png;base64,OTHER" });+ expect(container.querySelector(".pdf-page-item img")).toBeNull();++ thumbnailArrives({ ntxId: "ntx-1", pageNumber: 1, dataUrl: "data:image/png;base64,MINE" });+ const images = [ ...container.querySelectorAll(".pdf-page-item img") ] as HTMLImageElement[];+ expect(images).toHaveLength(1);+ expect(images[0].getAttribute("src")).toBe("data:image/png;base64,MINE");+ expect(images[0].getAttribute("alt")).toBe(`pdf.pages_alt({"pageNumber":1})`);+ });++ it("renders nothing for a note that is not a PDF, or before the viewer has reported its pages", () => {+ shown.pages = null;+ renderPanel();+ expect(container.querySelector(".pdf-pages-list")).toBeNull();++ shown.pages = { totalPages: 3, currentPage: 1, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };+ shown.note = { noteId: "note-2", type: "text", mime: "text/html" } as unknown as FNote;+ renderPanel();+ expect(container.querySelector(".pdf-pages-list")).toBeNull();+ });++ it("says so when the document has no pages", () => {+ shown.pages = { totalPages: 0, currentPage: 0, scrollToPage: vi.fn(), requestThumbnail: vi.fn() };+ renderPanel();+ expect(container.querySelector(".no-pages")).not.toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsxnew file mode 100644index 0000000000..6906863dd9--- /dev/null+++ b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx@@ -0,0 +1,285 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type NoteContext from "../../../components/note_context";+import FNote from "../../../entities/fnote";+import options from "../../../services/options";++// The component's own job is the message protocol with the viewer iframe: what it publishes into+// the note context and what it relays. The hooks around it — the spaced-update save, the+// read-only decision, the view-mode config — need the whole app to construct, so they are stood+// in for here; the specs of those hooks cover them.+const spacedUpdate = vi.hoisted(() => ({ resetUpdateTimer: vi.fn(), scheduleUpdate: vi.fn(), updateNowIfNecessary: vi.fn() }));+const readOnly = vi.hoisted(() => ({ current: false }));+const historyStore = vi.hoisted(() => vi.fn());+/** What the component last handed the save hook: its data getter and content-change reaction. */+const saveOptions = vi.hoisted(() => ({ current: null as null | { getData(): unknown; onContentChange(blob: unknown): void } }));+/** The Trilium event handlers the component registered, by event name. */+const eventHandlers = vi.hoisted(() => new Map<string, (data: any) => unknown>());+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useBlobEditorSpacedUpdate: (options: any) => {+ saveOptions.current = options;+ return spacedUpdate;+ },+ useEffectiveReadOnly: () => readOnly.current,+ useTriliumEvent: (name: string, handler: (data: any) => unknown) => {+ eventHandlers.set(name, handler);+ }+}));+vi.mock("../../collections/NoteList", () => ({+ useViewModeConfig: () => ({ config: { files: [] }, storeFn: historyStore })+}));+// The viewer iframe itself is a separate component with its own spec; here it only has to hand+// back a frame the messages can be addressed to, and report it loaded.+vi.mock("./PdfViewer", () => ({+ default: ({ iframeRef, onLoad }: { iframeRef: { current: HTMLIFrameElement | null }; onLoad: () => void }) =>+ <iframe ref={iframeRef} class="pdf-preview" onLoad={onLoad} />,+ getPdfUrl: (path: string) => `/api/${path}`+}));+const activateNoteContext = vi.hoisted(() => vi.fn());+vi.mock("../../../components/app_context", () => ({+ default: { tabManager: { activateNoteContext } }+}));+const download = vi.hoisted(() => vi.fn());+vi.mock("../../../services/open", () => ({+ default: { download, getUrlForDownload: (path: string) => `/${path}` }+}));++const { default: PdfPreview } = await import("./Pdf");++const NOTE = { noteId: "note-1", mime: "application/pdf", type: "file", title: "doc.pdf" } as unknown as FNote;++let container: HTMLDivElement;+let noteContext: NoteContext;+let contextData: Record<string, unknown>;++beforeEach(() => {+ readOnly.current = false;+ contextData = {};+ noteContext = {+ ntxId: "ntx-1",+ setContextData: vi.fn((key: string, value: unknown) => { contextData[key] = value; }),+ getContextData: vi.fn((key: string) => contextData[key]),+ isActive: () => true+ } as unknown as NoteContext;++ container = document.createElement("div");+ document.body.append(container);+ // Effects, which install the message listener, only run once Preact flushes them.+ act(() => render(<PdfPreview note={NOTE} noteContext={noteContext} blob={null} componentId="cmp" />, container));+});++afterEach(() => {+ act(() => render(null, container));+ container.remove();+ vi.clearAllMocks();+});++/**+ * Records what the component posts into its iframe. Recorded rather than delivered: the blank+ * frame has no origin the real call would accept.+ */+function recordPostsToViewer() {+ const iframe = container.querySelector("iframe") as HTMLIFrameElement;+ return vi.spyOn(iframe.contentWindow as Window, "postMessage").mockImplementation(() => {});+}++/** Delivers a message the way the viewer iframe posts it to the parent window. */+function fromViewer(data: Record<string, unknown>) {+ window.dispatchEvent(new MessageEvent("message", { data }));+}++/** The same message, addressed to this viewer. */+function fromThisViewer(data: Record<string, unknown>) {+ fromViewer({ noteId: "note-1", ntxId: "ntx-1", ...data });+}++describe("PdfPreview", () => {+ it("acts only on messages addressed to its own viewer", () => {+ // Every open PDF posts to the same parent window; a message from another split or tab+ // must not write into this note context, or the sidebar shows one document's list while+ // navigating another.+ const annotations = [ { id: "5R", type: "highlight", pageNumber: 1 } ];+ fromViewer({ type: "pdfjs-viewer-annotations", annotations, noteId: "note-1", ntxId: "ntx-2" });+ fromViewer({ type: "pdfjs-viewer-annotations", annotations, noteId: "note-2", ntxId: "ntx-1" });+ fromViewer({ type: "pdfjs-viewer-annotations", annotations });+ expect(noteContext.setContextData).not.toHaveBeenCalled();++ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations });+ expect(noteContext.setContextData).toHaveBeenCalledWith("pdfAnnotations", expect.objectContaining({ annotations }));+ });++ it("publishes each sidebar panel's data, with the callbacks that drive its own iframe", () => {+ const posted = recordPostsToViewer();++ fromThisViewer({ type: "pdfjs-viewer-toc", data: [+ { title: "Chapter", level: 0, id: "h1", dest: null, items: [ { title: "Section", level: 1, id: "h2", dest: null, items: [] } ] }+ ] });+ // The outline is flattened into the heading list the table of contents renders, levels+ // starting at 1 as headings do.+ expect(contextData.toc).toMatchObject({+ headings: [ { id: "h1", text: "Chapter", level: 1 }, { id: "h2", text: "Section", level: 2 } ],+ activeHeadingId: null+ });+ (contextData.toc as any).scrollToHeading({ id: "h2" });+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-scroll-to-heading", headingId: "h2" }, window.location.origin);++ fromThisViewer({ type: "pdfjs-viewer-active-heading", headingId: "h2" });+ expect(contextData.toc).toMatchObject({ activeHeadingId: "h2" });++ fromThisViewer({ type: "pdfjs-viewer-page-info", totalPages: 12, currentPage: 3 });+ expect(contextData.pdfPages).toMatchObject({ totalPages: 12, currentPage: 3 });+ (contextData.pdfPages as any).scrollToPage(7);+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-scroll-to-page", pageNumber: 7 }, window.location.origin);+ (contextData.pdfPages as any).requestThumbnail(2);+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-request-thumbnail", pageNumber: 2 }, window.location.origin);++ fromThisViewer({ type: "pdfjs-viewer-current-page", currentPage: 5 });+ expect(contextData.pdfPages).toMatchObject({ totalPages: 12, currentPage: 5 });++ fromThisViewer({ type: "pdfjs-viewer-attachments", attachments: [ { id: "a1", filename: "notes.txt", size: 3 } ] });+ (contextData.pdfAttachments as any).downloadAttachment("a1");+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-download-attachment", id: "a1" }, window.location.origin);++ fromThisViewer({ type: "pdfjs-viewer-layers", layers: [ { id: "l1", name: "Layer", visible: true } ] });+ (contextData.pdfLayers as any).toggleLayer("l1", false);+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-toggle-layer", layerId: "l1", visible: false }, window.location.origin);++ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [ { id: "5R", pageNumber: 2 } ] });+ (contextData.pdfAnnotations as any).scrollToAnnotation("5R", 2);+ expect(posted).toHaveBeenLastCalledWith({ type: "trilium-scroll-to-annotation", annotationId: "5R", pageNumber: 2 }, window.location.origin);+ });++ it("leaves a page-tracking update alone until the page info has arrived", () => {+ // A current-page message before page-info has nothing to update, and the active heading+ // likewise waits for the table of contents.+ fromThisViewer({ type: "pdfjs-viewer-current-page", currentPage: 5 });+ fromThisViewer({ type: "pdfjs-viewer-active-heading", headingId: "h1" });+ expect(noteContext.setContextData).not.toHaveBeenCalled();+ });++ it("clears the table of contents when the document has none", () => {+ fromThisViewer({ type: "pdfjs-viewer-toc", data: null });+ expect(contextData.toc).toMatchObject({ headings: [], activeHeadingId: null });+ });++ it("schedules a save when the viewer reports a change, unless the note is read-only", () => {+ fromThisViewer({ type: "pdfjs-viewer-document-modified" });+ expect(spacedUpdate.resetUpdateTimer).toHaveBeenCalledOnce();+ expect(spacedUpdate.scheduleUpdate).toHaveBeenCalledOnce();++ vi.clearAllMocks();+ readOnly.current = true;+ act(() => render(<PdfPreview note={NOTE} noteContext={noteContext} blob={null} componentId="cmp" />, container));+ fromThisViewer({ type: "pdfjs-viewer-document-modified" });+ expect(spacedUpdate.scheduleUpdate).not.toHaveBeenCalled();+ });++ it("relays a thumbnail on the window, marked with the context it was rendered for", () => {+ // Thumbnails arrive one at a time and go out as a window event the page list keys itself;+ // a second viewer relays onto the same window, so each carries its own context.+ const relayed: CustomEvent[] = [];+ const listener = (event: Event) => relayed.push(event as CustomEvent);+ window.addEventListener("pdf-thumbnail", listener);++ fromThisViewer({ type: "pdfjs-viewer-thumbnail", pageNumber: 4, dataUrl: "data:image/png;base64,AAAA" });+ window.removeEventListener("pdf-thumbnail", listener);++ expect(relayed).toHaveLength(1);+ expect(relayed[0].detail).toEqual({ ntxId: "ntx-1", pageNumber: 4, dataUrl: "data:image/png;base64,AAAA" });+ });++ it("fetches the document bytes from the viewer when a save needs them", async () => {+ const posted = recordPostsToViewer();++ // The spaced update asks for the current bytes; the component asks the viewer, which+ // answers with a message addressed back to it. Answers meant for another viewer, or of+ // another kind, are not it.+ const pending = saveOptions.current?.getData() as Promise<Blob>;+ expect(posted).toHaveBeenCalledWith({ type: "trilium-request-blob" }, window.location.origin);+ fromViewer({ type: "pdfjs-viewer-blob", data: new Uint8Array([ 9 ]), noteId: "note-1", ntxId: "ntx-2" });+ fromThisViewer({ type: "pdfjs-viewer-annotations", annotations: [] });+ fromThisViewer({ type: "pdfjs-viewer-blob", data: new Uint8Array([ 37, 80, 68, 70 ]) });++ const blob = await pending;+ expect(blob.type).toBe("application/pdf");+ expect(blob.size).toBe(4);+ });++ it("gives up on a save whose bytes never come, and reloads the viewer on outside changes", async () => {+ recordPostsToViewer();+ vi.useFakeTimers();+ const pending = saveOptions.current?.getData() as Promise<Blob>;+ const rejected = expect(pending).rejects.toThrow("Timeout");+ await vi.advanceTimersByTimeAsync(10_000);+ await rejected;+ vi.useRealTimers();++ // When the note's content changes under it — another client saved — the viewer is+ // reloaded so it shows that document rather than a stale one.+ const iframe = container.querySelector("iframe") as HTMLIFrameElement;+ const frameWindow = iframe.contentWindow as Window;+ const reload = vi.spyOn(frameWindow.location, "reload").mockImplementation(() => {});+ saveOptions.current?.onContentChange({});+ expect(reload).toHaveBeenCalledOnce();++ // With the viewer gone — the note switched away mid-save — there is nothing to ask and+ // nothing to reload; a save in flight simply has no data.+ const options = saveOptions.current;+ act(() => render(null, container));+ expect(options?.getData()).toBeUndefined();+ expect(() => options?.onContentChange({})).not.toThrow();+ });++ it("flushes pending edits before a download, and only for its own context", async () => {+ await eventHandlers.get("customDownload")?.({ ntxId: "ntx-2" });+ expect(spacedUpdate.updateNowIfNecessary).not.toHaveBeenCalled();++ await eventHandlers.get("customDownload")?.({ ntxId: "ntx-1" });+ expect(spacedUpdate.updateNowIfNecessary).toHaveBeenCalledOnce();+ expect(download).toHaveBeenCalledWith(expect.stringMatching(/^\/api\/notes\/note-1\/download\?\d+$/));+ });++ it("forwards print and find to the viewer while it is the active note", () => {+ const posted = recordPostsToViewer();++ eventHandlers.get("printActiveNote")?.({});+ eventHandlers.get("findInText")?.({});+ expect(posted.mock.calls.map(([ message ]) => message)).toEqual([ { type: "trilium-print" }, { type: "trilium-find" } ]);++ // An inactive split must not print or open the find bar for a shortcut meant elsewhere.+ (noteContext as any).isActive = () => false;+ eventHandlers.get("printActiveNote")?.({});+ eventHandlers.get("findInText")?.({});+ expect(posted).toHaveBeenCalledTimes(2);+ });++ it("hands the viewer its identity and stores on load, and claims focus on a click inside", () => {+ vi.spyOn(options, "getJson").mockReturnValue({ sig: 1 });+ const iframe = container.querySelector("iframe") as HTMLIFrameElement;+ iframe.dispatchEvent(new Event("load"));++ const win = iframe.contentWindow as Window;+ expect(win.TRILIUM_NOTE_ID).toBe("note-1");+ expect(win.TRILIUM_NTX_ID).toBe("ntx-1");+ expect(win.TRILIUM_VIEW_HISTORY_STORE).toEqual({ files: [] });+ expect(win.TRILIUM_SIGNATURES).toEqual({ sig: 1 });++ // Clicking inside the frame does not bubble to Trilium's own focus handling, so the+ // component activates its note context itself.+ win.dispatchEvent(new Event("click"));+ expect(activateNoteContext).toHaveBeenCalledWith("ntx-1");+ });++ it("stores the view history and the signature library the viewer hands back", () => {+ const save = vi.spyOn(options, "save").mockResolvedValue(undefined as never);++ fromThisViewer({ type: "pdfjs-viewer-save-view-history", data: JSON.stringify({ files: [ { fingerprint: "f", page: 2 } ] }) });+ expect(historyStore).toHaveBeenCalledWith({ files: [ { fingerprint: "f", page: 2 } ] });++ fromThisViewer({ type: "pdfjs-viewer-save-signatures", data: "{\"sig\":1}" });+ expect(save).toHaveBeenCalledWith("pdfSignatures", "{\"sig\":1}");+ });+});diff --git a/packages/pdfjs-viewer/src/annotations.spec.ts b/packages/pdfjs-viewer/src/annotations.spec.tsindex 54264e9fdc..e6429fed4f 100644--- a/packages/pdfjs-viewer/src/annotations.spec.ts+++ b/packages/pdfjs-viewer/src/annotations.spec.ts@@ -243,7 +243,9 @@ describe("extraction from a real document", () => {[ "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 ] } ]+ [ "pdfjs_internal_editor_2", { annotationType: 9, id: "5R", pageIndex: 0, color: [ 0, 255, 0 ] } ],+ // A signature: a kind the sidebar does not list, so it stays out here as well.+ [ "pdfjs_internal_editor_3", { annotationType: 13, id: null, pageIndex: 0, isSignature: true } ]]),hash: "x",transfer: []@@ -260,6 +262,7 @@ describe("extraction from a real document", () => {]);// 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);+ expect(annotations.some((annotation: any) => annotation.id === "pdfjs_internal_editor_3")).toBe(false);});it("removes deleted annotations even when they are adjacent", async () => {@@ -368,6 +371,20 @@ describe("scrolling to an annotation", () => {expect(viewer.scrollRequests).toHaveBeenCalledWith(expect.objectContaining({ behavior: "smooth" }));});+ it("ignores a scroll request from another origin", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfAnnotations();+ renderAnnotation("5R");++ window.dispatchEvent(new MessageEvent("message", {+ data: { type: "trilium-scroll-to-annotation", annotationId: "5R", pageNumber: 1 },+ origin: "https://evil.example"+ }));+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(viewer.scrollRequests).not.toHaveBeenCalled();+ });+it("scrolls to an annotation that only exists in the editor", async () => {viewer = await installViewerApp(allFeaturesPdf());await setupPdfAnnotations();@@ -394,6 +411,10 @@ describe("scrolling to an annotation", () => {await vi.waitFor(() => expect(window.PDFViewerApplication?.pdfViewer.currentPageNumber).toBe(2));expect(viewer.scrollRequests).not.toHaveBeenCalled();+ // Other things render meanwhile; only the annotation itself ends the wait.+ viewer.viewerEl.append(document.createElement("div"));+ await new Promise((resolve) => setTimeout(resolve, 0));+ 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/annotations.ts b/packages/pdfjs-viewer/src/annotations.tsindex 748dcd3818..eeee0fdccd 100644--- a/packages/pdfjs-viewer/src/annotations.ts+++ b/packages/pdfjs-viewer/src/annotations.ts@@ -64,7 +64,7 @@ function resolveTypeName(ann: Record<string, any>): string {return TYPE_NAMES[AnnotationType.HIGHLIGHT];}- return TYPE_NAMES[ann.annotationType] ?? "unknown";+ return TYPE_NAMES[ann.annotationType];}export async function setupPdfAnnotations() {@@ -201,7 +201,7 @@ function unsavedAnnotations(storage: any): PdfAnnotationInfo[] {contents: typeof serialized.value === "string" ? serialized.value : "",highlightedText: "",author: "",- pageNumber: (serialized.pageIndex ?? 0) + 1,+ pageNumber: serialized.pageIndex + 1,// As in applyEditorOverrides: a text box's colour is that of its text, not a tint.color: serialized.color && type !== "freetext" ? rgbToHex(serialized.color) : null,creationDate: null,diff --git a/packages/pdfjs-viewer/src/bootstrap.spec.ts b/packages/pdfjs-viewer/src/bootstrap.spec.tsindex 7b6fb4215b..5b0c0130ce 100644--- a/packages/pdfjs-viewer/src/bootstrap.spec.ts+++ b/packages/pdfjs-viewer/src/bootstrap.spec.ts@@ -223,6 +223,34 @@ describe("reporting the document as modified", () => {expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(1);});+ it("treats a document that cannot be serialized as unchanged, then catches up", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ const storage = viewer.pdfDocument.annotationStorage as any;+ // pdf.js stores an editor before it is finished: "Add signature" leaves one with no+ // outlines in annotationStorage until the dialog resolves, and serializing it throws.+ // That is a state pdf.js passes through, not a change to report — and not a reason to+ // let the throw out of the storage hook, or out of the setup, either.+ const serializable = vi.spyOn(storage, "serializable", "get").mockImplementation(() => {+ throw new Error("outlines are not set yet");+ });+ expect(() => manageSave()).not.toThrow();++ expect(() => storage.setValue("sig-1", { value: "pending" })).not.toThrow();+ viewer.eventBus.dispatch("switchannotationeditorparams", { source: null });+ expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(0);++ // The interaction nudges still report blind, and cope with the same state.+ startEditing();+ renderPage().dispatchEvent(new Event("keyup", { bubbles: true }));+ expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(1);++ // Once the editor is complete the document serializes again, and the change it made is+ // reported against the last hash that could be read — not swallowed.+ serializable.mockRestore();+ storage.setValue("sig-1", { value: "signed" });+ expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(2);+ });+it("stays quiet when a tool's parameters leave the document alone", async () => {viewer = await installViewerApp(allFeaturesPdf());manageSave();diff --git a/packages/pdfjs-viewer/src/bootstrap.ts b/packages/pdfjs-viewer/src/bootstrap.tsindex 8ded75234d..4d588e8d6a 100644--- a/packages/pdfjs-viewer/src/bootstrap.ts+++ b/packages/pdfjs-viewer/src/bootstrap.ts@@ -142,7 +142,7 @@ export function manageSave() {*/function serializedHash(): string | null {try {- return (storage as any)?.serializable?.hash ?? "";+ return (storage as any).serializable.hash;} catch {return null;}@@ -155,7 +155,6 @@ export function manageSave() {* extended one has to be passed on blind.*/function onChange() {- if (!storage) return;reportedHash = serializedHash() ?? reportedHash;storage.resetModified();announceModified();@@ -176,7 +175,6 @@ export function manageSave() {* registration order.*/function reportIfChanged() {- if (!storage) return;// Cleared whether or not this turns into an announcement: pdf.js raises the storage hook// once per dirtying, so a flag left set would swallow the next real change.storage.resetModified();