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
client/AI chat: add printing support
Adorian Dorane9f591f19467
diff --git a/apps/client/src/print.css b/apps/client/src/print.cssindex e9a0a8eddd..d6541ebc23 100644--- a/apps/client/src/print.css+++ b/apps/client/src/print.css@@ -249,6 +249,30 @@ span[style] {}/* #endregion */+/* #region AI chat */+body[data-note-type="llmChat"] {+ font-size: var(--print-font-size);+}++body[data-note-type="llmChat"] .llm-chat-message-wrapper {+ contain: none !important;+}++body[data-note-type="llmChat"] .llm-chat-message-user {+ background: #f0f0f0;+ border: 0.5pt solid #ccc;+ print-color-adjust: exact;+ -webkit-print-color-adjust: exact;+}++body[data-note-type="llmChat"] .llm-chat-footer {+ /* The timestamp/usage footer is revealed on hover on screen; on paper there is no hover, and a+ transcript wants its timestamps. */+ opacity: 1;+ color: #666;+}+/* #endregion */+/* #region Page breaks */.page-break {page-break-after: always;diff --git a/apps/client/src/print.tsx b/apps/client/src/print.tsxindex 8a3409fac9..fb91f8990f 100644--- a/apps/client/src/print.tsx+++ b/apps/client/src/print.tsx@@ -5,6 +5,7 @@ import FNote from "./entities/fnote";import content_renderer from "./services/content_renderer";import { applyInlineMermaid } from "./services/content_renderer_text";import froca from "./services/froca";+import { waitForPendingRenders } from "./services/pending_renders";import { isElectron } from "./services/utils";import { CustomNoteList, useNoteViewType } from "./widgets/collections/NoteList";@@ -114,6 +115,12 @@ export function SingleNoteRenderer({ note, onReady }: RendererProps) {const { $renderedContent } = await content_renderer.getRenderedContent(note, { noChildrenList: true, expandNestedIncludes: true });container.replaceChildren(...$renderedContent);+ // Note types rendered as a mounted component (an AI chat) start their transform+ // passes — mermaid, syntax highlighting, included notes — in a layout effect that+ // getRenderedContent does not await. Printing snapshots the page, so wait for those+ // to settle first; otherwise they land after the capture and are missing from the PDF.+ await waitForPendingRenders();+// Wait for all images to load.const images = Array.from(container.querySelectorAll("img"));await Promise.all(diff --git a/apps/client/src/services/pending_renders.spec.ts b/apps/client/src/services/pending_renders.spec.tsnew file mode 100644index 0000000000..9ae3a9c189--- /dev/null+++ b/apps/client/src/services/pending_renders.spec.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";++import { trackPendingRender, waitForPendingRenders } from "./pending_renders.js";++function deferred() {+ let resolve: () => void = () => {};+ let reject: (e: unknown) => void = () => {};+ const promise = new Promise<void>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++/** Lets every already-queued microtask (and the promise chains they queue) run to completion. */+function flushMicrotasks() {+ return new Promise<void>((resolve) => setTimeout(resolve, 0));+}++/** Whether `waitForPendingRenders()` has resolved, without blocking on it. */+function watchCompletion() {+ const state = { done: false };+ void waitForPendingRenders().then(() => {+ state.done = true;+ });+ return state;+}++describe("pending renders", () => {+ it("resolves immediately when nothing is tracked", async () => {+ await expect(waitForPendingRenders()).resolves.toBeUndefined();+ });++ it("waits for tracked work, including work scheduled by tracked work", async () => {+ const first = deferred();+ const second = deferred();+ trackPendingRender(first.promise);++ const completion = watchCompletion();+ await Promise.resolve();+ expect(completion.done).toBe(false);++ // An included note renders its own content: work that only gets tracked once the first+ // pass has finished must still be waited for.+ first.resolve();+ trackPendingRender(second.promise);+ await Promise.resolve();+ expect(completion.done).toBe(false);++ second.resolve();+ await flushMicrotasks();+ expect(completion.done).toBe(true);+ });++ it("does not stall or reject when tracked work fails", async () => {+ const failing = deferred();+ trackPendingRender(failing.promise);++ failing.reject(new Error("mermaid blew up"));++ await expect(waitForPendingRenders()).resolves.toBeUndefined();+ });+});diff --git a/apps/client/src/services/pending_renders.ts b/apps/client/src/services/pending_renders.tsnew file mode 100644index 0000000000..6a840e60d7--- /dev/null+++ b/apps/client/src/services/pending_renders.ts@@ -0,0 +1,33 @@+/**+ * Tracks the asynchronous tail of content rendering.+ *+ * Most render paths are awaitable: `content_renderer.getRenderedContent()` returns once the note's+ * content is in the DOM. Components are not — a widget that renders HTML kicks off its transform+ * passes (mermaid, KaTeX, syntax highlighting, included notes, all of which lazily import their+ * library) from a layout effect and never awaits them, because on screen they simply paint when they+ * are ready.+ *+ * That breaks any caller that snapshots the finished DOM instead of watching it: printing / PDF+ * export captures the page once, so a transform that lands after the capture is silently missing from+ * the output. Such a caller awaits {@link waitForPendingRenders} to get a settled DOM.+ */+const pending = new Set<Promise<unknown>>();++/** Registers async render work, so that {@link waitForPendingRenders} waits for it. */+export function trackPendingRender(work: Promise<unknown>) {+ // Failures are the tracked work's own business: a transform that throws still finishes, and a+ // caller waiting for a settled DOM should proceed rather than inherit the rejection.+ const tracked = work.catch(() => undefined);+ pending.add(tracked);+ void tracked.then(() => pending.delete(tracked));+}++/**+ * Resolves once all tracked render work has settled, including work that other work scheduled (an+ * included note renders its own content, which highlights its own code blocks, …).+ */+export async function waitForPendingRenders() {+ while (pending.size > 0) {+ await Promise.all([...pending]);+ }+}diff --git a/apps/client/src/widgets/ribbon/NoteActions.tsx b/apps/client/src/widgets/ribbon/NoteActions.tsxindex 1ed77356c4..9f57919be8 100644--- a/apps/client/src/widgets/ribbon/NoteActions.tsx+++ b/apps/client/src/widgets/ribbon/NoteActions.tsx@@ -88,7 +88,7 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNoteconst isExportableToXlsx = noteType === "spreadsheet";const isContentAvailable = note.isContentAvailable();const isPrintable = isContentAvailable && (- ["text", "code", "spreadsheet"].includes(noteType) ||+ ["text", "code", "spreadsheet", "llmChat"].includes(noteType) ||(noteType === "book" && ["presentation", "list", "table"].includes(viewType ?? "")) ||(noteType === "file" && note.mime === "application/pdf"));diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsxindex 68d5d04761..3871b0334a 100644--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.tsx@@ -14,6 +14,7 @@ import { applyInlineMermaid, rewriteMermaidDiagramsInContainer } from "../../../import { getLocaleById } from "../../../services/i18n";import { applyLinkEmbeds } from "../../../services/link_embed";import { renderMathInElement } from "../../../services/math";+import { trackPendingRender } from "../../../services/pending_renders";import { formatCodeBlocks } from "../../../services/syntax_highlight";import { useNoteBlob, useNoteLabel, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { RawHtmlBlock } from "../../react/RawHtml";@@ -87,13 +88,20 @@ export function ReadOnlyTextContent({ html, ntxId, dir, className, contentRef: eappContext.triggerEvent("contentElRefreshed", { ntxId, contentEl: container });}- rewriteMermaidDiagramsInContainer(container);- applyInlineMermaid(container);- applyIncludedNotes(container);- applyLinkEmbeds(container);+ // The passes that lazily load their library (mermaid, highlight.js) — plus included notes,+ // which render a whole note of their own — finish after this effect returns. On screen they+ // simply paint when ready; a caller that snapshots the DOM instead (printing) has to wait for+ // them, so the work is registered rather than dropped on the floor.+ trackPendingRender(Promise.all([+ rewriteMermaidDiagramsInContainer(container),+ applyInlineMermaid(container),+ applyIncludedNotes(container),+ applyLinkEmbeds(container),+ applyReferenceLinks(container),+ formatCodeBlocks($(container))+ ]));+applyMath(container);- applyReferenceLinks(container);- formatCodeBlocks($(container));setupImageOpening(container, true);}, [ html, ntxId, contentRef ]);@@ -130,12 +138,14 @@ function useNoteLanguage(note: FNote) {}function applyIncludedNotes(container: HTMLDivElement) {+ const loaded: Promise<unknown>[] = [];const includedNotes = container.querySelectorAll<HTMLElement>("section.include-note");for (const includedNote of includedNotes) {const noteId = includedNote.dataset.noteId;if (!noteId) continue;- loadIncludedNote(noteId, $(includedNote));+ loaded.push(loadIncludedNote(noteId, $(includedNote)));}+ return Promise.all(loaded);}function applyMath(container: HTMLDivElement) {