Skip to content

Build your personal knowledge base with Trilium Notes

fix(mind-map): generate SVG preview with native exportSvg instead of snapdom

Elian Doran6bf570ce50b0
diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsx
index 4130942e55..9901d45e48 100644
--- a/apps/client/src/widgets/type_widgets/MindMap.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx
@@ -5,7 +5,6 @@ import "./MindMap.css";
// allow node-menu plugin css to be bundled by webpack
import nodeMenu from "@mind-elixir/node-menu";
import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
-import { snapdom } from "@zumer/snapdom";
import { t } from "i18next";
import { DARK_THEME, default as VanillaMindElixir, MindElixirData, MindElixirInstance, Operation, THEME as LIGHT_THEME } from "mind-elixir";
import type { LangPack } from "mind-elixir/i18n";
@@ -16,6 +15,7 @@ import { sanitizeNoteContentHtml } from "../../services/sanitize_content";
import utils from "../../services/utils";
import { useColorScheme, useEditorSpacedUpdate, useEffectiveReadOnly, useSyncedRef, useTriliumEvent, useTriliumEvents, useTriliumOption } from "../react/hooks";
import { refToJQuerySelector } from "../react/react_utils";
+import { renderMindMapPreviewSvg } from "./helpers/mind_map_export";
import { TypeWidgetProps } from "./type_widget";
const NEW_TOPIC_NAME = "";
@@ -103,16 +103,6 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {
getData: async () => {
if (!apiRef.current) return;
- const result = await snapdom(apiRef.current.nodes, {
- backgroundColor: "transparent",
- scale: 2
- });
-
- // a data URL in the format: "data:image/svg+xml;charset=utf-8,<url-encoded-svg>"
- // We need to extract the content after the comma and decode the URL encoding (%3C to <, %20 to space, etc.)
- // to get raw SVG content that Trilium's backend can store as an attachment
- const svgContent = decodeURIComponent(result.url.split(',')[1]);
-
return {
content: apiRef.current.getDataString(),
attachments: [
@@ -120,7 +110,7 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {
role: "image",
title: NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap,
mime: "image/svg+xml",
- content: svgContent,
+ content: await renderMindMapPreviewSvg(apiRef.current),
position: 0
}
]
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts
new file mode 100644
index 0000000000..e2bf21f7bc
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.spec.ts
@@ -0,0 +1,228 @@
+// @vitest-environment jsdom
+// The label injection relies on sanitizeNoteContentHtml (DOMPurify), which happy-dom
+// breaks (NodeIterator mishandling — see sanitize_content.spec.ts). jsdom matches
+// real-browser behavior.
+import MindElixir, { type MindElixirData, type MindElixirInstance } from "mind-elixir";
+import { describe, expect, it } from "vitest";
+
+import { injectSvgLabels, renderMindMapPreviewSvg } from "./mind_map_export";
+
+// mind-elixir touches these browser APIs at construction time; jsdom lacks them.
+window.matchMedia = window.matchMedia ?? ((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false
+}));
+globalThis.ResizeObserver = globalThis.ResizeObserver ?? class {
+
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+
+};
+
+/**
+ * Reproduces the structure of mind-elixir's `exportSvg()` output:
+ * an outer svg holding a background rect and an inner svg with the map layers.
+ */
+function buildExportedSvg() {
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="400px" height="300px">` +
+ `<rect x="0" y="0" width="400" height="300" fill="#fff"/>` +
+ `<svg x="100" y="100" overflow="visible"><g class="topiclinks"></g></svg>` +
+ `</svg>`;
+}
+
+function buildMind({ labels = [] as string[], exportedSvg = buildExportedSvg() } = {}) {
+ const nodes = document.createElement("me-nodes");
+ for (const labelHtml of labels) {
+ const label = document.createElement("div");
+ label.className = "svg-label";
+ label.innerHTML = labelHtml;
+ nodes.appendChild(label);
+ }
+ document.body.appendChild(nodes);
+
+ return {
+ nodes,
+ exportSvg: () => new Blob([ exportedSvg ], { type: "image/svg+xml" })
+ } as unknown as MindElixirInstance;
+}
+
+describe("injectSvgLabels", () => {
+ it("appends a foreignObject per label to the inner svg, carrying the label content", () => {
+ const mind = buildMind({ labels: [ "first label", "second <b>label</b>" ] });
+
+ const result = injectSvgLabels(mind, buildExportedSvg());
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ const innerSvg = doc.documentElement.querySelector(":scope > svg");
+ const foreignObjects = innerSvg?.querySelectorAll("foreignObject") ?? [];
+
+ expect(foreignObjects).toHaveLength(2);
+ expect(foreignObjects[0].textContent).toBe("first label");
+ expect(foreignObjects[1].querySelector("b")?.textContent).toBe("label");
+ // The outer svg must only gain content inside the inner svg.
+ expect(doc.documentElement.querySelectorAll(":scope > foreignObject")).toHaveLength(0);
+ });
+
+ it("sanitizes label HTML before embedding it", () => {
+ const dirtyLabel = `safe<img src="x" onerror="alert(1)"><script>alert(2)</script>`;
+ const mind = buildMind({ labels: [ dirtyLabel ] });
+
+ const result = injectSvgLabels(mind, buildExportedSvg());
+
+ expect(result).toContain("safe");
+ expect(result).not.toContain("onerror");
+ expect(result).not.toContain("<script>");
+ });
+
+ it("returns the input unchanged when there are no labels or no inner svg", () => {
+ const noLabels = buildMind();
+ expect(injectSvgLabels(noLabels, buildExportedSvg())).toBe(buildExportedSvg());
+
+ const withLabels = buildMind({ labels: [ "a label" ] });
+ const flatSvg = `<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`;
+ expect(injectSvgLabels(withLabels, flatSvg)).toBe(flatSvg);
+ });
+});
+
+describe("renderMindMapPreviewSvg", () => {
+ it("exports the map and injects the labels", async () => {
+ const mind = buildMind({ labels: [ "arrow label" ] });
+
+ const result = await renderMindMapPreviewSvg(mind);
+
+ expect(result).toContain("topiclinks");
+ expect(result).toContain("arrow label");
+ });
+});
+
+/**
+ * Non-regression tests against a real mind-elixir instance, guarding the internals the
+ * label injection depends on (labels as `.svg-label` divs inside `mind.nodes`, the
+ * nested-svg export structure). If these fail after a mind-elixir upgrade, re-verify
+ * mind_map_export.ts against the new internals — see the module comment there.
+ */
+describe("renderMindMapPreviewSvg (real mind-elixir)", () => {
+ function initRealMindMap(data: MindElixirData): MindElixirInstance {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const mind = new MindElixir({ el });
+ mind.init(data);
+ return mind;
+ }
+
+ const MAP_WITH_LABELS: MindElixirData = {
+ nodeData: {
+ id: "root",
+ topic: "Root topic",
+ children: [
+ { id: "a", topic: "Topic A", children: [] },
+ { id: "b", topic: "Topic B", children: [] }
+ ]
+ },
+ arrows: [
+ {
+ id: "arrow1",
+ label: "my arrow label",
+ from: "a",
+ to: "b",
+ delta1: { x: 50, y: -50 },
+ delta2: { x: -50, y: 50 }
+ }
+ ],
+ summaries: [
+ { id: "sum1", label: "my summary label", parent: "root", start: 0, end: 1 }
+ ]
+ };
+
+ it("renders arrow and summary labels as .svg-label elements inside mind.nodes", () => {
+ const mind = initRealMindMap(MAP_WITH_LABELS);
+ const labels = mind.nodes.querySelectorAll(".svg-label");
+
+ expect(labels).toHaveLength(2);
+ const labelTexts = Array.from(labels).map((label) => label.textContent);
+ expect(labelTexts).toContain("my arrow label");
+ expect(labelTexts).toContain("my summary label");
+ });
+
+ it("exportSvg() alone still misses the labels (the upstream gap we patch)", async () => {
+ // If this starts failing, upstream fixed SSShooter/mind-elixir-core#359 and
+ // injectSvgLabels may duplicate labels — re-evaluate whether it is still needed.
+ const mind = initRealMindMap(MAP_WITH_LABELS);
+ const rawExport = await mind.exportSvg().text();
+
+ expect(rawExport).toContain("Topic A");
+ expect(rawExport).not.toContain("my arrow label");
+ expect(rawExport).not.toContain("my summary label");
+ });
+
+ it("the preview contains topics and both labels, and parses as valid SVG", async () => {
+ const mind = initRealMindMap(MAP_WITH_LABELS);
+ const result = await renderMindMapPreviewSvg(mind);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ expect(doc.querySelector("parsererror")).toBeNull();
+
+ const expectedTexts = [
+ "Root topic", "Topic A", "Topic B", "my arrow label", "my summary label"
+ ];
+ for (const text of expectedTexts) {
+ expect(result).toContain(text);
+ }
+
+ // Both labels must land inside the inner (map layers) svg as foreignObjects.
+ const innerSvg = doc.documentElement.querySelector(":scope > svg");
+ const labelDivs = Array.from(innerSvg?.querySelectorAll("foreignObject > div") ?? [])
+ .map((div) => div.textContent);
+ expect(labelDivs).toContain("my arrow label");
+ expect(labelDivs).toContain("my summary label");
+ });
+
+ it("XML-special characters in topics and labels survive export as valid SVG", async () => {
+ const mind = initRealMindMap({
+ nodeData: {
+ id: "root",
+ topic: "Both l & r <tags>",
+ children: [
+ { id: "a", topic: "A", children: [] },
+ { id: "b", topic: "B", children: [] }
+ ]
+ },
+ arrows: [
+ {
+ id: "arrow1",
+ label: `label & <b>"quoted"</b>`,
+ from: "a",
+ to: "b",
+ delta1: { x: 50, y: -50 },
+ delta2: { x: -50, y: 50 }
+ }
+ ]
+ });
+ const result = await renderMindMapPreviewSvg(mind);
+
+ const doc = new DOMParser().parseFromString(result, "image/svg+xml");
+ expect(doc.querySelector("parsererror")).toBeNull();
+ expect(result).toContain("Both l &amp; r");
+
+ const labelDivs = Array.from(doc.querySelectorAll("foreignObject > div"))
+ .map((div) => div.textContent);
+ expect(labelDivs).toContain(`label & "quoted"`);
+ });
+
+ it("a map without arrows or summaries exports without injection", async () => {
+ const mind = initRealMindMap({
+ nodeData: { id: "root", topic: "Just a root", children: [] }
+ });
+ const result = await renderMindMapPreviewSvg(mind);
+
+ expect(result).toContain("Just a root");
+ expect(result).not.toContain("foreignObject><div"); // no injected labels
+ expect(await mind.exportSvg().text()).toBe(result);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts
new file mode 100644
index 0000000000..c5bf6fc93b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts
@@ -0,0 +1,94 @@
+import type { MindElixirInstance } from "mind-elixir";
+
+import { sanitizeNoteContentHtml } from "../../../services/sanitize_content";
+
+const SVG_NS = "http://www.w3.org/2000/svg";
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+
+/**
+ * Renders the mind map to an SVG string for the preview attachment (share pages,
+ * include-note, `api/images`) using mind-elixir's native exporter.
+ *
+ * The native exporter clones the map's SVG layers directly, which makes it orders of
+ * magnitude faster than a DOM screenshot library (~7ms vs ~1100ms with snapdom for the
+ * demo map, see #10478) — but it has one known gap: labels of arrows ("custom links")
+ * and summaries live in an HTML overlay (`.label-container`) rather than in the SVG
+ * layers it clones, so they are missing from its output (the reason the preview was
+ * previously generated with snapdom). {@link injectSvgLabels} re-adds them.
+ *
+ * Note that upstream considers `exportSvg()` deprecated in favor of DOM screenshot
+ * libraries and will not fix the label gap (see
+ * https://github.com/SSShooter/mind-elixir-core/issues/359) — that advice is intended
+ * for user-triggered exports (where Trilium does use snapdom, see the exportSvg/exportPng
+ * handlers in MindMap.tsx), but a screenshot pass is far too slow to run on every save.
+ * We deliberately keep the native exporter here for performance; if a future mind-elixir
+ * release removes it (a loud, type-level break), vendor the exporter instead of
+ * switching the save path back to a screenshot library.
+ */
+export async function renderMindMapPreviewSvg(mind: MindElixirInstance): Promise<string> {
+ const svgText = await mind.exportSvg().text();
+ return injectSvgLabels(mind, svgText);
+}
+
+/**
+ * Re-adds the arrow/summary labels missing from mind-elixir's `exportSvg()` output.
+ *
+ * Labels are absolutely positioned `div.svg-label` elements inside `mind.nodes`
+ * (their offset parent is the `position: relative` `me-nodes` element), so their
+ * `offsetLeft`/`offsetTop` are in the same coordinate space as the exported SVG
+ * layers. Each label is appended to the exporter's inner `<svg>` (the one holding
+ * the map layers) as a `<foreignObject>` replicating the label's box and text style.
+ *
+ * @param mind the live mind map instance the SVG was exported from.
+ * @param svgText the output of `mind.exportSvg().text()`.
+ * @returns the SVG with the labels injected, or the input unchanged if there are no
+ * labels or it cannot be parsed.
+ */
+export function injectSvgLabels(mind: MindElixirInstance, svgText: string): string {
+ const labels = mind.nodes.querySelectorAll<HTMLElement>(".svg-label");
+ if (labels.length === 0) {
+ return svgText;
+ }
+
+ const doc = new DOMParser().parseFromString(svgText, "image/svg+xml");
+ // The exporter produces <svg> [ <rect background>, <svg map layers> ] — label
+ // coordinates are relative to the inner svg.
+ const contentSvg = doc.documentElement?.querySelector(":scope > svg");
+ if (!contentSvg) {
+ return svgText;
+ }
+
+ for (const label of Array.from(labels)) {
+ contentSvg.appendChild(doc.importNode(buildLabelForeignObject(label), true));
+ }
+
+ return new XMLSerializer().serializeToString(doc);
+}
+
+/**
+ * Builds a `<foreignObject>` mirroring an on-screen `.svg-label` element, carrying
+ * over its box (position, size, background, border radius) and text styling. Built in
+ * the page's document so the label HTML is parsed leniently as HTML; the caller
+ * imports it into the SVG document.
+ */
+function buildLabelForeignObject(label: HTMLElement): SVGElement {
+ const style = getComputedStyle(label);
+
+ const foreignObject = document.createElementNS(SVG_NS, "foreignObject");
+ foreignObject.setAttribute("x", String(label.offsetLeft));
+ foreignObject.setAttribute("y", String(label.offsetTop));
+ foreignObject.setAttribute("width", style.width);
+ foreignObject.setAttribute("height", style.height);
+
+ const div = document.createElementNS(XHTML_NS, "div") as HTMLElement;
+ div.setAttribute("style",
+ "box-sizing: border-box; width: 100%; height: 100%; " +
+ `font-family: ${style.fontFamily}; font-size: ${style.fontSize}; ` +
+ `font-weight: ${style.fontWeight}; line-height: ${style.lineHeight}; ` +
+ `color: ${style.color}; padding: ${style.padding}; ` +
+ `background-color: ${style.backgroundColor}; border-radius: ${style.borderRadius};`);
+ div.innerHTML = sanitizeNoteContentHtml(label.innerHTML);
+
+ foreignObject.appendChild(div);
+ return foreignObject;
+}