Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): draw Mermaid diagrams in the page's light or dark theme

Elian Dorancdb35942cbfc
diff --git a/apps/client/src/services/mermaid.ts b/apps/client/src/services/mermaid.ts
index ba24025750..6e598f76c7 100644
--- a/apps/client/src/services/mermaid.ts
+++ b/apps/client/src/services/mermaid.ts
@@ -1,26 +1,9 @@
+import { getMermaidConfig as getSharedMermaidConfig, parseMermaidTheme } from "@triliumnext/commons";
import type { MermaidConfig } from "mermaid";
export function getMermaidConfig(): MermaidConfig {
const documentStyle = window.getComputedStyle(document.documentElement);
- const mermaidTheme = documentStyle.getPropertyValue("--mermaid-theme") as "default";
-
- return {
- theme: mermaidTheme.trim() as "default",
- // Mermaid 12 made ELK the default layout and `neo` the default look. Both are pinned to the
- // pre-12 values so diagrams already stored in notes keep rendering as they were written;
- // front matter still overrides either one per diagram.
- layout: "dagre",
- look: "classic",
- securityLevel: "antiscript",
- flowchart: { useMaxWidth: false },
- sequence: { useMaxWidth: false },
- gantt: { useMaxWidth: false },
- class: { useMaxWidth: false },
- state: { useMaxWidth: false },
- pie: { useMaxWidth: true },
- journey: { useMaxWidth: false },
- gitGraph: { useMaxWidth: false }
- };
+ return getSharedMermaidConfig(parseMermaidTheme(documentStyle.getPropertyValue("--mermaid-theme")));
}
/**
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index 000fccd41f..dbfba07b3e 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -46,13 +46,11 @@ class="image">
<li>Rendering for math equations.</li>
<li><a href="#root/_help_nBAXQFj20hS1">Including notes</a> (only if the included
notes are also shared).</li>
+ <li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode
+ and redrawn when the visitor switches it.</li>
</ul>
</td>
- <td>
- <ul>
- <li>Inline Mermaid diagrams are not rendered.</li>
- </ul>
- </td>
+ <td>&nbsp;</td>
</tr>
<tr>
<th><a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a>
@@ -117,6 +115,9 @@ class="image">
<td>
<ul>
<li>No further interaction supported.</li>
+ <li>The image is the one saved when the note was last edited, in the light
+ or dark theme the application had then, so it does not follow the page's
+ light or dark mode.</li>
</ul>
</td>
</tr>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index b24b9e8df1..2832b8f003 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -32,8 +32,8 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tbody>
<tr>
<th><a class="reference-link" href="../Note%20Types/Text.md">Text</a></th>
- <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, in the language selected for each block. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li></ul></td>
- <td><ul><li>Inline Mermaid diagrams are not rendered.</li></ul></td>
+ <td><ul><li>Table of contents.</li><li>Syntax highlight of code blocks, in the language selected for each block. For “Auto-detected” blocks, the language is guessed among the ones enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → <em>Code Notes</em>; a language not enabled there is not highlighted.</li><li>Rendering for math equations.</li><li><a href="../Note%20Types/Text/Include%20Note.md">Including notes</a> (only if the included notes are also shared).</li><li>Mermaid diagrams in code blocks, drawn in the page's light or dark mode and redrawn when the visitor switches it.</li></ul></td>
+ <td>&nbsp;</td>
</tr>
<tr>
<th><a class="reference-link" href="../Note%20Types/Code.md">Code</a></th>
@@ -68,7 +68,7 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
<tr>
<th><a class="reference-link" href="../Note%20Types/Mermaid%20Diagrams.md">Mermaid Diagrams</a></th>
<td><ul><li>The diagram is displayed as a vector image.</li></ul></td>
- <td><ul><li>No further interaction supported.</li></ul></td>
+ <td><ul><li>No further interaction supported.</li><li>The image is the one saved when the note was last edited, in the light or dark theme the application had then, so it does not follow the page's light or dark mode.</li></ul></td>
</tr>
<tr>
<th><a class="reference-link" href="../Note%20Types/Canvas.md">Canvas</a></th>
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index 2c4fe79d34..5b91f6abe9 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -43,6 +43,7 @@ export * from "./lib/security_settings.js";
export * from "./lib/setup_marker.js";
export * from "./lib/standalone_api_interface.js";
export * from "./lib/favicon_contrast.js";
+export * from "./lib/mermaid_config.js";
export * from "./lib/link_embed.js";
export * from "./lib/llm_api.js";
export * from "./lib/marked_extensions.js";
diff --git a/packages/commons/src/lib/mermaid_config.spec.ts b/packages/commons/src/lib/mermaid_config.spec.ts
new file mode 100644
index 0000000000..dc57bf4584
--- /dev/null
+++ b/packages/commons/src/lib/mermaid_config.spec.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+
+import { getMermaidConfig, parseMermaidTheme } from "./mermaid_config.js";
+
+describe("getMermaidConfig", () => {
+ it("uses the given theme and pins the pre-12 layout and look", () => {
+ const config = getMermaidConfig("dark");
+
+ expect(config.theme).toBe("dark");
+ expect(config.layout).toBe("dagre");
+ expect(config.look).toBe("classic");
+ expect(config.securityLevel).toBe("antiscript");
+ expect(config.flowchart).toEqual({ useMaxWidth: false });
+ expect(config.pie).toEqual({ useMaxWidth: true });
+ });
+});
+
+describe("parseMermaidTheme", () => {
+ it("trims a known theme and falls back to default for an empty or unknown one", () => {
+ expect(parseMermaidTheme(" dark ")).toBe("dark");
+ expect(parseMermaidTheme("neutral")).toBe("neutral");
+ expect(parseMermaidTheme("")).toBe("default");
+ expect(parseMermaidTheme("midnight")).toBe("default");
+ });
+});
diff --git a/packages/commons/src/lib/mermaid_config.ts b/packages/commons/src/lib/mermaid_config.ts
new file mode 100644
index 0000000000..73849348d8
--- /dev/null
+++ b/packages/commons/src/lib/mermaid_config.ts
@@ -0,0 +1,35 @@
+/** The Mermaid themes a page can ask for through its `--mermaid-theme` CSS variable. */
+export type MermaidTheme = "default" | "base" | "dark" | "forest" | "neutral";
+
+const MERMAID_THEMES: ReadonlySet<string> = new Set<MermaidTheme>([ "default", "base", "dark", "forest", "neutral" ]);
+
+/**
+ * The Mermaid configuration every render path shares: the editor, read-only notes, Mermaid notes
+ * and the share theme. Typed without Mermaid's own types so that commons need not depend on it;
+ * the client returns it as `MermaidConfig`, which checks the shape.
+ */
+export function getMermaidConfig(theme: MermaidTheme) {
+ return {
+ theme,
+ // Mermaid 12 made ELK the default layout and `neo` the default look. Both are pinned to the
+ // pre-12 values so diagrams already stored in notes keep rendering as they were written;
+ // front matter still overrides either one per diagram.
+ layout: "dagre",
+ look: "classic",
+ securityLevel: "antiscript",
+ flowchart: { useMaxWidth: false },
+ sequence: { useMaxWidth: false },
+ gantt: { useMaxWidth: false },
+ class: { useMaxWidth: false },
+ state: { useMaxWidth: false },
+ pie: { useMaxWidth: true },
+ journey: { useMaxWidth: false },
+ gitGraph: { useMaxWidth: false }
+ } as const;
+}
+
+/** Reads a `--mermaid-theme` value, falling back to `default` when it is empty or unknown. */
+export function parseMermaidTheme(value: string): MermaidTheme {
+ const theme = value.trim();
+ return MERMAID_THEMES.has(theme) ? theme as MermaidTheme : "default";
+}
diff --git a/packages/share-theme/package.json b/packages/share-theme/package.json
index e91b71bb05..4c9629c803 100644
--- a/packages/share-theme/package.json
+++ b/packages/share-theme/package.json
@@ -27,6 +27,7 @@
"@digitak/esrun": "3.2.26",
"@triliumnext/ckeditor5": "workspace:*",
"esbuild": "0.28.2",
+ "happy-dom": "20.14.5",
"highlight.js": "11.12.0",
"sass": "1.105.1",
"typescript": "6.0.3",
diff --git a/packages/share-theme/src/base.css b/packages/share-theme/src/base.css
index 4b130928a4..9ec78a4582 100644
--- a/packages/share-theme/src/base.css
+++ b/packages/share-theme/src/base.css
@@ -11,6 +11,7 @@ html.theme-light {
--text-heading: #000000;
--text-menu: #333333;
--text-link: #0000ff;
+ --mermaid-theme: default;
color-scheme: light;
}
@@ -24,6 +25,7 @@ html.theme-dark {
--text-menu: #AAAAAA;
--text-link: #87CEFA;
--text-menu-active: #000000;
+ --mermaid-theme: dark;
color-scheme: dark;
}
diff --git a/packages/share-theme/src/content/mermaid.spec.ts b/packages/share-theme/src/content/mermaid.spec.ts
index 55a5f6ec12..11f6066a26 100644
--- a/packages/share-theme/src/content/mermaid.spec.ts
+++ b/packages/share-theme/src/content/mermaid.spec.ts
@@ -1,6 +1,7 @@
+// @vitest-environment happy-dom
import { afterEach, describe, expect, it, vi } from "vitest";
-import { loadMermaid } from "./mermaid.js";
+import setupMermaid, { loadMermaid } from "./mermaid.js";
describe("loadMermaid", () => {
afterEach(() => {
@@ -25,3 +26,41 @@ describe("loadMermaid", () => {
await expect(loadMermaid()).rejects.toThrow("HTTP 404");
});
});
+
+describe("setupMermaid", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ document.documentElement.removeAttribute("style");
+ document.documentElement.removeAttribute("class");
+ document.body.innerHTML = "";
+ });
+
+ it("draws diagrams in the page's Mermaid theme and again when the theme changes", async () => {
+ const fakeMermaid = { initialize: vi.fn(), run: vi.fn(async () => {}) };
+ vi.stubGlobal("fakeMermaid", fakeMermaid);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+ entry: "data:text/javascript,export default globalThis.fakeMermaid;"
+ }))));
+ document.body.innerHTML = `<div id="content"><pre><code class="language-mermaid">graph TD; A--&gt;B</code></pre></div>`;
+ document.documentElement.style.setProperty("--mermaid-theme", "dark");
+
+ await setupMermaid();
+
+ const diagram = document.querySelector("#content > .mermaid");
+ expect(diagram?.textContent).toBe("graph TD; A-->B");
+ expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(
+ expect.objectContaining({ theme: "dark", layout: "dagre", startOnLoad: false }));
+ expect(fakeMermaid.run).toHaveBeenLastCalledWith({ nodes: [ diagram ] });
+
+ // A class change that leaves the theme alone does not draw the diagrams again.
+ document.documentElement.classList.add("left-pane-collapsed");
+ await Promise.resolve();
+ expect(fakeMermaid.run).toHaveBeenCalledTimes(1);
+
+ document.documentElement.style.setProperty("--mermaid-theme", "default");
+ document.documentElement.classList.add("theme-light");
+ await vi.waitFor(() => expect(fakeMermaid.run).toHaveBeenCalledTimes(2));
+ expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: "default" }));
+ expect(diagram?.textContent).toBe("graph TD; A-->B");
+ });
+});
diff --git a/packages/share-theme/src/content/mermaid.ts b/packages/share-theme/src/content/mermaid.ts
index e02e014df4..81230aeb6a 100644
--- a/packages/share-theme/src/content/mermaid.ts
+++ b/packages/share-theme/src/content/mermaid.ts
@@ -1,33 +1,65 @@
+import { getMermaidConfig, type MermaidTheme, parseMermaidTheme } from "@triliumnext/commons/src/lib/mermaid_config.js";
+
export default async function setupMermaid() {
- const mermaidEls = document.querySelectorAll("#content pre code.language-mermaid");
- if (mermaidEls.length === 0) {
+ const codeBlocks = document.querySelectorAll("#content pre code.language-mermaid");
+ if (codeBlocks.length === 0) {
return;
}
const mermaid = await loadMermaid();
- for (const codeBlock of mermaidEls) {
+ const diagrams: Diagram[] = [];
+ for (const codeBlock of codeBlocks) {
const parentPre = codeBlock.parentElement;
if (!parentPre) {
continue;
}
- const mermaidDiv = document.createElement("div");
- mermaidDiv.classList.add("mermaid");
- mermaidDiv.innerHTML = codeBlock.innerHTML;
- parentPre.replaceWith(mermaidDiv);
+ const element = document.createElement("div");
+ element.classList.add("mermaid");
+ parentPre.replaceWith(element);
+ diagrams.push({ element, source: codeBlock.textContent ?? "" });
}
- // Mermaid 12 made ELK the default layout, `neo` the default look and `redux-color` the default
- // theme. All three are pinned to the pre-12 values so a published diagram renders the same way
- // it does in the app; front matter still overrides them per diagram.
- mermaid.initialize({ theme: "default", layout: "dagre", look: "classic" });
- mermaid.init();
+ let theme = readMermaidTheme();
+ let rendering = renderDiagrams(mermaid, diagrams, theme);
+
+ // The theme switch toggles a class on <html>, which changes `--mermaid-theme`.
+ new MutationObserver(() => {
+ const newTheme = readMermaidTheme();
+ if (newTheme === theme) {
+ return;
+ }
+
+ theme = newTheme;
+ rendering = rendering.then(() => renderDiagrams(mermaid, diagrams, newTheme));
+ }).observe(document.documentElement, { attributes: true, attributeFilter: [ "class" ] });
+
+ await rendering;
+}
+
+interface Diagram {
+ element: HTMLElement;
+ source: string;
}
interface Mermaid {
initialize(config: Record<string, unknown>): void;
- init(): void;
+ run(options: { nodes: HTMLElement[] }): Promise<void>;
+}
+
+/** Draws every diagram from its source, replacing what an earlier render left in the element. */
+async function renderDiagrams(mermaid: Mermaid, diagrams: Diagram[], theme: MermaidTheme) {
+ mermaid.initialize({ ...getMermaidConfig(theme), startOnLoad: false });
+ for (const { element, source } of diagrams) {
+ element.removeAttribute("data-processed");
+ element.textContent = source;
+ }
+ await mermaid.run({ nodes: diagrams.map((diagram) => diagram.element) });
+}
+
+function readMermaidTheme() {
+ return parseMermaidTheme(getComputedStyle(document.documentElement).getPropertyValue("--mermaid-theme"));
}
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3a7291b87d..8a0d1c3d5d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1370,6 +1370,9 @@ importers:
esbuild:
specifier: 0.28.2
version: 0.28.2
+ happy-dom:
+ specifier: 20.14.5
+ version: 20.14.5
highlight.js:
specifier: 11.12.0
version: 11.12.0