Skip to content

Build your personal knowledge base with Trilium Notes

fix(text): errors not shown and some diagrams not rendering

Elian Doran98fb37b25425
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index c57b935f93..67ccae6192 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -7,16 +7,33 @@ import server from "./server";
import { buildNote } from "../test/easy-froca";
// `applyInlineMermaid` dynamically imports "mermaid"; provide a controllable
-// stub whose behavior we tune per-test via the shared `mermaidRunImpl` hook.
-let mermaidRunImpl: (args: { nodes: HTMLElement[] }) => void | Promise<void> = () => {};
+// stub whose behavior we tune per-test via the shared `mermaidRenderImpl` hook.
+let mermaidRenderImpl: (id: string, source: string) => { svg: string } | Promise<{ svg: string }>
+ = (_id, source) => ({ svg: `<svg>${source}</svg>` });
const mermaidInitialize = vi.fn();
vi.mock("mermaid", () => ({
default: {
initialize: (...args: unknown[]) => mermaidInitialize(...args),
- run: (args: { nodes: HTMLElement[] }) => mermaidRunImpl(args)
+ // loadElkIfNeeded() probes the source via parse(); no ELK layout in tests.
+ parse: async () => undefined,
+ render: (id: string, source: string) => mermaidRenderImpl(id, source)
}
}));
+// i18n isn't initialized with resources in tests, so `t` returns an empty
+// string. Stub the one key this suite asserts on so the surfaced error text is
+// real; other keys fall through to the bare key (irrelevant to these tests).
+vi.mock("./i18n.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./i18n.js")>();
+ return {
+ ...actual,
+ t: (key: string, opts?: { error?: string }) =>
+ key === "content_renderer.mermaid_diagram_error"
+ ? `Mermaid diagram failed to render: ${opts?.error}`
+ : key
+ };
+});
+
// Spy on the KaTeX auto-render entry point so we can assert that
// `postProcessRichContent` only invokes it when a `span.math-tex` is present.
// The original module is kept intact (default export, CSS side-effects) so the
@@ -353,7 +370,7 @@ describe("rewriteMermaidDiagramsInContainer", () => {
describe("applyInlineMermaid", () => {
beforeEach(() => {
- mermaidRunImpl = () => {};
+ mermaidRenderImpl = (_id, source) => ({ svg: `<svg>${source}</svg>` });
mermaidInitialize.mockClear();
});
@@ -377,33 +394,22 @@ describe("applyInlineMermaid", () => {
it("renders a pending diagram and caches the produced SVG", async () => {
const container = makeContainer(["graph A"]);
- mermaidRunImpl = ({ nodes }) => {
- for (const node of nodes) {
- node.innerHTML = "<svg>A</svg>";
- node.setAttribute("data-processed", "true");
- }
- };
await applyInlineMermaid(container);
expect(mermaidInitialize).toHaveBeenCalledTimes(1);
const visible = container.querySelector("div.mermaid-diagram") as HTMLElement;
- expect(visible.innerHTML).toBe("<svg>A</svg>");
+ expect(visible.innerHTML).toBe("<svg>graph A</svg>");
expect(visible.getAttribute("data-processed")).toBe("true");
- // Offscreen render container is cleaned up.
- expect(document.body.querySelectorAll("div").length).toBe(0);
});
- it("paints cached SVG without re-running mermaid on a second pass", async () => {
+ it("paints cached SVG without re-rendering mermaid on a second pass", async () => {
const container = makeContainer(["graph CACHE"]);
- let runCount = 0;
- mermaidRunImpl = ({ nodes }) => {
- runCount++;
- for (const node of nodes) {
- node.innerHTML = "<svg>CACHE</svg>";
- node.setAttribute("data-processed", "true");
- }
+ let renderCount = 0;
+ mermaidRenderImpl = (_id, source) => {
+ renderCount++;
+ return { svg: `<svg>${source}</svg>` };
};
await applyInlineMermaid(container);
- expect(runCount).toBe(1);
+ expect(renderCount).toBe(1);
// Reset the visible node so we can observe the cached repaint.
const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
@@ -413,20 +419,14 @@ describe("applyInlineMermaid", () => {
await applyInlineMermaid(container);
// No new render: cache hit short-circuits and pending stays empty.
- expect(runCount).toBe(1);
+ expect(renderCount).toBe(1);
expect(mermaidInitialize).not.toHaveBeenCalled();
- expect(node.innerHTML).toBe("<svg>CACHE</svg>");
+ expect(node.innerHTML).toBe("<svg>graph CACHE</svg>");
expect(node.getAttribute("data-processed")).toBe("true");
});
it("shows the previous SVG as a placeholder while the new diagram renders", async () => {
const container = makeContainer(["graph V1"]);
- mermaidRunImpl = ({ nodes }) => {
- for (const node of nodes) {
- node.innerHTML = `<svg>${node.textContent}</svg>`;
- node.setAttribute("data-processed", "true");
- }
- };
await applyInlineMermaid(container);
// Edit the diagram source in place; the old SVG should be used as the
@@ -435,27 +435,18 @@ describe("applyInlineMermaid", () => {
const previousSvg = node.innerHTML;
node.textContent = "graph V2";
- let placeholderDuringRun = "";
- mermaidRunImpl = ({ nodes }) => {
- placeholderDuringRun = node.innerHTML;
- for (const clone of nodes) {
- clone.innerHTML = `<svg>${clone.textContent}</svg>`;
- clone.setAttribute("data-processed", "true");
- }
+ let placeholderDuringRender = "";
+ mermaidRenderImpl = (_id, source) => {
+ placeholderDuringRender = node.innerHTML;
+ return { svg: `<svg>${source}</svg>` };
};
await applyInlineMermaid(container);
- expect(placeholderDuringRun).toBe(previousSvg);
+ expect(placeholderDuringRender).toBe(previousSvg);
expect(node.innerHTML).toBe("<svg>graph V2</svg>");
});
it("evicts cache entries whose source is no longer present", async () => {
const container = makeContainer(["graph KEEP", "graph DROP"]);
- mermaidRunImpl = ({ nodes }) => {
- for (const node of nodes) {
- node.innerHTML = `<svg>${node.textContent}</svg>`;
- node.setAttribute("data-processed", "true");
- }
- };
await applyInlineMermaid(container);
// Remove the second diagram so its cached source must be evicted.
@@ -469,26 +460,54 @@ describe("applyInlineMermaid", () => {
expect(remaining.innerHTML).toBe("<svg>graph KEEP</svg>");
});
- it("logs but does not throw when mermaid.run rejects", async () => {
+ it("logs and surfaces the error in place when mermaid.render rejects", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const container = makeContainer(["graph BOOM"]);
- mermaidRunImpl = () => {
+ mermaidRenderImpl = () => {
throw new Error("mermaid failed");
};
await applyInlineMermaid(container);
expect(error).toHaveBeenCalled();
+ const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
+ // The failure is rendered into the node (not left as raw source), so it's
+ // visible in the UI instead of swallowed to the console.
+ expect(node.classList.contains("mermaid-error")).toBe(true);
+ expect(node.textContent).toContain("mermaid failed");
+ expect(node.getAttribute("data-processed")).toBeNull();
error.mockRestore();
});
- it("leaves the visible node untouched when the offscreen clone was not processed", async () => {
- const container = makeContainer(["graph SKIP"]);
- mermaidRunImpl = () => {
- // Render succeeds but never marks the clone as processed.
+ it("renders the valid diagram even when a sibling diagram fails", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const container = makeContainer(["graph OK", "graph BAD"]);
+ mermaidRenderImpl = (_id, source) => {
+ if (source === "graph BAD") throw new Error("bad diagram");
+ return { svg: `<svg>${source}</svg>` };
};
await applyInlineMermaid(container);
+ const [ ok, bad ] = container.querySelectorAll<HTMLElement>("div.mermaid-diagram");
+ // The good diagram still renders; only the failing one shows the error.
+ expect(ok.innerHTML).toBe("<svg>graph OK</svg>");
+ expect(bad.classList.contains("mermaid-error")).toBe(true);
+ expect(bad.textContent).toContain("bad diagram");
+ error.mockRestore();
+ });
+
+ it("keeps the previous render as placeholder instead of an error when a re-render fails", async () => {
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const container = makeContainer(["graph V1"]);
+ await applyInlineMermaid(container);
+
const node = container.querySelector("div.mermaid-diagram") as HTMLElement;
- // Visible node keeps its original source text; no SVG was applied.
- expect(node.getAttribute("data-processed")).toBeNull();
- expect(node.innerHTML).toBe("graph SKIP");
+ const previousSvg = node.innerHTML;
+ node.textContent = "graph BROKEN";
+ mermaidRenderImpl = () => {
+ throw new Error("still broken");
+ };
+ await applyInlineMermaid(container);
+ // A prior good render is showing, so keep it rather than flashing an error.
+ expect(node.classList.contains("mermaid-error")).toBe(false);
+ expect(node.innerHTML).toBe(previousSvg);
+ error.mockRestore();
});
});
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index 56731e4691..3570e51981 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -2,10 +2,11 @@ import FAttachment from "../entities/fattachment.js";
import FNote from "../entities/fnote.js";
import { default as content_renderer, type RenderOptions } from "./content_renderer.js";
import froca from "./froca.js";
+import { t } from "./i18n.js";
import link from "./link.js";
import { applyLinkEmbeds } from "./link_embed.js";
import { renderMathInElement } from "./math.js";
-import { getMermaidConfig } from "./mermaid.js";
+import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
import { sanitizeNoteContentHtml } from "./sanitize_content.js";
import { formatCodeBlocks } from "./syntax_highlight.js";
import tree from "./tree.js";
@@ -131,6 +132,9 @@ const mermaidSvgCache = new WeakMap<HTMLElement, Map<string, string>>();
*/
const mermaidLastRenderedByPosition = new WeakMap<HTMLElement, string[]>();
+/** Monotonic id for mermaid.render(), which requires a unique element id per call. */
+let mermaidRenderId = 0;
+
export async function applyInlineMermaid(container: HTMLDivElement) {
const nodes = Array.from(container.querySelectorAll<HTMLElement>("div.mermaid-diagram"));
if (!nodes.length) {
@@ -146,10 +150,10 @@ export async function applyInlineMermaid(container: HTMLDivElement) {
const lastRendered = mermaidLastRenderedByPosition.get(container) ?? [];
// Decide per node: exact cache hit → paint final SVG; source changed →
- // paint the previous SVG (by position) as a placeholder and queue an
- // offscreen re-render. This way the user keeps seeing the old diagram
- // until mermaid has finished producing the new one.
- const pending: Array<{ visible: HTMLElement; source: string }> = [];
+ // paint the previous SVG (by position) as a placeholder and queue a
+ // re-render. This way the user keeps seeing the old diagram until mermaid
+ // has finished producing the new one.
+ const pending: Array<{ visible: HTMLElement; source: string; hasPlaceholder: boolean }> = [];
const seenSources = new Set<string>();
for (const [ index, node ] of nodes.entries()) {
/* v8 ignore next -- defensive fallback: textContent on an HTMLElement is always a string */
@@ -163,8 +167,8 @@ export async function applyInlineMermaid(container: HTMLDivElement) {
continue;
}
- pending.push({ visible: node, source });
const placeholder = lastRendered[index];
+ pending.push({ visible: node, source, hasPlaceholder: Boolean(placeholder) });
if (placeholder) {
node.innerHTML = placeholder;
}
@@ -181,41 +185,43 @@ export async function applyInlineMermaid(container: HTMLDivElement) {
}
const mermaid = (await import("mermaid")).default;
- mermaid.initialize(getMermaidConfig());
-
- // Render clones offscreen so the visible nodes keep showing the placeholder
- // until the new SVG is ready. Keeps mermaid away from our placeholder SVG
- // (which would otherwise confuse its text-based parser).
- const offscreen = document.createElement("div");
- offscreen.style.cssText = "position:absolute;left:-9999px;top:-9999px;width:0;height:0;overflow:hidden;visibility:hidden;";
- document.body.appendChild(offscreen);
-
- const pairs = pending.map(({ visible, source }) => {
- const clone = document.createElement("div");
- clone.className = "mermaid-diagram";
- clone.textContent = source;
- offscreen.appendChild(clone);
- return { visible, clone, source };
- });
-
- try {
- await mermaid.run({ nodes: pairs.map((p) => p.clone) });
- for (const { visible, clone, source } of pairs) {
- if (clone.getAttribute("data-processed") !== "true") continue;
- const svg = clone.innerHTML;
- visible.innerHTML = svg;
+ mermaid.initialize({ startOnLoad: false, ...getMermaidConfig() });
+
+ // Render each diagram to an SVG string via mermaid.render() — the same API the
+ // editable note and standalone Mermaid widget use. mermaid.render() builds its
+ // own correctly-sized measurement element; rendering in place via mermaid.run()
+ // inside a collapsed offscreen container silently broke measurement-sensitive
+ // diagrams (e.g. gantt). Each diagram renders independently so one failure
+ // surfaces its own error instead of blanking the diagrams beside it.
+ for (const { visible, source, hasPlaceholder } of pending) {
+ try {
+ await loadElkIfNeeded(mermaid, source);
+ const { svg } = await mermaid.render(`mermaid-inline-${mermaidRenderId++}`, source);
+ const processed = postprocessMermaidSvg(svg);
+ visible.innerHTML = processed;
visible.setAttribute("data-processed", "true");
- cache.set(source, svg);
+ cache.set(source, processed);
+ } catch (e) {
+ console.error(e);
+ // Keep a prior good render (shown as placeholder) rather than flashing
+ // an error mid-edit; otherwise surface the failure so it isn't silently
+ // swallowed (e.g. an invalid diagram in a chat reply).
+ if (!hasPlaceholder) {
+ showMermaidError(visible, e);
+ }
}
- } catch (e) {
- console.error(e);
- } finally {
- offscreen.remove();
}
mermaidLastRenderedByPosition.set(container, nodes.map((n) => n.innerHTML));
}
+/** Render a mermaid failure in place so it's visible instead of console-only. */
+function showMermaidError(node: HTMLElement, error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ node.classList.add("mermaid-error");
+ node.textContent = t("content_renderer.mermaid_diagram_error", { error: message });
+}
+
export async function renderChildrenList($renderedContent: JQuery<HTMLElement>, note: FNote, includeArchivedNotes: boolean) {
let childNoteIds = note.getChildNoteIds();
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index bea7869d69..c1535f0cbe 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2383,7 +2383,8 @@
"unpin_tab_description": "Unpin this tab, allowing it to be closed and moved freely"
},
"content_renderer": {
- "open_externally": "Open externally"
+ "open_externally": "Open externally",
+ "mermaid_diagram_error": "Mermaid diagram failed to render: {{error}}"
},
"modal": {
"close": "Close",
diff --git a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.css b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.css
index e60260e7be..fa79b552a4 100644
--- a/apps/client/src/widgets/type_widgets/text/ReadOnlyText.css
+++ b/apps/client/src/widgets/type_widgets/text/ReadOnlyText.css
@@ -15,6 +15,19 @@
}
}
+/* Top-level (not scoped to the note view) so a swallowed mermaid failure is
+ visible in the chat panel too, where the container lacks the note class. */
+.mermaid-diagram.mermaid-error {
+ display: block;
+ white-space: pre-wrap;
+ padding: 0.75em 1em;
+ border: 1px solid var(--main-border-color);
+ border-radius: 4px;
+ color: var(--muted-text-color);
+ font-family: var(--monospace-font-family, monospace);
+ font-size: 0.85em;
+}
+
body.heading-style-markdown .note-detail-readonly-text-content {
h1::before { content: "#\2004"; color: var(--muted-text-color); }
h2::before { content: "##\2004"; color: var(--muted-text-color); }