Skip to content

Build your personal knowledge base with Trilium Notes

fix(pdf): address the viewer's messages before its frame has loaded

Elian Dorane526b881d87c
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
index 6906863dd9..f8e4222e0f 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.spec.tsx
@@ -34,8 +34,9 @@ vi.mock("../../collections/NoteList", () => ({
// 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} />,
+ default: ({ iframeRef, onLoad, noteId, ntxId }: {
+ iframeRef: { current: HTMLIFrameElement | null }; onLoad: () => void; noteId?: string; ntxId?: string | null;
+ }) => <iframe ref={iframeRef} class="pdf-preview" onLoad={onLoad} data-note-id={noteId} data-ntx-id={ntxId} />,
getPdfUrl: (path: string) => `/api/${path}`
}));
const activateNoteContext = vi.hoisted(() => vi.fn());
@@ -256,14 +257,14 @@ describe("PdfPreview", () => {
expect(posted).toHaveBeenCalledTimes(2);
});
- it("hands the viewer its identity and stores on load, and claims focus on a click inside", () => {
+ it("hands the viewer its identity in the URL and its stores on load, and claims focus on a click inside", () => {
vi.spyOn(options, "getJson").mockReturnValue({ sig: 1 });
const iframe = container.querySelector("iframe") as HTMLIFrameElement;
+ // The viewer can post before `load`, so the address it stamps on messages goes in the URL.
+ expect(iframe.dataset).toMatchObject({ noteId: "note-1", ntxId: "ntx-1" });
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 });
diff --git a/apps/client/src/widgets/type_widgets/file/Pdf.tsx b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
index 9f35c2d5d5..51958bec09 100644
--- a/apps/client/src/widgets/type_widgets/file/Pdf.tsx
+++ b/apps/client/src/widgets/type_widgets/file/Pdf.tsx
@@ -244,8 +244,6 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
if (win) {
win.TRILIUM_VIEW_HISTORY_STORE = historyConfig.config;
win.TRILIUM_SIGNATURES = options.getJson("pdfSignatures") ?? {};
- win.TRILIUM_NOTE_ID = note.noteId;
- win.TRILIUM_NTX_ID = noteContext.ntxId;
}
if (iframeRef.current?.contentWindow) {
@@ -255,6 +253,8 @@ export default function PdfPreview({ note, blob, componentId, noteContext }: {
}
}}
editable={!isReadOnly}
+ noteId={note.noteId}
+ ntxId={noteContext.ntxId}
/>
);
}
diff --git a/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx b/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx
index 46ce907f84..43b1910e42 100644
--- a/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/file/PdfViewer.spec.tsx
@@ -1,9 +1,31 @@
import { existsSync } from "node:fs";
import path from "node:path";
+import { render } from "preact";
import { afterEach, describe, expect, it } from "vitest";
-import { getFontFaceCss, getPdfUrl } from "./PdfViewer";
+import PdfViewer, { getFontFaceCss, getPdfUrl } from "./PdfViewer";
+
+describe("PdfViewer", () => {
+ function viewerUrl(props: { noteId?: string; ntxId?: string | null }) {
+ const container = document.createElement("div");
+ render(<PdfViewer pdfUrl="/api/notes/abc123/open" {...props} />, container);
+ const src = container.querySelector("iframe")?.getAttribute("src");
+ render(null, container);
+ return new URL(src ?? "", "http://localhost").searchParams;
+ }
+
+ it("addresses the viewer in its URL, so it can post before the frame loads", () => {
+ const params = viewerUrl({ noteId: "abc123", ntxId: "ntx 1" });
+ expect(params.get("noteId")).toBe("abc123");
+ expect(params.get("ntxId")).toBe("ntx 1");
+ expect(params.get("file")).toBe("/api/notes/abc123/open");
+
+ // A viewer outside a note (print preview, lightbox, revisions) reports to no one.
+ expect(viewerUrl({}).has("noteId")).toBe(false);
+ expect(viewerUrl({ noteId: "abc123", ntxId: null }).has("ntxId")).toBe(false);
+ });
+});
describe("getPdfUrl", () => {
afterEach(() => history.replaceState({}, "", "/"));
diff --git a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
index fdad094da7..68967f413f 100644
--- a/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/PdfViewer.tsx
@@ -34,12 +34,18 @@ interface PdfViewerProps extends Pick<HTMLAttributes<HTMLIFrameElement>, "tabInd
* crisper preview. Has no effect when the real DPR already meets or exceeds this value.
*/
minPixelRatio?: number;
+ /**
+ * The note and note context the viewer addresses its messages to. They travel in the URL so
+ * that messages posted before the frame's `load` event carry them too.
+ */
+ noteId?: string;
+ ntxId?: string | null;
}
/**
* Reusable component displaying a PDF. The PDF needs to be provided via a URL.
*/
-export default function PdfViewer({ iframeRef: externalIframeRef, pdfUrl, onLoad, editable, toolbar = true, disableSelection, minPixelRatio }: PdfViewerProps) {
+export default function PdfViewer({ iframeRef: externalIframeRef, pdfUrl, onLoad, editable, toolbar = true, disableSelection, minPixelRatio, noteId, ntxId }: PdfViewerProps) {
const iframeRef = useSyncedRef(externalIframeRef, null);
const [ locale ] = useTriliumOption("locale");
const [ newLayout ] = useTriliumOptionBool("newLayout");
@@ -50,7 +56,7 @@ export default function PdfViewer({ iframeRef: externalIframeRef, pdfUrl, onLoad
ref={iframeRef}
class="pdf-preview"
style={{width: "100%", height: "100%"}}
- src={`pdfjs/web/viewer.html?v=${glob.triliumVersion}&file=${pdfUrl}&locale=${locale}&sidebar=${newLayout ? "0" : "1"}&editable=${editable ? "1" : "0"}&toolbar=${toolbar ? "1" : "0"}${minPixelRatio ? `&minPixelRatio=${minPixelRatio}` : ""}`}
+ src={`pdfjs/web/viewer.html?v=${glob.triliumVersion}&file=${pdfUrl}&locale=${locale}&sidebar=${newLayout ? "0" : "1"}&editable=${editable ? "1" : "0"}&toolbar=${toolbar ? "1" : "0"}${minPixelRatio ? `&minPixelRatio=${minPixelRatio}` : ""}${noteId ? getAddressParams(noteId, ntxId) : ""}`}
onLoad={() => {
injectStyles();
onLoad?.();
@@ -59,6 +65,10 @@ export default function PdfViewer({ iframeRef: externalIframeRef, pdfUrl, onLoad
);
}
+function getAddressParams(noteId: string, ntxId: string | null | undefined) {
+ return `&noteId=${encodeURIComponent(noteId)}${ntxId ? `&ntxId=${encodeURIComponent(ntxId)}` : ""}`;
+}
+
function useStyleInjection(iframeRef: RefObject<HTMLIFrameElement>, disableSelection?: boolean) {
const styleRef = useRef<HTMLStyleElement | null>(null);
diff --git a/packages/pdfjs-viewer/e2e/harness/parent.html b/packages/pdfjs-viewer/e2e/harness/parent.html
index 4fb6057cc8..113c827998 100644
--- a/packages/pdfjs-viewer/e2e/harness/parent.html
+++ b/packages/pdfjs-viewer/e2e/harness/parent.html
@@ -4,7 +4,7 @@
<body style="margin:0">
<!-- Stub of the Trilium client: hosts the viewer in an iframe and speaks the
postMessage protocol of apps/client/src/widgets/type_widgets/file/Pdf.tsx. -->
-<iframe id="viewer" src="web/viewer.html?v=e2e&file=/sample.pdf&locale=en&sidebar=1&editable=1&toolbar=1"
+<iframe id="viewer" src="web/viewer.html?v=e2e&file=/sample.pdf&locale=en&sidebar=1&editable=1&toolbar=1&noteId=note1&ntxId=ntx1"
style="width:1200px;height:850px;border:none"></iframe>
<script>
window.harness = {
@@ -16,8 +16,6 @@
const iframe = document.getElementById("viewer");
iframe.addEventListener("load", () => {
- iframe.contentWindow.TRILIUM_NOTE_ID = "note1";
- iframe.contentWindow.TRILIUM_NTX_ID = "ntx1";
iframe.contentWindow.TRILIUM_VIEW_HISTORY_STORE = {};
});
diff --git a/packages/pdfjs-viewer/e2e/message-ids.spec.ts b/packages/pdfjs-viewer/e2e/message-ids.spec.ts
new file mode 100644
index 0000000000..c7bdf7b0e4
--- /dev/null
+++ b/packages/pdfjs-viewer/e2e/message-ids.spec.ts
@@ -0,0 +1,27 @@
+import { expect, test } from "@playwright/test";
+
+/**
+ * The client drops every message whose `noteId`/`ntxId` is not its own, so a message sent before
+ * the viewer knows them never reaches the sidebar.
+ */
+test("addresses the messages sent while the viewer page is still loading", async ({ page, context }) => {
+ // Icons the toolbar loads through CSS hold back the frame's `load` event, but not the document.
+ await context.route("**/images/**", async (route) => {
+ await new Promise((resolve) => setTimeout(resolve, 3_000));
+ await route.continue();
+ });
+ await page.addInitScript(() => {
+ if (window.top !== window) return;
+ (window as any).pageInfo = [];
+ window.addEventListener("message", (event: any) => {
+ if (event.data?.type === "pdfjs-viewer-page-info") {
+ (window as any).pageInfo.push({ noteId: event.data.noteId, ntxId: event.data.ntxId });
+ }
+ });
+ });
+
+ await page.goto("/parent.html");
+
+ await expect.poll(() => page.evaluate(() => (window as any).pageInfo), { timeout: 15_000 })
+ .toContainEqual({ noteId: "note1", ntxId: "ntx1" });
+});
diff --git a/packages/pdfjs-viewer/src/bootstrap.spec.ts b/packages/pdfjs-viewer/src/bootstrap.spec.ts
index 5b0c0130ce..b05d1b8be2 100644
--- a/packages/pdfjs-viewer/src/bootstrap.spec.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.spec.ts
@@ -125,6 +125,21 @@ describe("boot sequence", () => {
}
});
+ it("takes the note and context it reports to from the URL, before the frame has loaded", async () => {
+ // The parent assigns nothing until the frame's `load` event, which a small document can beat.
+ delete (window as Partial<Window>).TRILIUM_NOTE_ID;
+ delete (window as Partial<Window>).TRILIUM_NTX_ID;
+ viewer = await installViewerApp(allFeaturesPdf());
+ await bootWith("editable=1&noteId=note-2&ntxId=ntx-2");
+
+ viewer.eventBus.dispatch("documentloaded", { source: null });
+ await vi.waitFor(() => expect(viewer.messagesOfType("pdfjs-viewer-page-info").length).toBeGreaterThan(0));
+
+ for (const message of viewer.messages) {
+ expect(message).toMatchObject({ noteId: "note-2", ntxId: "ntx-2" });
+ }
+ });
+
it("applies the toolbar and sidebar switches from the URL", async () => {
document.body.innerHTML = `
<div id="viewsManagerToggleButton"></div>
diff --git a/packages/pdfjs-viewer/src/bootstrap.ts b/packages/pdfjs-viewer/src/bootstrap.ts
index 4d588e8d6a..3eaec8b6d6 100644
--- a/packages/pdfjs-viewer/src/bootstrap.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.ts
@@ -10,6 +10,14 @@ export async function main() {
const urlParams = new URLSearchParams(window.location.search);
const isEditable = urlParams.get("editable") === "1";
+ // The client drops every message not addressed to its own note and context, and a small
+ // document can post before the frame's `load` event, so the address comes with the URL.
+ const noteId = urlParams.get("noteId");
+ if (noteId !== null) {
+ window.TRILIUM_NOTE_ID = noteId;
+ window.TRILIUM_NTX_ID = urlParams.get("ntxId");
+ }
+
applyMinPixelRatio(urlParams);
const hideToolbar = urlParams.get("toolbar") === "0";