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(share): keep a Mermaid diagram's placeholder until it is drawn
Elian Doran745d10a82e02
diff --git a/packages/share-theme/src/content/mermaid.spec.ts b/packages/share-theme/src/content/mermaid.spec.tsindex f83114a560..ba1eee3e14 100644--- a/packages/share-theme/src/content/mermaid.spec.ts+++ b/packages/share-theme/src/content/mermaid.spec.ts@@ -43,21 +43,25 @@ describe("setupMermaid", () => {await setupMermaid();const diagram = document.querySelector("#content > .mermaid");- expect(diagram?.textContent).toBe("graph TD; A-->B");+ const firstId = diagram?.querySelector("svg")?.id;+ expect(document.querySelector("#content pre")).toBeNull();+ expect(firstId).toMatch(/^share-mermaid-\d+$/);expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: "dark", layout: "dagre", startOnLoad: false }));- expect(fakeMermaid.run).toHaveBeenLastCalledWith({ nodes: [ diagram ] });+ expect(fakeMermaid.render).toHaveBeenLastCalledWith(firstId, "graph TD; A-->B");// 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);+ expect(fakeMermaid.render).toHaveBeenCalledTimes(1);document.documentElement.style.setProperty("--mermaid-theme", "default");document.documentElement.classList.add("theme-light");- await vi.waitFor(() => expect(fakeMermaid.run).toHaveBeenCalledTimes(2));+ await vi.waitFor(() => expect(fakeMermaid.render).toHaveBeenCalledTimes(2));expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: "default" }));- expect(diagram?.textContent).toBe("graph TD; A-->B");+ expect(document.querySelector("#content > .mermaid")).toBe(diagram);+ expect(diagram?.querySelectorAll("svg")).toHaveLength(1);+ expect(diagram?.querySelector("svg")?.id).not.toBe(firstId);});it("draws a Mermaid note in place of its saved image and keeps the source block", async () => {@@ -67,11 +71,40 @@ describe("setupMermaid", () => {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?.querySelectorAll(":scope > .mermaid > svg")).toHaveLength(1);expect(container?.querySelector("details pre.mermaid-note-source")).not.toBeNull();- expect(fakeMermaid.run).toHaveBeenLastCalledWith({ nodes: [ diagram ] });+ expect(fakeMermaid.render).toHaveBeenLastCalledWith(expect.any(String), "graph TD; A-->B");+ });++ it("keeps what a diagram replaces until Mermaid draws it, and draws every diagram again on a theme change", async () => {+ const fakeMermaid = stubMermaid();+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});+ document.body.innerHTML = `<div id="content"><div class="mermaid-note">`+ + `<img class="mermaid-note-image" src="api/images/abc/diagram">`+ + `<pre class="mermaid-note-source">broken</pre></div>`+ + `<pre><code class="language-mermaid">graph TD; A-->B</code></pre></div>`;++ await setupMermaid();++ expect(document.querySelector("#content > .mermaid-note > img.mermaid-note-image")).not.toBeNull();+ expect(document.querySelectorAll("#content > .mermaid > svg")).toHaveLength(1);+ expect(consoleError).toHaveBeenCalledWith(expect.objectContaining({ message: "Parse error" }));++ document.documentElement.style.setProperty("--mermaid-theme", "dark");+ document.documentElement.classList.add("theme-dark");+ await vi.waitFor(() => expect(consoleError).toHaveBeenCalledTimes(2));+ expect(fakeMermaid.initialize).toHaveBeenLastCalledWith(expect.objectContaining({ theme: "dark" }));+ expect(fakeMermaid.render.mock.calls.map(([ , source ]) => source))+ .toStrictEqual([ "graph TD; A-->B", "broken", "graph TD; A-->B", "broken" ]);+ expect(document.querySelector("#content > .mermaid-note > img.mermaid-note-image")).not.toBeNull();+ expect(document.querySelectorAll("#content > .mermaid > svg")).toHaveLength(1);++ // Back to the default theme, so that `afterEach` does not start another drawing.+ document.documentElement.style.removeProperty("--mermaid-theme");+ document.documentElement.classList.remove("theme-dark");+ await vi.waitFor(() => expect(consoleError).toHaveBeenCalledTimes(3));+ consoleError.mockRestore();});it("keeps a Mermaid note's saved image when Mermaid cannot be loaded", async () => {@@ -114,9 +147,20 @@ const MERMAID_NOTE =`<div id="content"><div class="mermaid-note">`let stubCount = 0;-/** Serves a fake Mermaid, at a URL of its own: modules are cached by URL. */+/**+ * Serves a fake Mermaid, at a URL of its own: modules are cached by URL. It cannot draw a source+ * containing `broken`.+ */function stubMermaid() {- const fakeMermaid = { initialize: vi.fn(), run: vi.fn(async () => {}) };+ const fakeMermaid = {+ initialize: vi.fn(),+ render: vi.fn(async (id: string, source: string) => {+ if (source.includes("broken")) {+ throw new Error("Parse error");+ }+ return { svg: `<svg id="${id}"></svg>` };+ })+ };vi.stubGlobal("fakeMermaid", fakeMermaid);vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({entry: `data:text/javascript,export default globalThis.fakeMermaid; // ${++stubCount}`diff --git a/packages/share-theme/src/content/mermaid.ts b/packages/share-theme/src/content/mermaid.tsindex a61b131ee6..7e37498bca 100644--- a/packages/share-theme/src/content/mermaid.ts+++ b/packages/share-theme/src/content/mermaid.ts@@ -1,25 +1,17 @@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.+ * Draws the Mermaid diagrams on the page: code blocks in a text note, and Mermaid notes. A code+ * block or a note's saved image stays in place until Mermaid has drawn its diagram.*/export default async function setupMermaid() {- const placeholders = findPlaceholders();- if (placeholders.length === 0) {+ const diagrams = findDiagrams();+ if (diagrams.length === 0) {return;}const mermaid = await loadMermaid();- const diagrams: Diagram[] = [];- for (const { placeholder, source } of placeholders) {- const element = document.createElement("div");- element.classList.add("mermaid");- placeholder.replaceWith(element);- diagrams.push({ element, source });- }-let theme = readMermaidTheme();let rendering = renderDiagrams(mermaid, diagrams, theme);@@ -38,12 +30,15 @@ export default async function setupMermaid() {}interface Diagram {+ /** The element the first drawing replaces. */+ placeholder: Element;+ /** The element the drawings go into. */element: HTMLElement;source: string;}-/** The elements a drawn diagram replaces, each with the source it is drawn from. */-function findPlaceholders() {+/** The diagrams on the page, each with the element its drawing replaces. */+function findDiagrams() {const placeholders: { placeholder: Element; source: string }[] = [];for (const block of document.querySelectorAll("#content pre")) {@@ -61,22 +56,39 @@ function findPlaceholders() {}}- return placeholders;+ return placeholders.map(({ placeholder, source }): Diagram => {+ const element = document.createElement("div");+ element.classList.add("mermaid");+ return { placeholder, element, source };+ });}interface Mermaid {initialize(config: Record<string, unknown>): void;- run(options: { nodes: HTMLElement[] }): Promise<void>;+ render(id: string, source: string): Promise<{ svg: string }>;}-/** Draws every diagram from its source, replacing what an earlier render left in the element. */+let renderCount = 0;++/**+ * Draws every diagram from its source. A diagram Mermaid cannot draw keeps what the page showed+ * for it before: its placeholder, or its drawing in the previous theme.+ */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;+ for (const { placeholder, element, source } of diagrams) {+ try {+ const { svg } = await mermaid.render(`share-mermaid-${renderCount++}`, source);+ element.innerHTML = svg;+ } catch (error) {+ console.error(error);+ continue;+ }++ if (placeholder.isConnected) {+ placeholder.replaceWith(element);+ }}- await mermaid.run({ nodes: diagrams.map((diagram) => diagram.element) });}function readMermaidTheme() {