Skip to content

Build your personal knowledge base with Trilium Notes

fix(mermaid): keep dagre and the classic look across the v12 bump

Elian Doran519df5a02da7
diff --git a/apps/client/package.json b/apps/client/package.json
index 3481e5607a..99e97637d6 100644
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@ -19,7 +19,6 @@
"dependencies": {
"@excalidraw/excalidraw": "0.18.1",
"@fullcalendar/rrule": "7.1.0",
- "@mermaid-js/layout-elk": "0.2.2",
"@popperjs/core": "2.11.8",
"@preact/signals": "2.11.2",
"@triliumnext/ckeditor5": "workspace:*",
diff --git a/apps/client/src/services/content_renderer.spec.ts b/apps/client/src/services/content_renderer.spec.ts
index d990a3b970..36649e1057 100644
--- a/apps/client/src/services/content_renderer.spec.ts
+++ b/apps/client/src/services/content_renderer.spec.ts
@@ -53,10 +53,10 @@ vi.mock("./open.js", () => ({
}
}));
-const loadElkIfNeeded = vi.fn(async (..._args: any[]) => {});
+const getMermaidConfig = vi.fn(() => ({ theme: "default", layout: "dagre", look: "classic" }));
const postprocessMermaidSvg = vi.fn((...args: any[]) => `<svg class="mm">${args[0]}</svg>`);
vi.mock("./mermaid.js", () => ({
- loadElkIfNeeded: (...a: any[]) => loadElkIfNeeded(...a),
+ getMermaidConfig: () => getMermaidConfig(),
postprocessMermaidSvg: (...a: any[]) => postprocessMermaidSvg(...a)
}));
@@ -514,7 +514,9 @@ describe("getRenderedContent render / doc / protectedSession / mermaid", () => {
const { type, $renderedContent } = await getRenderedContent(note);
expect(type).toBe("mermaid");
expect(mermaidInitialize).toHaveBeenCalledOnce();
- expect(loadElkIfNeeded).toHaveBeenCalledOnce();
+ expect(mermaidInitialize).toHaveBeenCalledWith(
+ expect.objectContaining({ layout: "dagre", look: "classic", startOnLoad: false })
+ );
expect(postprocessMermaidSvg).toHaveBeenCalledWith("<g/>");
expect($renderedContent.find("svg.mm").length).toBe(1);
});
diff --git a/apps/client/src/services/content_renderer.ts b/apps/client/src/services/content_renderer.ts
index 12a8795df9..5fd15c3d59 100644
--- a/apps/client/src/services/content_renderer.ts
+++ b/apps/client/src/services/content_renderer.ts
@@ -12,7 +12,7 @@ import { type MediaEnvironment, showsFileActions } from "../widgets/type_widgets
import type { LlmChatContent, StoredMessage } from "../widgets/type_widgets/llm_chat/llm_chat_types.js";
import renderText, { postProcessRichContent, renderChildrenList } from "./content_renderer_text.js";
import renderDoc from "./doc_renderer.js";
-import { loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
+import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";
import { renderOfficeToHtml } from "./office_renderer.js";
import openService from "./open.js";
import { waitForPendingRenders } from "./pending_renders.js";
@@ -460,13 +460,9 @@ async function renderMermaid(note: FNote | FAttachment, $renderedContent: JQuery
$renderedContent.css("display", "flex").css("justify-content", "space-around");
- const documentStyle = window.getComputedStyle(document.documentElement);
- const mermaidTheme = documentStyle.getPropertyValue("--mermaid-theme");
-
- mermaid.mermaidAPI.initialize({ startOnLoad: false, theme: mermaidTheme.trim() as "default", securityLevel: "antiscript" });
+ mermaid.mermaidAPI.initialize({ ...getMermaidConfig(), startOnLoad: false });
try {
- await loadElkIfNeeded(mermaid, content);
const { svg } = await mermaid.mermaidAPI.render(`in-mermaid-graph-${idCounter++}`, content);
$renderedContent.append($(postprocessMermaidSvg(svg)));
diff --git a/apps/client/src/services/content_renderer_text.spec.ts b/apps/client/src/services/content_renderer_text.spec.ts
index 6c1ee500b2..a4ccb956e6 100644
--- a/apps/client/src/services/content_renderer_text.spec.ts
+++ b/apps/client/src/services/content_renderer_text.spec.ts
@@ -19,8 +19,6 @@ const mermaidInitialize = vi.fn();
vi.mock("mermaid", () => ({
default: {
initialize: (...args: unknown[]) => mermaidInitialize(...args),
- // loadElkIfNeeded() probes the source via parse(); no ELK layout in tests.
- parse: async () => undefined,
render: (id: string, source: string) => mermaidRenderImpl(id, source)
}
}));
diff --git a/apps/client/src/services/content_renderer_text.ts b/apps/client/src/services/content_renderer_text.ts
index ad35822601..b9108eade6 100644
--- a/apps/client/src/services/content_renderer_text.ts
+++ b/apps/client/src/services/content_renderer_text.ts
@@ -7,7 +7,7 @@ import froca from "./froca.js";
import { t } from "./i18n.js";
import link from "./link.js";
import { applyLinkEmbeds } from "./link_embed.js";
-import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
+import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";
import { sanitizeNoteContentHtml } from "./sanitize_content.js";
import { formatCodeBlocks } from "./syntax_highlight.js";
import tree from "./tree.js";
@@ -242,7 +242,6 @@ export async function applyInlineMermaid(container: HTMLDivElement) {
// surfaces its own error instead of blanking the diagrams beside it.
for (const { visible, source } of pending) {
try {
- await loadElkIfNeeded(mermaid, source);
const { svg } = await mermaid.render(`mermaid-inline-${mermaidRenderId++}`, source);
const processed = postprocessMermaidSvg(svg);
visible.innerHTML = processed;
diff --git a/apps/client/src/services/mermaid.spec.ts b/apps/client/src/services/mermaid.spec.ts
index 8c85d80657..bf195cfb12 100644
--- a/apps/client/src/services/mermaid.spec.ts
+++ b/apps/client/src/services/mermaid.spec.ts
@@ -1,6 +1,5 @@
-import type { Mermaid } from "mermaid";
-import { describe, expect, it, vi } from "vitest";
-import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "./mermaid.js";
+import { describe, expect, it } from "vitest";
+import { getMermaidConfig, postprocessMermaidSvg } from "./mermaid.js";
import { trimIndentation } from "@triliumnext/commons";
describe("Mermaid", () => {
@@ -41,12 +40,14 @@ describe("Mermaid", () => {
});
describe("getMermaidConfig", () => {
- it("reads the --mermaid-theme CSS variable (trimmed) and keeps the static useMaxWidth flags", () => {
+ it("reads the --mermaid-theme CSS variable (trimmed), pins the pre-12 layout and look, and keeps the static useMaxWidth flags", () => {
document.documentElement.style.setProperty("--mermaid-theme", " dark ");
const config = getMermaidConfig();
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.sequence).toEqual({ useMaxWidth: false });
@@ -60,60 +61,3 @@ describe("getMermaidConfig", () => {
document.documentElement.style.removeProperty("--mermaid-theme");
});
});
-
-describe("loadElkIfNeeded", () => {
- function fakeMermaid(parseResult: unknown) {
- return {
- parse: vi.fn(async () => parseResult),
- registerLayoutLoaders: vi.fn()
- } as unknown as Mermaid & {
- parse: ReturnType<typeof vi.fn>;
- registerLayoutLoaders: ReturnType<typeof vi.fn>;
- };
- }
-
- // NOTE: the module-level `elkLoaded` flag flips to true the first time an
- // elk diagram is parsed, and the source exposes no way to reset it. The
- // "does not register" cases must therefore run while the flag is still false.
- // The "already loaded" early-exit test flips the flag itself (so it does not
- // depend on a sibling test having run first) before asserting the early exit.
-
- it("does not register loaders when parsing yields nothing", async () => {
- const mermaid = fakeMermaid(null);
- await loadElkIfNeeded(mermaid, "graph TD; A-->B");
- expect(mermaid.parse).toHaveBeenCalledWith("graph TD; A-->B", { suppressErrors: true });
- expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
- });
-
- it("does not register loaders when the layout is not elk", async () => {
- const mermaid = fakeMermaid({ config: { layout: "dagre" } });
- await loadElkIfNeeded(mermaid, "graph TD; A-->B");
- expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
- });
-
- it("does not register loaders when there is no config at all", async () => {
- const mermaid = fakeMermaid({});
- await loadElkIfNeeded(mermaid, "graph TD; A-->B");
- expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
- });
-
- it("registers the elk layout loader when the diagram requests elk", async () => {
- const mermaid = fakeMermaid({ config: { layout: "elk" } });
- await loadElkIfNeeded(mermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");
- expect(mermaid.registerLayoutLoaders).toHaveBeenCalledTimes(1);
- expect(mermaid.registerLayoutLoaders.mock.calls[0][0]).toBeTruthy();
- });
-
- it("exits immediately without parsing once elk has already been loaded", async () => {
- // Make this test self-contained rather than relying on a sibling test having
- // already flipped the module-level `elkLoaded` flag: first flip it ourselves by
- // parsing an elk diagram, then assert the early-exit on a fresh mermaid instance.
- const firstMermaid = fakeMermaid({ config: { layout: "elk" } });
- await loadElkIfNeeded(firstMermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");
-
- const mermaid = fakeMermaid({ config: { layout: "elk" } });
- await loadElkIfNeeded(mermaid, "---\nconfig:\n layout: elk\n---\ngraph TD; A-->B");
- expect(mermaid.parse).not.toHaveBeenCalled();
- expect(mermaid.registerLayoutLoaders).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/client/src/services/mermaid.ts b/apps/client/src/services/mermaid.ts
index 35d2555f8d..ba24025750 100644
--- a/apps/client/src/services/mermaid.ts
+++ b/apps/client/src/services/mermaid.ts
@@ -1,7 +1,4 @@
import type { MermaidConfig } from "mermaid";
-import type { Mermaid } from "mermaid";
-
-let elkLoaded = false;
export function getMermaidConfig(): MermaidConfig {
const documentStyle = window.getComputedStyle(document.documentElement);
@@ -9,6 +6,11 @@ export function getMermaidConfig(): MermaidConfig {
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 },
@@ -21,30 +23,6 @@ export function getMermaidConfig(): MermaidConfig {
};
}
-/**
- * Determines whether the ELK extension of Mermaid.js needs to be loaded (which is a relatively large library), based on the
- * front-matter of the diagram and loads the library if needed.
- *
- * <p>
- * If the library has already been loaded or the diagram does not require it, the method will exit immediately.
- *
- * @param mermaidContent the plain text of the mermaid diagram, potentially including a frontmatter.
- */
-export async function loadElkIfNeeded(mermaid: Mermaid, mermaidContent: string) {
- if (elkLoaded) {
- // Exit immediately since the ELK library is already loaded.
- return;
- }
-
- const parsedContent = await mermaid.parse(mermaidContent, {
- suppressErrors: true
- });
- if (parsedContent && parsedContent.config?.layout === "elk") {
- elkLoaded = true;
- mermaid.registerLayoutLoaders((await import("@mermaid-js/layout-elk")).default);
- }
-}
-
/**
* Processes the output of a Mermaid SVG render before it should be delivered to the user.
*
diff --git a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
index e6b14b548d..19be7b050e 100644
--- a/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
+++ b/apps/client/src/widgets/type_widgets/mermaid/Mermaid.tsx
@@ -3,7 +3,7 @@ import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
import { useCallback } from "preact/hooks";
import { t } from "../../../services/i18n";
-import { getMermaidConfig, loadElkIfNeeded, postprocessMermaidSvg } from "../../../services/mermaid";
+import { getMermaidConfig, postprocessMermaidSvg } from "../../../services/mermaid";
import NoteContentSwitcher from "../../layout/NoteContentSwitcher";
import SvgSplitEditor from "../helpers/SvgSplitEditor";
import { TypeWidgetProps } from "../type_widget";
@@ -15,7 +15,6 @@ let idCounter = 1;
export default function Mermaid(props: TypeWidgetProps) {
const renderSvg = useCallback(async (content: string) => {
const mermaid = (await import("mermaid")).default;
- await loadElkIfNeeded(mermaid, content);
if (!content.trim()) {
return "";
diff --git a/apps/standalone/package.json b/apps/standalone/package.json
index 79a688087b..7ff69fd2a7 100644
--- a/apps/standalone/package.json
+++ b/apps/standalone/package.json
@@ -15,7 +15,6 @@
},
"dependencies": {
"@excalidraw/excalidraw": "0.18.1",
- "@mermaid-js/layout-elk": "0.2.2",
"@popperjs/core": "2.11.8",
"@preact/signals": "2.11.2",
"@sqlite.org/sqlite-wasm": "3.51.1-build2",
diff --git a/packages/share-theme/src/scripts/modules/mermaid.ts b/packages/share-theme/src/scripts/modules/mermaid.ts
index 78ae5a573c..1b6257840a 100644
--- a/packages/share-theme/src/scripts/modules/mermaid.ts
+++ b/packages/share-theme/src/scripts/modules/mermaid.ts
@@ -18,5 +18,9 @@ export default async function setupMermaid() {
parentPre.replaceWith(mermaidDiv);
}
+ // 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();
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6cf75da761..8394ef8e60 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -209,9 +209,6 @@ importers:
'@fullcalendar/rrule':
specifier: 7.1.0
- '@mermaid-js/layout-elk':
- specifier: 0.2.2
- version: 0.2.2([email protected])
'@popperjs/core':
specifier: 2.11.8
version: 2.11.8
@@ -826,9 +823,6 @@ importers:
'@excalidraw/excalidraw':
specifier: 0.18.1
version: 0.18.1(patch_hash=859531a8ff622291b895d36bcd33e07ced6fcb3bcc90631ccaf776789b03f0c2)([email protected]([email protected]))([email protected])
- '@mermaid-js/layout-elk':
- specifier: 0.2.2
- version: 0.2.2([email protected])
'@popperjs/core':
specifier: 2.11.8
version: 2.11.8
@@ -3376,11 +3370,6 @@ packages:
resolution: {integrity: sha512-PzdZZzRhcXvKB0begee28n5lvwAcinGKYuLZOVxHAZm+n7y01ddEGfdS1ZXRuVcV+ndG6mSEAE8vgudom5UjYg==}
- '@mermaid-js/[email protected]':
- resolution: {integrity: sha512-vnH3gtqfhyBiRVKNpT8iDENTw18q/OF0GF/SfYfHN43KZpu+6eZDEOMHTfNYAkpmUWJNgtRQFIS6BTc7vH/DYQ==}
- peerDependencies:
- mermaid: 12.0.0
-
'@mermaid-js/[email protected]':
resolution: {integrity: sha512-lnjOhe7zyHjc+If7yT4zoedx2vo4sHaTmtkl1+or8BRTnCtDmcTpAjpzDSfCZrshM5bCoz0GyidzadJAH1xobA==}
@@ -14567,12 +14556,6 @@ snapshots:
'@mdn/[email protected]': {}
- dependencies:
- d3: 7.9.0
- elkjs: 0.9.3
- mermaid: 12.0.0
-
'@mermaid-js/[email protected]':
dependencies:
langium: 3.3.1