Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): draw Mermaid notes live, like inline diagrams

Elian Doranbbbaf7b0a540
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 dbfba07b3e..c08cde3f82 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
@@ -109,15 +109,15 @@ class="image">
</th>
<td>
<ul>
- <li>The diagram is displayed as a vector image.</li>
+ <li>The diagram is drawn in the page's light or dark mode and redrawn when
+ the visitor switches it. Until it is drawn, and in browsers with JavaScript
+ disabled, the image saved when the note was last edited is shown instead.</li>
+ <li>The source of the diagram can be expanded below it.</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>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 2832b8f003..32cda0bc43 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -67,8 +67,8 @@ Trilium allows you to share selected notes as **publicly accessible** read-only
</tr>
<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><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>
+ <td><ul><li>The diagram is drawn in the page's light or dark mode and redrawn when the visitor switches it. Until it is drawn, and in browsers with JavaScript disabled, the image saved when the note was last edited is shown instead.</li><li>The source of the diagram can be expanded below it.</li></ul></td>
+ <td><ul><li>No further interaction supported.</li></ul></td>
</tr>
<tr>
<th><a class="reference-link" href="../Note%20Types/Canvas.md">Canvas</a></th>
diff --git a/packages/share-theme/src/content/mermaid.spec.ts b/packages/share-theme/src/content/mermaid.spec.ts
index 11f6066a26..781f5139c6 100644
--- a/packages/share-theme/src/content/mermaid.spec.ts
+++ b/packages/share-theme/src/content/mermaid.spec.ts
@@ -36,11 +36,7 @@ describe("setupMermaid", () => {
});
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;"
- }))));
+ const fakeMermaid = stubMermaid();
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");
@@ -63,4 +59,46 @@ describe("setupMermaid", () => {
expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: "default" }));
expect(diagram?.textContent).toBe("graph TD; A-->B");
});
+
+ it("draws a Mermaid note in place of its saved image and keeps the source block", async () => {
+ const fakeMermaid = stubMermaid();
+ document.body.innerHTML = MERMAID_NOTE;
+
+ await setupMermaid();
+
+ const container = document.querySelector("#content > .mermaid-note");
+ const diagram = container?.querySelector(":scope > .mermaid");
+ expect(container?.querySelector("img")).toBeNull();
+ expect(diagram?.textContent).toBe("graph TD; A-->B");
+ expect(container?.querySelector("details pre.mermaid-note-source")).not.toBeNull();
+ expect(fakeMermaid.run).toHaveBeenLastCalledWith({ nodes: [ diagram ] });
+ });
+
+ it("keeps a Mermaid note's saved image when Mermaid cannot be loaded", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 404 })));
+ document.body.innerHTML = MERMAID_NOTE;
+
+ await expect(setupMermaid()).rejects.toThrow("HTTP 404");
+
+ expect(document.querySelector(".mermaid-note > img.mermaid-note-image")).not.toBeNull();
+ expect(document.querySelector(".mermaid")).toBeNull();
+ });
});
+
+const MERMAID_NOTE = `<div id="content"><div class="mermaid-note">`
+ + `<img class="mermaid-note-image" src="api/images/abc/diagram">`
+ + `<hr><details><summary>Chart source</summary>`
+ + `<pre class="mermaid-note-source">graph TD; A--&gt;B</pre></details>`
+ + `</div></div>`;
+
+let stubCount = 0;
+
+/** Serves a fake Mermaid, at a URL of its own: modules are cached by URL. */
+function stubMermaid() {
+ 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; // ${++stubCount}`
+ }))));
+ return fakeMermaid;
+}
diff --git a/packages/share-theme/src/content/mermaid.ts b/packages/share-theme/src/content/mermaid.ts
index 81230aeb6a..93c51c4012 100644
--- a/packages/share-theme/src/content/mermaid.ts
+++ b/packages/share-theme/src/content/mermaid.ts
@@ -1,24 +1,23 @@
import { getMermaidConfig, type MermaidTheme, parseMermaidTheme } from "@triliumnext/commons/src/lib/mermaid_config.js";
+/**
+ * Draws the Mermaid diagrams on the page: code blocks in a text note, and Mermaid notes, whose saved
+ * image stays in place until Mermaid has loaded.
+ */
export default async function setupMermaid() {
- const codeBlocks = document.querySelectorAll("#content pre code.language-mermaid");
- if (codeBlocks.length === 0) {
+ const placeholders = findPlaceholders();
+ if (placeholders.length === 0) {
return;
}
const mermaid = await loadMermaid();
const diagrams: Diagram[] = [];
- for (const codeBlock of codeBlocks) {
- const parentPre = codeBlock.parentElement;
- if (!parentPre) {
- continue;
- }
-
+ for (const { placeholder, source } of placeholders) {
const element = document.createElement("div");
element.classList.add("mermaid");
- parentPre.replaceWith(element);
- diagrams.push({ element, source: codeBlock.textContent ?? "" });
+ placeholder.replaceWith(element);
+ diagrams.push({ element, source });
}
let theme = readMermaidTheme();
@@ -43,6 +42,27 @@ interface Diagram {
source: string;
}
+/** The elements a drawn diagram replaces, each with the source it is drawn from. */
+function findPlaceholders() {
+ const placeholders: { placeholder: Element; source: string }[] = [];
+
+ for (const codeBlock of document.querySelectorAll("#content pre code.language-mermaid")) {
+ if (codeBlock.parentElement) {
+ placeholders.push({ placeholder: codeBlock.parentElement, source: codeBlock.textContent ?? "" });
+ }
+ }
+
+ for (const note of document.querySelectorAll("#content .mermaid-note")) {
+ const image = note.querySelector(":scope > .mermaid-note-image");
+ const source = note.querySelector(".mermaid-note-source");
+ if (image && source) {
+ placeholders.push({ placeholder: image, source: source.textContent ?? "" });
+ }
+ }
+
+ return placeholders;
+}
+
interface Mermaid {
initialize(config: Record<string, unknown>): void;
run(options: { nodes: HTMLElement[] }): Promise<void>;
diff --git a/packages/share-theme/src/index.ts b/packages/share-theme/src/index.ts
index c3401f7666..c6fd786dcc 100644
--- a/packages/share-theme/src/index.ts
+++ b/packages/share-theme/src/index.ts
@@ -55,6 +55,8 @@ document.addEventListener(
if (noteType === "text" || document.querySelector("#content.ck-content")) {
setupTextNote();
+ } else if (noteType === "mermaid") {
+ $try(setupMermaid);
}
// Format <time> elements using the browser's locale.
diff --git a/packages/trilium-core/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.ts
index 9d849f16b6..0456ebbd5b 100644
--- a/packages/trilium-core/src/share/content_renderer.spec.ts
+++ b/packages/trilium-core/src/share/content_renderer.spec.ts
@@ -701,6 +701,25 @@ describe("content_renderer", () => {
});
});
+ describe("Mermaid note", () => {
+ it("shows the saved image and keeps the source for the share theme to draw", () => {
+ const note = buildShareNote({
+ id: "mermaidNote",
+ type: "mermaid",
+ mime: "text/vnd.mermaid",
+ content: "graph TD; A-->B[<script>]"
+ });
+ const root = parse(String(getContent(note).content));
+ const container = root.querySelector("div.mermaid-note");
+
+ expect(container?.querySelector("img.mermaid-note-image")?.getAttribute("src"))
+ .toMatch(/^api\/images\/mermaidNote\//);
+ expect(container?.querySelector("details pre.mermaid-note-source")?.textContent)
+ .toBe("graph TD; A-->B[<script>]");
+ expect(root.querySelector("script")).toBeNull();
+ });
+ });
+
describe("Web view note", () => {
const SANDBOX = "allow-same-origin allow-scripts allow-popups";
diff --git a/packages/trilium-core/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.ts
index 49facd38de..09f82d785a 100644
--- a/packages/trilium-core/src/share/content_renderer.ts
+++ b/packages/trilium-core/src/share/content_renderer.ts
@@ -854,18 +854,24 @@ export function renderCode(result: Result, mime?: string) {
}
}
+/**
+ * Renders a Mermaid note as the image the app saved, which the share theme's script replaces with
+ * a diagram drawn from `.mermaid-note-source` in the page's light or dark theme.
+ */
function renderMermaid(result: Result, note: SNote | BNote) {
if (typeof result.content !== "string") {
return;
}
result.content = `
-<img src="api/images/${note.noteId}/${note.encodedTitle}?${note.utcDateModified}">
+<div class="mermaid-note">
+<img class="mermaid-note-image" src="api/images/${note.noteId}/${note.encodedTitle}?${note.utcDateModified}">
<hr>
<details>
<summary>Chart source</summary>
- <pre>${escapeHtml(result.content)}</pre>
-</details>`;
+ <pre class="mermaid-note-source">${escapeHtml(result.content)}</pre>
+</details>
+</div>`;
}
function renderImage(result: Result, note: SNote | BNote) {