Skip to content

Build your personal knowledge base with Trilium Notes

fix(pdf): stop reporting a change when pdf.js registers stored annotations

Elian Doran3917ad76e7ef
diff --git a/packages/pdfjs-viewer/e2e/annotation-save.spec.ts b/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
index 62f3cb56c9..1a6623c75d 100644
--- a/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
+++ b/packages/pdfjs-viewer/e2e/annotation-save.spec.ts
@@ -115,6 +115,36 @@ test("leaves an annotation the user has selected selected", async ({ page }) =>
expect(await selectedEditorCount(page)).toBe(1);
});
+test("picking a tool on an already-annotated document schedules nothing", async ({ page, context }) => {
+ // Produce a document that carries a stored annotation, the way any previously annotated
+ // PDF does.
+ const first = await openHarness(page);
+ await enterInkMode(first);
+ await drawStroke(page, await pageBox(first), [[200, 200], [320, 260]]);
+ await page.waitForTimeout(500);
+ const bytes = await requestBlob(page, 1);
+
+ await context.route("**/sample.pdf", (route) => route.fulfill({
+ body: Buffer.from(bytes),
+ contentType: "application/pdf"
+ }));
+ const reopened = await context.newPage();
+ const viewer = await openHarness(reopened);
+ expect(await modifiedCount(reopened)).toBe(0);
+
+ // Entering an editing mode registers that stored annotation as an editor, which dirties
+ // annotationStorage without changing the document. Reporting it would have the parent
+ // re-serialise and re-upload the whole PDF for a button press (#11059).
+ await enterHighlightMode(viewer);
+ await reopened.waitForTimeout(1200);
+ expect(await modifiedCount(reopened)).toBe(0);
+
+ // The document is still saveable: drawing on it reports as usual.
+ await drawStroke(reopened, await pageBox(viewer), [[200, 400], [320, 440]]);
+ await reopened.waitForTimeout(500);
+ expect(await modifiedCount(reopened)).toBeGreaterThan(0);
+});
+
test("annotations survive reopening the saved document", async ({ page, context }) => {
const viewer = await openHarness(page);
await enterInkMode(viewer);
diff --git a/packages/pdfjs-viewer/src/bootstrap.spec.ts b/packages/pdfjs-viewer/src/bootstrap.spec.ts
index c14ed982c8..78ff68478c 100644
--- a/packages/pdfjs-viewer/src/bootstrap.spec.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.spec.ts
@@ -98,8 +98,8 @@ describe("boot sequence", () => {
await vi.waitFor(() => expect(viewer.messagesOfType(type).length).toBeGreaterThan(0));
}
- // And the save plumbing is live.
- (viewer.pdfDocument.annotationStorage as any).onSetModified?.();
+ // And the save plumbing is live: dirtying the storage reaches the parent.
+ (viewer.pdfDocument.annotationStorage as any).setValue("field-1", { value: "typed" });
expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(1);
});
@@ -164,8 +164,8 @@ describe("reporting the document as modified", () => {
const resetModified = vi.spyOn(storage, "resetModified");
manageSave();
- // The primary hook: pdf.js calls this whenever annotationStorage is dirtied.
- storage.onSetModified();
+ // The primary hook: pdf.js dirties annotationStorage, as filling in a form field does.
+ storage.setValue("field-1", { value: "typed" });
// A tool's parameters changing (colour, thickness) also mutates the document.
viewer.eventBus.dispatch("switchannotationeditorparams", { source: null });
// Deletions and undo/redo only surface here, and only when there is something to undo.
@@ -178,6 +178,29 @@ describe("reporting the document as modified", () => {
expect(resetModified).toHaveBeenCalledTimes(3);
});
+ it("stays quiet while pdf.js registers the annotations already in the document", async () => {
+ viewer = await installViewerApp(allFeaturesPdf());
+ const storage = viewer.pdfDocument.annotationStorage as any;
+ const resetModified = vi.spyOn(storage, "resetModified");
+ manageSave();
+
+ // Entering an editing mode turns every stored annotation on a rendered page into an
+ // editor, and registering each one dirties annotationStorage. Nothing about the document
+ // changed, so pressing a toolbar button — or scrolling another annotated page into view —
+ // must not schedule a save, let alone one per annotation (#11059).
+ storage.onSetModified();
+ storage.onSetModified();
+
+ expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(0);
+ // The flag still has to be cleared, or pdf.js' one-shot would never raise the next
+ // real change.
+ expect(resetModified).toHaveBeenCalledTimes(2);
+
+ // Which it does: an actual edit is still reported.
+ storage.setValue("field-1", { value: "typed" });
+ expect(viewer.messagesOfType("pdfjs-viewer-document-modified")).toHaveLength(1);
+ });
+
it("stays quiet when the editing state changes with nothing to undo", async () => {
viewer = await installViewerApp(allFeaturesPdf());
manageSave();
diff --git a/packages/pdfjs-viewer/src/bootstrap.ts b/packages/pdfjs-viewer/src/bootstrap.ts
index e8a4cab3dd..af18cd7514 100644
--- a/packages/pdfjs-viewer/src/bootstrap.ts
+++ b/packages/pdfjs-viewer/src/bootstrap.ts
@@ -125,14 +125,57 @@ export function manageSave() {
let pointerDown = false;
let pointerDownOnPage = false;
+ // What the document held when the parent was last told about it. Compared against, rather
+ // than trusted, because pdf.js reports far more than actual changes — see onStorageModified.
+ let reportedHash = serializedHash();
+
+ /**
+ * A digest of everything `saveDocument()` would write out. pdf.js serializes an annotation it
+ * has not modified to nothing at all, so this stays put while the ones already stored in the
+ * document are registered, and moves as soon as one is genuinely edited.
+ */
+ function serializedHash(): string {
+ return (storage as any)?.serializable?.hash ?? "";
+ }
+
+ /**
+ * Reports a possible modification, without asking whether the document really changed —
+ * for signals that can be raised by an edit `annotationStorage` cannot see yet. An ink
+ * drawing session lives outside it until committed, so an interaction that might have
+ * extended one has to be passed on blind.
+ */
function onChange() {
if (!storage) return;
+ reportedHash = serializedHash();
+ storage.resetModified();
+ announceModified();
+ }
+
+ /**
+ * pdf.js dirtied `annotationStorage`. That covers real edits, but also every time an editing
+ * mode turns the annotations already stored on a rendered page into editors — one signal per
+ * annotation, raised again for each page that scrolls into view. Passing those on had the
+ * parent re-serialise and re-upload the whole PDF because a toolbar button was pressed
+ * (#11059), so the content is compared before anything is announced.
+ */
+ function onStorageModified() {
+ if (!storage) return;
+ // Cleared whether or not this turns into an announcement: pdf.js raises the hook once per
+ // dirtying, so a flag left set would swallow the next real change.
+ storage.resetModified();
+
+ const hash = serializedHash();
+ if (hash === reportedHash) return;
+ reportedHash = hash;
+ announceModified();
+ }
+
+ function announceModified() {
window.parent.postMessage({
type: "pdfjs-viewer-document-modified",
ntxId: window.TRILIUM_NTX_ID,
noteId: window.TRILIUM_NOTE_ID
} satisfies PdfDocumentModifiedMessage, window.location.origin);
- storage.resetModified();
}
window.addEventListener("message", async (event) => {
@@ -157,7 +200,7 @@ export function manageSave() {
});
(app.pdfDocument.annotationStorage as any).onSetModified = () => {
- onChange();
+ onStorageModified();
}; // works great for most cases, including forms.
app.eventBus.on("switchannotationeditorparams", () => {
onChange();