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(mind-map): PNG export clipped text — add slack to exact-fit foreignObjects
Elian Doran60f171537aa6
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.tsindex e2bf21f7bc..18d9dbb37b 100644--- 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@@ -5,7 +5,7 @@import MindElixir, { type MindElixirData, type MindElixirInstance } from "mind-elixir";import { describe, expect, it } from "vitest";-import { injectSvgLabels, renderMindMapPreviewSvg } from "./mind_map_export";+import { postProcessExportedSvg, renderMindMapPreviewSvg } from "./mind_map_export";// mind-elixir touches these browser APIs at construction time; jsdom lacks them.window.matchMedia = window.matchMedia ?? ((query: string) => ({@@ -53,11 +53,11 @@ function buildMind({ labels = [] as string[], exportedSvg = buildExportedSvg() }} as unknown as MindElixirInstance;}-describe("injectSvgLabels", () => {+describe("postProcessExportedSvg", () => {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 result = postProcessExportedSvg(mind, buildExportedSvg());const doc = new DOMParser().parseFromString(result, "image/svg+xml");const innerSvg = doc.documentElement.querySelector(":scope > svg");const foreignObjects = innerSvg?.querySelectorAll("foreignObject") ?? [];@@ -73,20 +73,38 @@ describe("injectSvgLabels", () => {const dirtyLabel = `safe<img src="x" onerror="alert(1)"><script>alert(2)</script>`;const mind = buildMind({ labels: [ dirtyLabel ] });- const result = injectSvgLabels(mind, buildExportedSvg());+ const result = postProcessExportedSvg(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());+ it("adds anti-clipping slack to the exporter's exact-fit foreignObject sizes", () => {+ // Exact-fit boxes + pre-wrap clip text when rasterization resolves fonts a hair+ // wider than the page did ("Hi there" → "Hi") — sizes must gain slack.+ const exportedSvg = `<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"><foreignObject x="10" y="10"+ width="86.3167px" height="37.5px"><div>Hi there</div></foreignObject></svg></svg>`;+ const result = postProcessExportedSvg(buildMind(), exportedSvg);++ const doc = new DOMParser().parseFromString(result, "image/svg+xml");+ const foreignObject = doc.querySelector("foreignObject");+ expect(foreignObject?.getAttribute("width")).toBe(String(Math.ceil(86.3167 * 1.02 + 2)));+ expect(foreignObject?.getAttribute("height")).toBe(String(Math.ceil(37.5 * 1.02 + 2)));+ // The background rect and the svg dimensions must stay untouched.+ expect(doc.querySelector("rect")?.getAttribute("width")).toBe("400");+ });++ it("adds no labels when the map has none, and returns unparseable input unchanged", () => {+ const noLabels = postProcessExportedSvg(buildMind(), buildExportedSvg());+ const doc = new DOMParser().parseFromString(noLabels, "image/svg+xml");+ expect(doc.querySelectorAll("foreignObject")).toHaveLength(0);const withLabels = buildMind({ labels: [ "a label" ] });const flatSvg = `<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`;- expect(injectSvgLabels(withLabels, flatSvg)).toBe(flatSvg);+ expect(postProcessExportedSvg(withLabels, flatSvg)).toBe(flatSvg);});});@@ -215,14 +233,18 @@ describe("renderMindMapPreviewSvg (real mind-elixir)", () => {expect(labelDivs).toContain(`label & "quoted"`);});- it("a map without arrows or summaries exports without injection", async () => {+ it("a map without arrows or summaries exports without label injection", async () => {const mind = initRealMindMap({nodeData: { id: "root", topic: "Just a root", children: [] }});const result = await renderMindMapPreviewSvg(mind);+ const rawExport = await mind.exportSvg().text();expect(result).toContain("Just a root");- expect(result).not.toContain("foreignObject><div"); // no injected labels- expect(await mind.exportSvg().text()).toBe(result);+ // Post-processing must not add foreignObjects beyond the exporter's own+ // (it only resizes them).+ const countForeignObjects = (svg: string) => new DOMParser()+ .parseFromString(svg, "image/svg+xml").querySelectorAll("foreignObject").length;+ expect(countForeignObjects(result)).toBe(countForeignObjects(rawExport));});});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.tsindex 46e8c87761..3700e5a9eb 100644--- a/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts+++ b/apps/client/src/widgets/type_widgets/helpers/mind_map_export.ts@@ -14,7 +14,8 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";* 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.+ * previously generated with snapdom). {@link postProcessExportedSvg} re-adds them and+ * relaxes the exporter's exact-fit text boxes so rasterization cannot clip them.** Note that upstream considers `exportSvg()` deprecated in favor of DOM screenshot* libraries and will not fix the label gap (see@@ -27,29 +28,35 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";*/export async function renderMindMapPreviewSvg(mind: MindElixirInstance): Promise<string> {const svgText = await mind.exportSvg().text();- return injectSvgLabels(mind, svgText);+ return postProcessExportedSvg(mind, svgText);}+// The exporter emits exact-fit foreignObject boxes: the text's measured width in the+// page's font, to the third decimal, with `white-space: pre-wrap`. Any context that+// resolves fonts even fractionally wider — PNG rasterization at scale, an <img> on a+// machine with different fonts — soft-wraps the text and the exact-fit height clips the+// wrapped line ("Hi there" renders as "Hi"). The boxes are invisible and the text is+// left-anchored, so widening them slightly is visually free.+const SIZE_SLACK_RATIO = 1.02;+const SIZE_SLACK_PX = 2;+/**- * Re-adds the arrow/summary labels missing from mind-elixir's `exportSvg()` output.+ * Post-processes mind-elixir's `exportSvg()` output to make it robust and complete:*- * 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.+ * - Re-adds the arrow/summary labels the exporter misses. 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.+ * - Adds slack to every `<foreignObject>`'s exact-fit size so text is not clipped when+ * the SVG is rasterized with slightly different font metrics (see the slack constants).** @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.+ * @returns the post-processed SVG, or the input unchanged if 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;- }-+export function postProcessExportedSvg(mind: MindElixirInstance, svgText: string): string {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.@@ -58,13 +65,27 @@ export function injectSvgLabels(mind: MindElixirInstance, svgText: string): strireturn svgText;}+ const labels = mind.nodes.querySelectorAll<HTMLElement>(".svg-label");for (const label of Array.from(labels)) {contentSvg.appendChild(doc.importNode(buildLabelForeignObject(label), true));}+ for (const foreignObject of Array.from(doc.querySelectorAll("foreignObject"))) {+ addSizeSlack(foreignObject, "width");+ addSizeSlack(foreignObject, "height");+ }+return new XMLSerializer().serializeToString(doc);}+function addSizeSlack(element: Element, attribute: "width" | "height") {+ const value = Number.parseFloat(element.getAttribute(attribute) ?? "");+ if (!Number.isFinite(value) || value <= 0) {+ return;+ }+ element.setAttribute(attribute, String(Math.ceil(value * SIZE_SLACK_RATIO + SIZE_SLACK_PX)));+}+/*** Builds a `<foreignObject>` mirroring an on-screen `.svg-label` element, carrying* over its box (position, size, background, border radius) and text styling. Built in@@ -76,15 +97,15 @@ function buildLabelForeignObject(label: HTMLElement): SVGElement {// The computed width/height carry the fractional used value, but degrade to "auto" when the// element is not rendered (e.g. a hidden tab) — fall back to the always-numeric offset size- // then. Round up so the foreignObject is never narrower than the text it must fit.+ // then. The anti-clipping slack is applied later by the shared foreignObject pass.const width = Number.parseFloat(style.width) || label.offsetWidth;const height = Number.parseFloat(style.height) || label.offsetHeight;const foreignObject = document.createElementNS(SVG_NS, "foreignObject");foreignObject.setAttribute("x", String(label.offsetLeft));foreignObject.setAttribute("y", String(label.offsetTop));- foreignObject.setAttribute("width", String(Math.ceil(width)));- foreignObject.setAttribute("height", String(Math.ceil(height)));+ foreignObject.setAttribute("width", String(width));+ foreignObject.setAttribute("height", String(height));const div = document.createElementNS(XHTML_NS, "div") as HTMLElement;div.setAttribute("style",