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(print): print saved searches in the browser
Elian Doranfd7a04fe4c12
diff --git a/apps/client/src/print.spec.tsx b/apps/client/src/print.spec.tsxindex de06025004..0ebf01ebed 100644--- a/apps/client/src/print.spec.tsx+++ b/apps/client/src/print.spec.tsx@@ -138,6 +138,18 @@ describe("App", () => {expect(readyListener).toHaveBeenCalledTimes(1);window.removeEventListener("note-ready", readyListener);});++ it("renders CollectionRenderer for a search note, whose results print as a list", async () => {+ const loadSearchNote = vi.spyOn(froca, "loadSearchNote").mockResolvedValue(undefined);+ buildNote({ id: "root", title: "root", children: [{ id: "app-search", title: "Search", type: "search" }] });+ const note = await froca.getNote("app-search");+ const container = renderInto(<App note={note} noteId="app-search" />);++ await vi.waitFor(() => expect(container.textContent).toContain("NOTELIST"));+ expect(loadSearchNote).toHaveBeenCalledWith("app-search");+ expect(document.body.dataset.noteType).toBe("search");+ loadSearchNote.mockRestore();+ });});describe("SingleNoteRenderer", () => {diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsxindex 041e83984b..8515918a56 100644--- a/apps/client/src/print.tsx+++ b/apps/client/src/print.tsx@@ -1,5 +1,5 @@import { render } from "preact";-import { useCallback, useLayoutEffect, useRef } from "preact/hooks";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";import Component from "./components/component";import FNote from "./entities/fnote";@@ -29,6 +29,7 @@ export type PrintReport = {export async function main() {const notePath = window.location.hash.substring(1);const noteId = notePath.split("/").at(-1);+ console.debug("[print] Rendering the print page for", notePath || "(no note path)");if (!noteId) return;await import("./print.css");@@ -48,12 +49,17 @@ export async function main() {document.head.appendChild(fontLink);const note = await froca.getNote(noteId);+ console.debug("[print] Note loaded:", noteId, note?.type);// printToPDF() and the browser print dialog name the document after document.title.if (note?.title) {document.title = note.title;}+ if (!note) {+ reportPrintError(new Error(`The note to print (${noteId}) could not be loaded.`));+ }+const bodyWrapper = document.createElement("div");render(<App note={note} noteId={noteId} />, bodyWrapper);document.body.appendChild(bodyWrapper);@@ -89,7 +95,7 @@ export function App({ note, noteId }: { note: FNote | null | undefined, noteId:return (<>- {note.type === "book"+ {note.type === "book" || note.type === "search"? <CollectionRenderer {...props} />: <SingleNoteRenderer {...props} />}@@ -159,7 +165,14 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {load().then(() => requestAnimationFrame(() => onReady({type: "single-note"- })));+ }))).catch((error: unknown) => {+ console.error("[print] Rendering the note failed:", error);+ onReady({+ type: "error",+ message: error instanceof Error ? error.message : String(error),+ stack: error instanceof Error ? error.stack : undefined+ });+ });}, [ note ]);return <>@@ -170,6 +183,29 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {export function CollectionRenderer({ note, onReady, onProgressChanged }: RendererProps) {const viewType = useNoteViewType(note);+ // A saved search holds its results as virtual children only once it has run server-side.+ const [ ready, setReady ] = useState(note.type !== "search");++ useEffect(() => {+ if (note.type !== "search") {+ return;+ }++ let cancelled = false;+ console.debug("[print] Running the saved search…");+ void froca.loadSearchNote(note.noteId)+ .catch((e: unknown) => console.warn("[print] Unable to run the saved search being printed:", e))+ .finally(() => {+ console.debug("[print] The saved search run finished.");+ if (!cancelled) setReady(true);+ });+ return () => {+ cancelled = true;+ };+ }, [ note ]);++ if (!ready) return null;+return <CustomNoteListviewType={viewType}isEnabled@@ -222,4 +258,20 @@ export async function loadCustomCss(note: FNote) {}/** index.ts holds the splash up until the note has rendered. */-export const ready = main();+window.addEventListener("error", (e) => console.error("[print] Uncaught error in the print page:", e.error ?? e.message));+window.addEventListener("unhandledrejection", (e) => console.error("[print] Unhandled rejection in the print page:", e.reason));++export const ready = main().catch((error: unknown) => {+ console.error("[print] The print page failed to render:", error);+ reportPrintError(error);+});++/**+ * Tells the window that opened the print page that it should not wait for a render any longer, so a+ * failure shows as the print report rather than as a print that never starts.+ */+function reportPrintError(error: unknown) {+ const message = error instanceof Error ? error.message : String(error);+ const stack = error instanceof Error ? error.stack : undefined;+ window.dispatchEvent(new CustomEvent("note-ready", { detail: { type: "error", message, stack } }));+}diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 23e826b362..2d87dc544d 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -201,30 +201,50 @@ export default function NoteDetail() {}// Browser fallback: render the print page in a hidden iframe and use window.print().+ console.debug("[print] Opening the print page for", noteContext.notePath);showToast("printing");const iframe = document.createElement('iframe');iframe.src = `?print#${noteContext.notePath}`;iframe.className = "print-iframe";document.body.appendChild(iframe);iframe.onload = () => {- if (!iframe.contentWindow) {+ const printWindow = iframe.contentWindow;+ console.debug("[print] The print page loaded", printWindow ? "" : "without a window");+ if (!printWindow) {toast.closePersistent("printing");document.body.removeChild(iframe);return;}- iframe.contentWindow.addEventListener("note-load-progress", (e) => {- showToast("printing", e.detail.progress);+ printWindow.addEventListener("error", (e) => {+ console.error("[print] Uncaught error in the print page:", e.error ?? e.message);+ });+ printWindow.addEventListener("unhandledrejection", (e) => {+ console.error("[print] Unhandled rejection in the print page:", e.reason);+ });++ // A print page that never reports leaves the toast up and prints nothing.+ const watchdog = setTimeout(() => console.warn(+ "[print] The print page has not reported ready; it may have failed to render.",+ { src: iframe.src, noteType: printWindow.document.body.dataset.noteType }+ ), 20_000);++ printWindow.addEventListener("note-load-progress", (e) => {+ console.debug("[print] Progress:", (e as CustomEvent<{ progress: number }>).detail.progress);+ showToast("printing", (e as CustomEvent<{ progress: number }>).detail.progress);});- iframe.contentWindow.addEventListener("note-ready", (e) => {+ printWindow.addEventListener("note-ready", (e) => {+ clearTimeout(watchdog);toast.closePersistent("printing");- if ("detail" in e) {- handlePrintReport(e.detail as PrintReport);- }+ const report = "detail" in e ? e.detail as PrintReport : undefined;+ console.debug("[print] The print page is ready:", report);+ handlePrintReport(report);- iframe.contentWindow?.print();+ if (report?.type !== "error") {+ printWindow.print();+ }document.body.removeChild(iframe);});};diff --git a/apps/client/src/widgets/collections/NoteList.spec.tsx b/apps/client/src/widgets/collections/NoteList.spec.tsxindex 9f305b65c1..b5fc79a193 100644--- a/apps/client/src/widgets/collections/NoteList.spec.tsx+++ b/apps/client/src/widgets/collections/NoteList.spec.tsx@@ -21,7 +21,7 @@ import LoadResults from "../../services/load_results";import { buildNote, buildNotes } from "../../test/easy-froca";import { ParentComponent } from "../react/react_utils";import type { ViewTypeOptions } from "./interface";-import { CustomNoteList, useNoteIds, useViewModeConfig } from "./NoteList";+import { CustomNoteList, shouldRenderNoteList, useNoteIds, useViewModeConfig } from "./NoteList";const wsHandlers = vi.hoisted(() => new Set<(message: unknown) => void>());vi.mock("../../services/ws", () => {@@ -67,6 +67,22 @@ function branchEntitiesReloaded(parentNoteId: string, childNoteId: string) {return loadResults;}+describe("shouldRenderNoteList", () => {+ const searchNote = buildNote({ title: "Search", type: "search" });++ it("draws a saved search's results for the printer, though nothing on screen scrolled to them", () => {+ expect(shouldRenderNoteList(searchNote, "searchPreview", false, "screen")).toBe(false);+ expect(shouldRenderNoteList(searchNote, "searchPreview", false, "print")).toBe(true);+ expect(shouldRenderNoteList(searchNote, "searchPreview", true, "screen")).toBe(true);+ });++ it("draws a book and a full-height view without waiting to be scrolled to", () => {+ const book = buildNote({ title: "Book", type: "book" });+ expect(shouldRenderNoteList(book, "list", false, "screen")).toBe(true);+ expect(shouldRenderNoteList(searchNote, "calendar", false, "screen")).toBe(true);+ });+});+describe("useNoteIds refresh race", () => {let container: HTMLElement | undefined;diff --git a/apps/client/src/widgets/collections/NoteList.tsx b/apps/client/src/widgets/collections/NoteList.tsxindex 85a197c5e8..77a9cfd679 100644--- a/apps/client/src/widgets/collections/NoteList.tsx+++ b/apps/client/src/widgets/collections/NoteList.tsx@@ -95,12 +95,12 @@ export function EmbeddedNoteList(props: Omit<NoteListProps, "isEnabled" | "viewTreturn <CustomNoteList {...props} isEnabled={true} viewType={viewType} />;}-export function CustomNoteList({ note, viewType, isEnabled: shouldEnable, contentReady = true, notePath, highlightedTokens, displayOnlyCollections, ntxId, onReady, onProgressChanged, ...restProps }: NoteListProps) {+export function CustomNoteList({ note, viewType, isEnabled: shouldEnable, contentReady = true, notePath, highlightedTokens, displayOnlyCollections, ntxId, onReady, onProgressChanged, media, ...restProps }: NoteListProps) {const widgetRef = useRef<HTMLDivElement>(null);const noteIds = useNoteIds(shouldEnable ? note : null, viewType, ntxId);const isFullHeight = (viewType && viewType !== "list" && viewType !== "grid" && viewType !== "searchPreview");const [ isIntersecting, setIsIntersecting ] = useState(false);- const shouldRender = (isFullHeight || isIntersecting || note?.type === "book");+ const shouldRender = shouldRenderNoteList(note, viewType, isIntersecting, media);const isEnabled = (note && shouldEnable && !!viewType && shouldRender);useEffect(() => {@@ -148,6 +148,7 @@ export function CustomNoteList({ note, viewType, isEnabled: shouldEnable, contenprops = {note, noteIds, notePath, ntxId,highlightedTokens,+ media,viewConfig: viewModeConfig.config,saveConfig: viewModeConfig.storeFn,onReady: onReady ?? (() => {}),@@ -181,6 +182,21 @@ export function useNoteViewType(note?: FNote | null): ViewTypeOptions | undefinereturn resolveViewType(note, viewType);}+/**+ * Whether a view is drawn yet. A full-height view, or a book's, is drawn at once; a list waits until+ * it scrolls into view. A print page has nothing on screen to scroll into, so it draws its results+ * for the paper.+ */+export function shouldRenderNoteList(+ note: FNote | null | undefined,+ viewType: ViewTypeOptions | undefined,+ isIntersecting: boolean,+ media: ViewModeMedia+) {+ const isFullHeight = viewType && viewType !== "list" && viewType !== "grid" && viewType !== "searchPreview";+ return !!(isFullHeight || isIntersecting || note?.type === "book" || media === "print");+}+export function useNoteIds(note: FNote | null | undefined, viewType: ViewTypeOptions | undefined, ntxId: string | null | undefined) {const [ noteIds, setNoteIds ] = useState<string[]>([]);const [ includeArchived ] = useNoteLabelBoolean(note, "includeArchived");diff --git a/apps/client/src/widgets/layout/NoteActions.spec.tsx b/apps/client/src/widgets/layout/NoteActions.spec.tsxindex 5422b3473b..6ff333725f 100644--- a/apps/client/src/widgets/layout/NoteActions.spec.tsx+++ b/apps/client/src/widgets/layout/NoteActions.spec.tsx@@ -170,7 +170,7 @@ describe("NoteContextMenu", () => {expect(await hasPropertiesItem("board", { "#readOnly": "" })).toBe(true);});- it("offers to print a render note only while it has a render target", async () => {+ it("offers to print the note types and views that have a print renderer", async () => {const isPrintEnabled = async (note: FNote) => {const noteContext = new NoteContext("ntx-render");noteContext.noteId = note.noteId;@@ -197,6 +197,10 @@ describe("NoteContextMenu", () => {expect(await isPrintEnabled(buildNote({ title: "Render", type: "render", "~renderNote": script.noteId }))).toBe(true);expect(await isPrintEnabled(buildNote({ title: "Unset", type: "render" }))).toBe(false);expect(await isPrintEnabled(buildNote({ title: "Disabled", type: "render", "~disabled:renderNote": script.noteId }))).toBe(false);++ expect(await isPrintEnabled(buildNote({ title: "Search", type: "search" }))).toBe(true);+ expect(await isPrintEnabled(buildNote({ title: "Search list", type: "search", "#viewType": "list" }))).toBe(true);+ expect(await isPrintEnabled(buildNote({ title: "Search grid", type: "search", "#viewType": "grid" }))).toBe(false);});it("draws the actions that look into the note as a strip of tiles, or a row where one is left", async () => {diff --git a/apps/client/src/widgets/layout/NoteActions.tsx b/apps/client/src/widgets/layout/NoteActions.tsxindex 4788f67dae..398ebf66bf 100644--- a/apps/client/src/widgets/layout/NoteActions.tsx+++ b/apps/client/src/widgets/layout/NoteActions.tsx@@ -20,6 +20,7 @@ import ws from "../../services/ws";import ClosePaneButton from "../buttons/close_pane_button";import CreatePaneButton from "../buttons/create_pane_button";import MovePaneButton from "../buttons/move_pane_button";+import { resolveViewType } from "../collections/interface";import { showImageCompressionDialog } from "../dialogs/image_compression/image_compression_dialog";import { isAlwaysFullWidthByType } from "../note_wrapper";import Dropdown, { type DropdownHandle } from "../react/Dropdown";@@ -86,6 +87,7 @@ export function NoteContextMenu({ note, noteContext, leadingViewActions = [], tr["text", "code", "spreadsheet", "llmChat"].includes(noteType) ||(noteType === "render" && !!renderNote) ||(noteType === "book" && ["presentation", "list", "table"].includes(viewType ?? "")) ||+ (noteType === "search" && ["list", "searchPreview"].includes(resolveViewType(note, viewType) ?? "")) ||(noteType === "file" && note.mime === "application/pdf"));const isElectron = getIsElectron();