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): commit in-progress annotation edits when saving
Elian Doran24ec508de178
diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.ymlindex 8b696a457a..c15b8295f7 100644--- a/.github/workflows/playwright.yml+++ b/.github/workflows/playwright.yml@@ -115,6 +115,34 @@ jobs:if: always()run: pkill -f trilium || true+ e2e-pdfjs-viewer:+ runs-on: ubuntu-22.04+ name: PDF viewer E2E tests+ steps:+ - uses: actions/checkout@v7++ - uses: pnpm/action-setup@v6+ - uses: actions/setup-node@v6+ with:+ node-version: 24+ cache: 'pnpm'++ - name: Install dependencies+ run: pnpm install --frozen-lockfile++ - name: Install Playwright browsers+ run: pnpm exec playwright install --with-deps chromium++ - name: PDF viewer end-to-end tests+ run: pnpm --filter pdfjs-viewer e2e++ - name: Upload test report+ if: failure()+ uses: actions/upload-artifact@v7+ with:+ name: pdfjs-viewer e2e report+ path: packages/pdfjs-viewer/test-output+e2e-standalone:strategy:fail-fast: falsediff --git a/packages/pdfjs-viewer/e2e/annotation-save.spec.ts b/packages/pdfjs-viewer/e2e/annotation-save.spec.tsnew file mode 100644index 0000000000..6be8228713--- /dev/null+++ b/packages/pdfjs-viewer/e2e/annotation-save.spec.ts@@ -0,0 +1,168 @@+import { expect, type FrameLocator, type Page, test } from "@playwright/test";++/**+ * Covers the annotation save flow of custom.ts/editing.ts: in-progress ink+ * drawing sessions live outside pdf.js' annotationStorage until committed, so+ * a save request must commit them (without disturbing active interactions) and+ * silent edits must still announce document modifications to the parent.+ */++test("commits an in-progress ink drawing when a save is requested", async ({ page }) => {+ const viewer = await openHarness(page);+ await enterInkMode(viewer);+ const box = await pageBox(viewer);++ // Draw two strokes and stay in ink mode — the annotate button is never+ // pressed again, which previously left the drawing uncommitted forever.+ await drawStroke(page, box, [[200, 200], [300, 250], [380, 210]]);+ await drawStroke(page, box, [[220, 320], [340, 360]]);+ await page.waitForTimeout(500);++ // Every stroke announces a potential modification (the first via pdf.js+ // editing states, later ones via the interaction-end nudge).+ expect(await modifiedCount(page)).toBeGreaterThanOrEqual(2);++ // The save must contain the drawing even though its session was never+ // committed by the user.+ const bytes = await requestBlob(page, 1);+ expect(countInkAnnotations(bytes)).toBe(1);++ // Drawing after the save starts a fresh session, which pdf.js tracks+ // completely silently — the nudge must still announce it so another save+ // gets scheduled, and that save must include it.+ const modifiedBefore = await modifiedCount(page);+ await drawStroke(page, box, [[500, 400], [600, 470], [650, 420]]);+ await page.waitForTimeout(500);+ expect(await modifiedCount(page)).toBeGreaterThan(modifiedBefore);+ expect(countInkAnnotations(await requestBlob(page, 2))).toBe(2);+});++test("does not cut short a stroke that is mid-draw when a save happens", async ({ page }) => {+ const viewer = await openHarness(page);+ await enterInkMode(viewer);+ const box = await pageBox(viewer);++ await drawStroke(page, box, [[200, 200], [320, 260]]);+ await page.waitForTimeout(500);+ expect(countInkAnnotations(await requestBlob(page, 1))).toBe(1);++ // Hold a stroke mid-draw and let a save fire: the commit must be skipped+ // (not truncating the stroke) and the save must still complete.+ await page.mouse.move(box.x + 500, box.y + 300);+ await page.mouse.down();+ await page.mouse.move(box.x + 560, box.y + 360, { steps: 5 });+ const midStrokeBytes = await requestBlob(page, 2);+ expect(countInkAnnotations(midStrokeBytes)).toBe(1);++ // Finishing the stroke re-announces a modification, and the follow-up save+ // then contains the previously skipped drawing.+ const modifiedBefore = await modifiedCount(page);+ await page.mouse.move(box.x + 620, box.y + 310, { steps: 5 });+ await page.mouse.up();+ await page.waitForTimeout(500);+ expect(await modifiedCount(page)).toBeGreaterThan(modifiedBefore);+ expect(countInkAnnotations(await requestBlob(page, 3))).toBe(2);+});++test("annotations survive reopening the saved document", async ({ page, context }) => {+ const viewer = await openHarness(page);+ await enterInkMode(viewer);+ const box = await pageBox(viewer);++ await drawStroke(page, box, [[250, 250], [400, 330], [480, 260]]);+ await page.waitForTimeout(500);+ const bytes = await requestBlob(page, 1);++ // Open a fresh viewer on the saved bytes — the equivalent of refreshing+ // Trilium after the auto-save.+ await context.route("**/saved.pdf", (route) => route.fulfill({+ body: Buffer.from(bytes),+ contentType: "application/pdf"+ }));+ const reopened = await context.newPage();+ await addPolyfills(reopened);+ await reopened.goto("/web/viewer.html?v=e2e&file=/saved.pdf&locale=en&editable=1&toolbar=1");+ await reopened.locator(".page canvas").first().waitFor({ state: "visible" });++ const inkCount = await reopened.evaluate(async () => {+ const pdfDocument = (window as any).PDFViewerApplication.pdfDocument;+ const firstPage = await pdfDocument.getPage(1);+ const annotations = await firstPage.getAnnotations({ intent: "display" });+ return annotations.filter((annotation: any) => annotation.subtype === "Ink").length;+ });+ expect(inkCount).toBe(1);+});++/**+ * pdf.js v6 requires Map.prototype.getOrInsertComputed and Math.sumPrecise+ * (Chromium >= 143); polyfill them so the tests also run on older browsers.+ * The worker gets the same polyfills from the harness server.+ */+async function addPolyfills(page: Page) {+ await page.addInitScript(() => {+ const mapPrototype = Map.prototype as any;+ if (!mapPrototype.getOrInsertComputed) {+ mapPrototype.getOrInsertComputed = function (key: unknown, cb: (key: unknown) => unknown) {+ if (!this.has(key)) this.set(key, cb(key));+ return this.get(key);+ };+ }+ const math = Math as any;+ if (!math.sumPrecise) {+ math.sumPrecise = (values: Iterable<number>) => {+ let sum = 0;+ for (const value of values) sum += value;+ return sum;+ };+ }+ });+}++async function openHarness(page: Page): Promise<FrameLocator> {+ await addPolyfills(page);+ await page.goto("/parent.html");+ const viewer = page.frameLocator("#viewer");+ await viewer.locator(".page canvas").first().waitFor({ state: "visible" });+ await page.waitForTimeout(1000); // let the editor layers settle+ return viewer;+}++async function enterInkMode(viewer: FrameLocator) {+ await viewer.locator("#editorInkButton").click();+ await viewer.locator(".annotationEditorLayer").first().waitFor({ state: "attached" });+}++async function pageBox(viewer: FrameLocator) {+ const box = await viewer.locator(".page").first().boundingBox();+ expect(box).not.toBeNull();+ if (!box) throw new Error("PDF page not rendered");+ return box;+}++async function drawStroke(page: Page, box: { x: number; y: number }, points: [number, number][]) {+ const [first, ...rest] = points;+ await page.mouse.move(box.x + first[0], box.y + first[1]);+ await page.mouse.down();+ for (const [x, y] of rest) {+ await page.mouse.move(box.x + x, box.y + y, { steps: 8 });+ }+ await page.mouse.up();+ await page.waitForTimeout(200);+}++function modifiedCount(page: Page): Promise<number> {+ return page.evaluate(() => (window as any).harness.modifiedCount);+}++/** Requests the document bytes like the Trilium spaced-update save does. */+async function requestBlob(page: Page, expectedCount: number): Promise<number[]> {+ await page.evaluate(() => (window as any).requestBlob());+ await page.waitForFunction((count) => (window as any).harness.blobs.length >= count, expectedCount);+ return page.evaluate((count) => (window as any).harness.blobs[count - 1], expectedCount);+}++/** Ink annotations appear in the incrementally-saved PDF as `/Subtype /Ink` objects. */+function countInkAnnotations(bytes: number[]): number {+ const text = Buffer.from(bytes).toString("latin1");+ return (text.match(/\/Subtype[\s]*\/Ink/g) ?? []).length;+}diff --git a/packages/pdfjs-viewer/e2e/harness/parent.html b/packages/pdfjs-viewer/e2e/harness/parent.htmlnew file mode 100644index 0000000000..4fb6057cc8--- /dev/null+++ b/packages/pdfjs-viewer/e2e/harness/parent.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<html>+<head><title>pdfjs-viewer e2e harness</title></head>+<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"+ style="width:1200px;height:850px;border:none"></iframe>+<script>+ window.harness = {+ /** Number of pdfjs-viewer-document-modified messages received. */+ modifiedCount: 0,+ /** Byte arrays received via pdfjs-viewer-blob, in order. */+ blobs: []+ };++ 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 = {};+ });++ window.addEventListener("message", (event) => {+ const data = event.data;+ if (!data || !data.type) return;+ if (data.type === "pdfjs-viewer-document-modified") {+ window.harness.modifiedCount++;+ }+ if (data.type === "pdfjs-viewer-blob") {+ window.harness.blobs.push(Array.from(new Uint8Array(data.data)));+ }+ });++ /** Asks the viewer for the current document bytes, like the spaced-update save does. */+ window.requestBlob = () => {+ iframe.contentWindow.postMessage({ type: "trilium-request-blob" }, window.location.origin);+ };+</script>+</body>+</html>diff --git a/packages/pdfjs-viewer/e2e/harness/serve.mjs b/packages/pdfjs-viewer/e2e/harness/serve.mjsnew file mode 100644index 0000000000..aef73d9a2b--- /dev/null+++ b/packages/pdfjs-viewer/e2e/harness/serve.mjs@@ -0,0 +1,101 @@+/**+ * Static server for the viewer e2e tests. Serves the built viewer (`dist/web`,+ * `dist/build`), the parent-page stub emulating the Trilium client, and a+ * generated blank PDF to annotate. Started by Playwright via the webServer+ * option in playwright.config.ts.+ */+import { createServer } from "node:http";+import { readFile } from "node:fs/promises";+import { extname, join, normalize, sep } from "node:path";+import { fileURLToPath } from "node:url";++const HARNESS_DIR = fileURLToPath(new URL(".", import.meta.url));+const DIST_DIR = join(HARNESS_DIR, "..", "..", "dist");+const PORT = Number(process.env.PDFJS_E2E_PORT ?? "8935");++const MIME_TYPES = {+ ".html": "text/html",+ ".mjs": "text/javascript",+ ".js": "text/javascript",+ ".css": "text/css",+ ".json": "application/json",+ ".pdf": "application/pdf",+ ".svg": "image/svg+xml",+ ".png": "image/png",+ ".gif": "image/gif",+ ".ftl": "text/plain",+ ".wasm": "application/wasm"+};++// pdf.js v6 relies on Map.prototype.getOrInsertComputed and Math.sumPrecise+// (Chromium >= 143). The main thread is polyfilled from the spec via+// addInitScript, but that does not reach the worker, so older browsers need the+// polyfill prepended to the worker bundle itself. No-op on current browsers.+const WORKER_POLYFILLS = `+if (!Map.prototype.getOrInsertComputed) {+ Map.prototype.getOrInsertComputed = function (key, cb) {+ if (!this.has(key)) this.set(key, cb(key));+ return this.get(key);+ };+}+if (!Math.sumPrecise) {+ Math.sumPrecise = function (values) { let s = 0; for (const v of values) s += v; return s; };+}+`;++const samplePdf = buildBlankPdf();++const server = createServer(async (req, res) => {+ const url = new URL(req.url, `http://127.0.0.1:${PORT}`);+ try {+ if (url.pathname === "/parent.html") {+ return send(res, "text/html", await readFile(join(HARNESS_DIR, "parent.html")));+ }+ if (url.pathname === "/sample.pdf") {+ return send(res, "application/pdf", samplePdf);+ }+ if (url.pathname.startsWith("/web/") || url.pathname.startsWith("/build/")) {+ const relative = normalize(url.pathname).split(sep).filter(part => part && part !== "..").join(sep);+ let content = await readFile(join(DIST_DIR, relative));+ if (url.pathname === "/build/pdf.worker.mjs") {+ content = Buffer.concat([Buffer.from(WORKER_POLYFILLS), content]);+ }+ return send(res, MIME_TYPES[extname(relative)] ?? "application/octet-stream", content);+ }+ res.writeHead(404).end("Not found");+ } catch (e) {+ res.writeHead(e?.code === "ENOENT" ? 404 : 500).end(String(e?.message ?? e));+ }+});++server.listen(PORT, "127.0.0.1", () => {+ console.log(`pdfjs-viewer e2e harness listening on http://127.0.0.1:${PORT}`);+});++function send(res, contentType, content) {+ res.writeHead(200, { "Content-Type": contentType });+ res.end(content);+}++/** Builds a minimal single-page blank PDF (US Letter) for the tests to annotate. */+function buildBlankPdf() {+ const objects = [+ "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",+ "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n",+ "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << >> /Contents 4 0 R >>\nendobj\n",+ "4 0 obj\n<< /Length 0 >>\nstream\n\nendstream\nendobj\n"+ ];+ let pdf = "%PDF-1.4\n";+ const offsets = [];+ for (const object of objects) {+ offsets.push(pdf.length);+ pdf += object;+ }+ const xrefPosition = pdf.length;+ pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ for (const offset of offsets) {+ pdf += `${String(offset).padStart(10, "0")} 00000 n \n`;+ }+ pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefPosition}\n%%EOF\n`;+ return Buffer.from(pdf, "latin1");+}diff --git a/packages/pdfjs-viewer/package.json b/packages/pdfjs-viewer/package.jsonindex 1d3018e5bb..7514dc653e 100644--- a/packages/pdfjs-viewer/package.json+++ b/packages/pdfjs-viewer/package.json@@ -4,7 +4,9 @@"private": true,"scripts": {"build": "tsx scripts/build.ts",- "watch": "tsx scripts/build.ts --watch"+ "watch": "tsx scripts/build.ts --watch",+ "test": "vitest",+ "e2e": "playwright test"},"dependencies": {"@triliumnext/commons": "workspace:*"diff --git a/packages/pdfjs-viewer/playwright.config.ts b/packages/pdfjs-viewer/playwright.config.tsnew file mode 100644index 0000000000..8f2447d2b3--- /dev/null+++ b/packages/pdfjs-viewer/playwright.config.ts@@ -0,0 +1,33 @@+import { defineConfig, devices } from "@playwright/test";++const port = process.env.PDFJS_E2E_PORT ?? "8935";+const baseURL = `http://127.0.0.1:${port}`;++/**+ * E2E tests for the viewer itself, run against the built bundle served statically+ * together with a stub of the Trilium client (see e2e/harness). No Trilium server+ * is involved; the tests speak the same postMessage protocol as the client.+ */+export default defineConfig({+ testDir: "./e2e",+ outputDir: "./test-output/playwright",+ reporter: [["list"], ["html", { outputFolder: "./test-output/playwright-report", open: "never" }]],+ retries: process.env.CI ? 2 : 0,+ timeout: 60_000,+ use: {+ ...devices["Desktop Chrome"],+ viewport: { width: 1280, height: 900 },+ baseURL,+ trace: "on-first-retry",+ // Set PLAYWRIGHT_CHROME_CHANNEL=chrome to run against a system Chrome+ // instead of the Playwright-managed Chromium.+ channel: process.env.PLAYWRIGHT_CHROME_CHANNEL+ },+ webServer: {+ command: "pnpm build && node e2e/harness/serve.mjs",+ url: `${baseURL}/parent.html`,+ reuseExistingServer: !process.env.CI,+ env: { PDFJS_E2E_PORT: port },+ timeout: 120_000+ }+});diff --git a/packages/pdfjs-viewer/src/custom.ts b/packages/pdfjs-viewer/src/custom.tsindex d0dbc25cab..74298b1c10 100644--- a/packages/pdfjs-viewer/src/custom.ts+++ b/packages/pdfjs-viewer/src/custom.ts@@ -4,6 +4,7 @@ import { setupPdfPages } from "./pages";import { setupPdfAttachments } from "./attachments";import { setupPdfLayers } from "./layers";import { setupPdfAnnotations, setupAnnotationLiveUpdates, extractFromSavedData } from "./annotations";+import { commitPendingAnnotationEdits, isAnnotationEditingActive, setAnnotationEditorUIManager } from "./editing";async function main() {const urlParams = new URLSearchParams(window.location.search);@@ -33,6 +34,12 @@ async function main() {manageParentCommands();+ // Needed to commit in-progress annotation edits before saving; pdf.js recreates the+ // manager for each loaded document.+ app.eventBus.on("annotationeditoruimanager", ({ uiManager }) => {+ setAnnotationEditorUIManager(uiManager);+ });+app.eventBus.on("documentloaded", () => {setupPdfAnnotations();});@@ -110,6 +117,8 @@ function hideSidebar() {function manageSave() {const app = window.PDFViewerApplication;const storage = app.pdfDocument.annotationStorage;+ let pointerDown = false;+ let pointerDownOnPage = false;function onChange() {if (!storage) return;@@ -126,6 +135,9 @@ function manageSave() {if (event.data?.type === "trilium-request-blob") {const app = window.PDFViewerApplication;+ // An in-progress edit (e.g. an uncommitted ink drawing session) is not part of+ // annotationStorage yet and would be silently dropped by saveDocument().+ commitPendingAnnotationEdits(pointerDown);const data = await app.pdfDocument.saveDocument();window.parent.postMessage({type: "pdfjs-viewer-blob",@@ -153,6 +165,35 @@ function manageSave() {onChange();}});++ // While an annotation editing tool is active, most edits leave no observable trace:+ // only the first stroke of an ink drawing session flips hasSomethingToUndo — later+ // strokes accumulate in the uncommitted session without touching annotationStorage.+ // Treat the end of every pointer/keyboard interaction on a page as a potential+ // modification so the parent (re)schedules a save; a save without actual changes is+ // harmless. The pointer-down state also tells commitPendingAnnotationEdits() not to+ // commit while a stroke is still being drawn — the pointerup nudge below then+ // re-requests the save that had to skip the commit.+ const isOnPage = (event: Event) => event.target instanceof Element && !!event.target.closest(".page");+ window.addEventListener("pointerdown", (event) => {+ pointerDown = true;+ pointerDownOnPage = isOnPage(event);+ }, { capture: true });+ const onPointerEnd = (event: Event) => {+ pointerDown = false;+ // Strokes are tracked window-wide by pdf.js, so they can end outside the page —+ // what matters is where the interaction started.+ if ((pointerDownOnPage || isOnPage(event)) && isAnnotationEditingActive()) {+ onChange();+ }+ };+ window.addEventListener("pointerup", onPointerEnd, { capture: true });+ window.addEventListener("pointercancel", onPointerEnd, { capture: true });+ window.addEventListener("keyup", (event) => {+ if (isOnPage(event) && isAnnotationEditingActive()) {+ onChange();+ }+ }, { capture: true });}function manageParentCommands() {diff --git a/packages/pdfjs-viewer/src/editing.spec.ts b/packages/pdfjs-viewer/src/editing.spec.tsnew file mode 100644index 0000000000..963fc5d087--- /dev/null+++ b/packages/pdfjs-viewer/src/editing.spec.ts@@ -0,0 +1,96 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ ANNOTATION_EDITOR_MODE_NONE,+ AnnotationEditorUIManagerLike,+ commitPendingAnnotationEdits,+ getAnnotationEditorUIManager,+ isAnnotationEditingActive,+ setAnnotationEditorUIManager+} from "./editing";++const INK_MODE = 15; // AnnotationEditorType.INK++function buildManager(overrides: Partial<AnnotationEditorUIManagerLike> = {}): AnnotationEditorUIManagerLike {+ return {+ getMode: () => INK_MODE,+ getActive: () => null,+ unselectAll: vi.fn(),+ ...overrides+ };+}++afterEach(() => {+ setAnnotationEditorUIManager(null);+ vi.restoreAllMocks();+});++describe("commitPendingAnnotationEdits", () => {+ it("commits in-progress edits via unselectAll when an editing tool is active", () => {+ const manager = buildManager();+ commitPendingAnnotationEdits(false, manager);+ expect(manager.unselectAll).toHaveBeenCalledOnce();++ // Also commits when an editor is active but no longer being edited.+ const withIdleEditor = buildManager({ getActive: () => ({ isInEditMode: () => false }) });+ commitPendingAnnotationEdits(false, withIdleEditor);+ expect(withIdleEditor.unselectAll).toHaveBeenCalledOnce();+ });++ it("does nothing without a manager or outside of an editing mode", () => {+ expect(() => commitPendingAnnotationEdits(false, null)).not.toThrow();++ const manager = buildManager({ getMode: () => ANNOTATION_EDITOR_MODE_NONE });+ commitPendingAnnotationEdits(false, manager);+ expect(manager.unselectAll).not.toHaveBeenCalled();+ });++ it("skips the commit while the user is mid-interaction", () => {+ // A stroke is being drawn (pointer down).+ const whileDrawing = buildManager();+ commitPendingAnnotationEdits(true, whileDrawing);+ expect(whileDrawing.unselectAll).not.toHaveBeenCalled();++ // A free-text editor is focused.+ const whileTyping = buildManager({ getActive: () => ({ isInEditMode: () => true }) });+ commitPendingAnnotationEdits(false, whileTyping);+ expect(whileTyping.unselectAll).not.toHaveBeenCalled();+ });++ it("never lets a commit failure propagate into the save", () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const manager = buildManager({+ unselectAll: () => {+ throw new Error("pdf.js internal change");+ }+ });+ expect(() => commitPendingAnnotationEdits(false, manager)).not.toThrow();+ expect(warn).toHaveBeenCalledOnce();+ });+});++describe("isAnnotationEditingActive", () => {+ it("is true only when a manager exists and a tool is selected", () => {+ expect(isAnnotationEditingActive(null)).toBe(false);+ expect(isAnnotationEditingActive(buildManager({ getMode: () => ANNOTATION_EDITOR_MODE_NONE }))).toBe(false);+ expect(isAnnotationEditingActive(buildManager())).toBe(true);+ });+});++describe("getAnnotationEditorUIManager", () => {+ it("returns the captured manager, falling back to the viewer's layer properties", () => {+ const fallbackManager = buildManager();+ vi.stubGlobal("window", {+ PDFViewerApplication: {+ pdfViewer: { _layerProperties: { annotationEditorUIManager: fallbackManager } }+ }+ });++ expect(getAnnotationEditorUIManager()).toBe(fallbackManager);++ const capturedManager = buildManager();+ setAnnotationEditorUIManager(capturedManager);+ expect(getAnnotationEditorUIManager()).toBe(capturedManager);++ vi.unstubAllGlobals();+ });+});diff --git a/packages/pdfjs-viewer/src/editing.ts b/packages/pdfjs-viewer/src/editing.tsnew file mode 100644index 0000000000..bfce75a742--- /dev/null+++ b/packages/pdfjs-viewer/src/editing.ts@@ -0,0 +1,70 @@+/**+ * Glue around pdf.js' annotation *editing* state, used by the save flow in `custom.ts`.+ *+ * pdf.js keeps in-progress edits — an ink/highlight drawing session, or a free-text editor+ * that is still focused — outside of `annotationStorage` until they are committed, which+ * normally only happens on a mode switch, Escape or focus loss. `saveDocument()` serializes+ * `annotationStorage` only, so saving while such an edit is pending silently drops it. The+ * stock viewer does not hit this because its Ctrl+S keyboard handler commits first; Trilium's+ * postMessage-driven save has to commit explicitly.+ */++/** Matches `AnnotationEditorType.NONE` in pdf.js — no annotation editing tool is active. */+export const ANNOTATION_EDITOR_MODE_NONE = 0;++/** The subset of pdf.js' `AnnotationEditorUIManager` that the save flow relies on. */+export interface AnnotationEditorUIManagerLike {+ getMode(): number;+ getActive(): { isInEditMode(): boolean } | null;+ unselectAll(): void;+}++let currentUIManager: AnnotationEditorUIManagerLike | null = null;++/**+ * Stores the manager announced via the `annotationeditoruimanager` event bus event.+ * pdf.js recreates the manager for each loaded document.+ */+export function setAnnotationEditorUIManager(uiManager: AnnotationEditorUIManagerLike | null) {+ currentUIManager = uiManager;+}++export function getAnnotationEditorUIManager(): AnnotationEditorUIManagerLike | null {+ // Prefer the instance captured from the event bus, but fall back to the viewer's layer+ // properties in case the event fired before our listener was registered.+ return currentUIManager+ ?? (window.PDFViewerApplication?.pdfViewer as any)?._layerProperties?.annotationEditorUIManager+ ?? null;+}++/**+ * Whether an annotation editing tool (ink, highlight, free text, ...) is currently active.+ * While one is, edits can accumulate without any observable event — only the first stroke of+ * an ink drawing session flips `hasSomethingToUndo`; later strokes stay in the uncommitted+ * session without touching `annotationStorage` — so user interactions need to be treated as+ * potential modifications.+ */+export function isAnnotationEditingActive(uiManager: AnnotationEditorUIManagerLike | null = getAnnotationEditorUIManager()): boolean {+ return !!uiManager && uiManager.getMode() !== ANNOTATION_EDITOR_MODE_NONE;+}++/**+ * Commits pending annotation edits into `annotationStorage` so that a subsequent+ * `saveDocument()` includes them — unless the user is literally mid-interaction: committing+ * during an ink stroke would cut the stroke short, and committing a focused free-text editor+ * would steal the caret. Skipped edits are picked up by a later save, re-requested by the+ * interaction-end listeners in `manageSave()`.+ */+export function commitPendingAnnotationEdits(isPointerDown: boolean, uiManager: AnnotationEditorUIManagerLike | null = getAnnotationEditorUIManager()) {+ try {+ if (!uiManager || uiManager.getMode() === ANNOTATION_EDITOR_MODE_NONE) return;+ if (isPointerDown || uiManager.getActive()?.isInEditMode()) return;++ // unselectAll() commits the active editor and ends any in-progress drawing session —+ // the same code path pdf.js runs when Escape is pressed.+ uiManager.unselectAll();+ } catch (e) {+ // The commit is best-effort; never let it break the save itself.+ console.warn("Could not commit pending annotation edits:", e);+ }+}