Skip to content

Build your personal knowledge base with Trilium Notes

fix(print): end only the live print that a print job belongs to

Elian Doranaa421b8f4f62
diff --git a/apps/client/src/services/live_print.spec.ts b/apps/client/src/services/live_print.spec.ts
index ca50a160b1..bcb366da40 100644
--- a/apps/client/src/services/live_print.spec.ts
+++ b/apps/client/src/services/live_print.spec.ts
@@ -3,6 +3,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { buildNote } from "../test/easy-froca";
import { endLivePrint, getLivePrintTarget, printLiveInBrowser, startLivePrint } from "./live_print";
+/** The job of the last live print a test started, ended after each test. */
+let lastJobId: number | undefined;
+async function start(...args: Parameters<typeof startLivePrint>) {
+ lastJobId = await startLivePrint(...args);
+ return lastJobId;
+}
+
function addThemeLink(href: string, media?: string) {
const link = document.createElement("link");
link.rel = "stylesheet";
@@ -23,7 +30,8 @@ describe("live print", () => {
});
afterEach(() => {
- endLivePrint();
+ if (lastJobId !== undefined) endLivePrint(lastJobId);
+ lastJobId = undefined;
for (const link of document.head.querySelectorAll("link")) link.remove();
document.body.replaceChildren();
});
@@ -38,7 +46,7 @@ describe("live print", () => {
const target = document.createElement("div");
document.body.appendChild(target);
- await startLivePrint(note, target);
+ await start(note, target);
expect(document.body.classList.contains("print-live")).toBe(true);
expect(target.classList.contains("print-live-target")).toBe(true);
@@ -47,7 +55,7 @@ describe("live print", () => {
const printCss = [ ...document.head.querySelectorAll<HTMLLinkElement>("link[data-live-print-css]") ];
expect(printCss.map((link) => [ link.getAttribute("href"), link.media ])).toEqual([ [ "api/notes/live-css/download", "print" ] ]);
- endLivePrint();
+ endLivePrint(lastJobId ?? -1);
expect(document.body.classList.contains("print-live")).toBe(false);
expect(target.classList.contains("print-live-target")).toBe(false);
@@ -64,8 +72,8 @@ describe("live print", () => {
const second = document.createElement("div");
document.body.append(first, second);
- await startLivePrint(note, first);
- await startLivePrint(note, second);
+ await start(note, first);
+ await start(note, second);
expect(first.classList.contains("print-live-target")).toBe(false);
expect(second.classList.contains("print-live-target")).toBe(true);
@@ -80,16 +88,36 @@ describe("live print", () => {
<div class="clipped" style="overflow: hidden"></div>`;
document.body.appendChild(target);
- await startLivePrint(note, target);
+ await start(note, target);
expect(target.querySelector(".scroller")?.classList.contains("print-live-unscroll")).toBe(true);
expect(target.querySelector(".clipped")?.classList.contains("print-live-unscroll")).toBe(false);
- endLivePrint();
+ endLivePrint(lastJobId ?? -1);
expect(target.querySelector(".print-live-unscroll")).toBeNull();
});
+ it("ignores the end of a job that a newer live print replaced", async () => {
+ const note = buildNote({ id: "live-jobs", title: "Jobs", type: "render" });
+ const first = document.createElement("div");
+ const second = document.createElement("div");
+ document.body.append(first, second);
+
+ const firstJob = await start(note, first);
+ const secondJob = await start(note, second);
+ expect(secondJob).not.toBe(firstJob);
+
+ // A late `print-done` of the first job leaves the second one prepared.
+ endLivePrint(firstJob);
+ expect(document.body.classList.contains("print-live")).toBe(true);
+ expect(second.classList.contains("print-live-target")).toBe(true);
+
+ endLivePrint(secondJob);
+ expect(document.body.classList.contains("print-live")).toBe(false);
+ expect(second.classList.contains("print-live-target")).toBe(false);
+ });
+
it("prints through the browser dialog and restores the window afterwards", async () => {
const note = buildNote({ id: "live-browser", title: "Browser", type: "render" });
const target = document.createElement("div");
diff --git a/apps/client/src/services/live_print.ts b/apps/client/src/services/live_print.ts
index 8140127b25..0dde18bd58 100644
--- a/apps/client/src/services/live_print.ts
+++ b/apps/client/src/services/live_print.ts
@@ -17,6 +17,8 @@ const PRINT_CSS_ATTR = "data-live-print-css";
const UNSCROLL_CLASS = "print-live-unscroll";
let activeTarget: HTMLElement | undefined;
+/** Identifies the live print {@link activeTarget} belongs to; each {@link startLivePrint} gets a new one. */
+let activeJobId = 0;
/**
* Returns the element of `noteDetail` that a live print prints when it shows the type widget
@@ -28,9 +30,13 @@ export function getLivePrintTarget(noteDetail: HTMLElement | null, shownType: st
return noteDetail?.querySelector<HTMLElement>(".note-detail-render-content") ?? undefined;
}
-/** Prepares the window to print `target`, ending any live print still active. */
+/**
+ * Prepares the window to print `target`, ending any live print still active. Returns the ID of the
+ * new live print, which {@link endLivePrint} takes.
+ */
export async function startLivePrint(note: FNote, target: HTMLElement) {
- endLivePrint();
+ endLivePrint(activeJobId);
+ const jobId = ++activeJobId;
activeTarget = target;
document.body.classList.add(ACTIVE_CLASS);
target.classList.add(TARGET_CLASS);
@@ -50,11 +56,15 @@ export async function startLivePrint(note: FNote, target: HTMLElement) {
await loadPrintCss(note);
await document.fonts.ready;
+ return jobId;
}
-/** Restores the window after a live print. Does nothing when none is active. */
-export function endLivePrint() {
- if (!activeTarget) return;
+/**
+ * Restores the window after the live print `jobId`. Does nothing when that live print is no longer
+ * active, so the late end of a job does not undo the live print that replaced it.
+ */
+export function endLivePrint(jobId: number) {
+ if (!activeTarget || jobId !== activeJobId) return;
activeTarget.classList.remove(TARGET_CLASS);
for (const el of activeTarget.querySelectorAll(`.${UNSCROLL_CLASS}`)) {
@@ -75,8 +85,8 @@ export function endLivePrint() {
/** Prints `target` through the browser's own print dialog. */
export async function printLiveInBrowser(note: FNote, target: HTMLElement) {
- await startLivePrint(note, target);
- window.addEventListener("afterprint", endLivePrint, { once: true });
+ const jobId = await startLivePrint(note, target);
+ window.addEventListener("afterprint", () => endLivePrint(jobId), { once: true });
window.print();
}
diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsx
index afa2355484..31c706a0c9 100644
--- a/apps/client/src/widgets/NoteDetail.tsx
+++ b/apps/client/src/widgets/NoteDetail.tsx
@@ -152,8 +152,8 @@ export default function NoteDetail() {
const api = window.electronApi?.printing;
if (!api) return;
api.onPrintProgress(({ progress, action }) => showToast(action as "printing" | "exporting_pdf", progress));
- api.onPrintDone((printReport) => {
- endLivePrint();
+ api.onPrintDone((printReport, liveJobId) => {
+ if (liveJobId !== undefined) endLivePrint(liveJobId);
toast.closePersistent("printing");
handlePrintReport(printReport as PrintReport);
});
diff --git a/apps/client/src/widgets/dialogs/print_preview.spec.tsx b/apps/client/src/widgets/dialogs/print_preview.spec.tsx
index 5e0401a185..6a621250a0 100644
--- a/apps/client/src/widgets/dialogs/print_preview.spec.tsx
+++ b/apps/client/src/widgets/dialogs/print_preview.spec.tsx
@@ -49,7 +49,6 @@ describe("PrintPreviewDialog", () => {
});
afterEach(() => {
- endLivePrint();
delete (window as any).electronApi;
});
@@ -118,7 +117,7 @@ describe("PrintPreviewDialog", () => {
// Closing without printing restores the window.
const cancelled = await show();
expect(cancelled.classList.contains("print-live-target")).toBe(true);
- expect(printing.exportAsPdfPreview).toHaveBeenCalledWith(expect.objectContaining({ live: true }));
+ expect(printing.exportAsPdfPreview).toHaveBeenCalledWith(expect.objectContaining({ liveJobId: expect.any(Number) }));
close();
await vi.waitFor(() => expect(cancelled.classList.contains("print-live-target")).toBe(false));
@@ -129,8 +128,13 @@ describe("PrintPreviewDialog", () => {
const systemPrint = document.querySelector<HTMLAnchorElement>(".print-preview-dialog .modal-footer a");
expect(systemPrint).toBeTruthy();
act(() => systemPrint?.click());
- expect(printing.printFromPreview).toHaveBeenCalledWith(expect.objectContaining({ live: true, silent: false }));
+ expect(printing.printFromPreview).toHaveBeenCalledWith(expect.objectContaining({ liveJobId: expect.any(Number), silent: false }));
await vi.waitFor(() => expect(document.querySelector(".print-preview-dialog.show")).toBeNull());
expect(printed.classList.contains("print-live-target")).toBe(true);
+
+ // The main process echoes the job with `print-done`, which ends exactly this live print.
+ const { liveJobId } = printing.printFromPreview.mock.calls[0]?.[0] as { liveJobId: number };
+ endLivePrint(liveJobId);
+ expect(printed.classList.contains("print-live-target")).toBe(false);
});
});
diff --git a/apps/client/src/widgets/dialogs/print_preview.tsx b/apps/client/src/widgets/dialogs/print_preview.tsx
index 57d109563e..2ca287555a 100644
--- a/apps/client/src/widgets/dialogs/print_preview.tsx
+++ b/apps/client/src/widgets/dialogs/print_preview.tsx
@@ -105,7 +105,8 @@ export default function PrintPreviewDialog() {
const notePathRef = useRef("");
const pdfUrlRef = useRef<string | undefined>(undefined);
const requestIdRef = useRef(0);
- const isLiveRef = useRef(false);
+ /** The live print the dialog started for a live target, which every request names. */
+ const liveJobIdRef = useRef<number | undefined>(undefined);
/** A live print sent to the printer keeps the window prepared until `print-done` ends it. */
const isLivePrintSentRef = useRef(false);
@@ -153,11 +154,8 @@ export default function PrintPreviewDialog() {
useTriliumEvent("showPrintPreview", async (data: PrintPreviewData) => {
if (shown) return;
- isLiveRef.current = !!data.liveTarget;
isLivePrintSentRef.current = false;
- if (data.liveTarget) {
- await startLivePrint(data.note, data.liveTarget);
- }
+ liveJobIdRef.current = data.liveTarget ? await startLivePrint(data.note, data.liveTarget) : undefined;
setNote(data.note);
notePathRef.current = data.notePath;
@@ -204,7 +202,7 @@ export default function PrintPreviewDialog() {
api.exportAsPdfPreview({
requestId: ++requestIdRef.current,
notePath: notePathRef.current,
- live: isLiveRef.current,
+ liveJobId: liveJobIdRef.current,
pageSize: opts.pageSize,
landscape: opts.landscape,
scale: opts.scale,
@@ -228,10 +226,10 @@ export default function PrintPreviewDialog() {
}, [shown, landscape, pageSize, scale, marginsStr, pageRanges, pageRangesValid, regeneratePreview]);
function handleClose() {
- if (isLiveRef.current && !isLivePrintSentRef.current) {
- endLivePrint();
+ if (liveJobIdRef.current !== undefined && !isLivePrintSentRef.current) {
+ endLivePrint(liveJobIdRef.current);
}
- isLiveRef.current = false;
+ liveJobIdRef.current = undefined;
requestIdRef.current++;
setShown(false);
isFirstGenerationRef.current = true;
@@ -256,10 +254,10 @@ export default function PrintPreviewDialog() {
}
function handlePrint(silent: boolean, deviceName?: string) {
- isLivePrintSentRef.current = isLiveRef.current;
+ isLivePrintSentRef.current = liveJobIdRef.current !== undefined;
window.electronApi?.printing.printFromPreview({
notePath: notePathRef.current,
- live: isLiveRef.current,
+ liveJobId: liveJobIdRef.current,
pageSize,
landscape,
scale,
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index bc4ab19c69..d8f20e74fa 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -435,7 +435,9 @@ describe("preload script", () => {
const listeners = ipcRendererListeners.get("print-done")!;
expect(listeners).toHaveLength(1);
listeners[0]({}, { success: true });
- expect(callback).toHaveBeenCalledWith({ success: true });
+ expect(callback).toHaveBeenCalledWith({ success: true }, undefined);
+ listeners[0]({}, { type: "single-note" }, 3);
+ expect(callback).toHaveBeenLastCalledWith({ type: "single-note" }, 3);
});
it("removePrintListeners clears both print listeners", () => {
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 64d2bfcc7b..73cc4144e0 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -188,8 +188,8 @@ contextBridge.exposeInMainWorld("electronApi", {
onPrintProgress(callback: (data: { progress: number; action: string }) => void) {
ipcRenderer.on("print-progress", (_event, data) => callback(data));
},
- onPrintDone(callback: (printReport: unknown) => void) {
- ipcRenderer.on("print-done", (_event, printReport) => callback(printReport));
+ onPrintDone(callback: (printReport: unknown, liveJobId?: number) => void) {
+ ipcRenderer.on("print-done", (_event, printReport, liveJobId) => callback(printReport, liveJobId));
},
removePrintListeners() {
ipcRenderer.removeAllListeners("print-progress");
diff --git a/apps/desktop/src/services/printing.spec.ts b/apps/desktop/src/services/printing.spec.ts
index 8022d3f375..7c74b784f8 100644
--- a/apps/desktop/src/services/printing.spec.ts
+++ b/apps/desktop/src/services/printing.spec.ts
@@ -477,7 +477,7 @@ describe("setupPrintingHandlers", () => {
printToPDF: vi.fn(async () => Buffer.from("live-pdf")),
print: vi.fn((_opts: unknown, cb: (success: boolean) => void) => cb(true))
};
- await fn({ sender }, { ...payload, live: true });
+ await fn({ sender }, { ...payload, liveJobId: 3 });
return sender;
}
@@ -498,7 +498,7 @@ describe("setupPrintingHandlers", () => {
expect(h.loadURL).not.toHaveBeenCalled();
expect(h.print).not.toHaveBeenCalled();
expect(sender.print).toHaveBeenCalledWith(expect.objectContaining({ silent: true, deviceName: "HP" }), expect.any(Function));
- expect(sender.send).toHaveBeenCalledWith("print-done", { type: "single-note" });
+ expect(sender.send).toHaveBeenCalledWith("print-done", { type: "single-note" }, 3);
expect(h.destroy).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.ts
index 44ea427ab6..52c09d8f63 100644
--- a/apps/desktop/src/services/printing.ts
+++ b/apps/desktop/src/services/printing.ts
@@ -41,8 +41,11 @@ interface PrintOpts {
interface ExportAsPdfOpts {
notePath: string;
- /** Prints the sender's own window, which the renderer prepared for printing, instead of `notePath`. */
- live?: boolean;
+ /**
+ * Prints the sender's own window, which the renderer prepared for printing as this live print,
+ * instead of `notePath`. `print-done` echoes it so the renderer restores only that live print.
+ */
+ liveJobId?: number;
title: string;
landscape: boolean;
pageSize: "A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "A6" | "Legal" | "Letter" | "Tabloid" | "Ledger";
@@ -334,7 +337,8 @@ export function setupPrintingHandlers() {
}
});
- electron.ipcMain.on("export-as-pdf-preview", async (e, { notePath, live, requestId, landscape, pageSize, scale, margins, pageRanges }: PreviewOpts) => {
+ electron.ipcMain.on("export-as-pdf-preview", async (e, { notePath, liveJobId, requestId, landscape, pageSize, scale, margins, pageRanges }: PreviewOpts) => {
+ const live = typeof liveJobId === "number";
try {
const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "exporting_pdf", live);
@@ -416,7 +420,8 @@ export function setupPrintingHandlers() {
}
});
- electron.ipcMain.on("print-from-preview", async (e, { notePath, live, landscape, pageSize, scale, margins, pageRanges, silent, deviceName }: PrintFromPreviewOpts) => {
+ electron.ipcMain.on("print-from-preview", async (e, { notePath, liveJobId, landscape, pageSize, scale, margins, pageRanges, silent, deviceName }: PrintFromPreviewOpts) => {
+ const live = typeof liveJobId === "number";
try {
const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "printing", live);
@@ -441,16 +446,25 @@ export function setupPrintingHandlers() {
}
e.sender.send("print-from-preview-done");
// Also sent for a live print: it is what restores the sender's window.
- e.sender.send("print-done", printReport ?? { type: "single-note" });
+ sendPrintDone(e, printReport ?? { type: "single-note" }, live ? liveJobId : undefined);
dispose();
});
} catch (err) {
e.sender.send("print-from-preview-done");
- e.sender.send("print-done", {
+ sendPrintDone(e, {
type: "error",
message: err instanceof Error ? err.message : String(err),
stack: err instanceof Error ? err.stack : undefined
- });
+ }, live ? liveJobId : undefined);
}
});
}
+
+/** Sends `print-done`, naming the live print it ends, if any, so the renderer restores only that one. */
+function sendPrintDone(e: IpcMainEvent, printReport: unknown, liveJobId: number | undefined) {
+ if (liveJobId === undefined) {
+ e.sender.send("print-done", printReport);
+ } else {
+ e.sender.send("print-done", printReport, liveJobId);
+ }
+}
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 950c67cb09..9b90d6f744 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -402,8 +402,11 @@ export interface ElectronPrintingApi {
*/
onPrintProgress(callback: (data: { progress: number; action: string }) => void): void;
- /** Subscribes to the "print finished" event, fired once the OS print job is dispatched. */
- onPrintDone(callback: (printReport: unknown) => void): void;
+ /**
+ * Subscribes to the "print finished" event, fired once the OS print job is dispatched.
+ * `liveJobId` names the live print the job ended, for a job that printed the app window itself.
+ */
+ onPrintDone(callback: (printReport: unknown, liveJobId?: number) => void): void;
/** Removes all listeners registered via {@link onPrintProgress} and {@link onPrintDone}. */
removePrintListeners(): void;