Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): address automated review feedback on SVG export

Elian Doran9b758b2e651a
diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.ts
index 784cf58e6e..46a4399e94 100644
--- a/apps/client/src/services/utils.spec.ts
+++ b/apps/client/src/services/utils.spec.ts
@@ -673,19 +673,30 @@ describe("SVG downloads (default export)", () => {
return downloads;
}
- it("downloadSvg downloads the SVG string as a data URL", () => {
+ function captureObjectUrls() {
+ const blobs: Blob[] = [];
+ vi.spyOn(URL, "createObjectURL").mockImplementation((blob) => {
+ blobs.push(blob as Blob);
+ return `blob:mock-${blobs.length}`;
+ });
+ vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
+ return blobs;
+ }
+
+ it("downloadSvg downloads the SVG string as a blob URL", async () => {
const downloads = captureDownload();
+ const blobs = captureObjectUrls();
utils.downloadSvg("diagram", `<svg><text>a & b</text></svg>`);
- expect(downloads).toHaveLength(1);
- expect(downloads[0].name).toBe("diagram.svg");
- const href = downloads[0].href ?? "";
- expect(href.startsWith("data:image/svg+xml;charset=utf-8,")).toBe(true);
- expect(decodeURIComponent(href.split(",")[1])).toBe(`<svg><text>a & b</text></svg>`);
+ expect(downloads).toEqual([ { name: "diagram.svg", href: "blob:mock-1" } ]);
+ expect(blobs).toHaveLength(1);
+ expect(blobs[0].type).toContain("image/svg+xml");
+ expect(await blobs[0].text()).toBe(`<svg><text>a & b</text></svg>`);
});
it("downloadSvgAsPng rasterizes at the given scale and downloads a PNG", async () => {
const downloads = captureDownload();
+ captureObjectUrls();
const drawImage = vi.fn();
const canvasSizes: { width: number, height: number }[] = [];
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage } as unknown as RenderingContext);
@@ -704,9 +715,9 @@ describe("SVG downloads (default export)", () => {
vi.unstubAllGlobals();
}
- expect(canvasSizes).toEqual([{ width: 200, height: 100 }]); // default scale is 2
+ expect(canvasSizes).toEqual([ { width: 200, height: 100 } ]); // default scale is 2
expect(drawImage).toHaveBeenCalled();
- expect(downloads).toEqual([{ name: "diagram.png", href: "data:image/png;base64,BBB" }]);
+ expect(downloads).toEqual([ { name: "diagram.png", href: "data:image/png;base64,BBB" } ]);
});
it("downloadSvgAsPng rejects when the SVG has no usable dimensions", async () => {
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.ts
index b769200a31..3ac2fafbad 100644
--- a/apps/client/src/services/utils.ts
+++ b/apps/client/src/services/utils.ts
@@ -616,8 +616,11 @@ export function createImageSrcUrl(note: FNote) {
* @param svgContent the content of the SVG file to download.
*/
function downloadSvg(nameWithoutExtension: string, svgContent: string) {
- const dataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`;
- triggerDownload(`${nameWithoutExtension}.svg`, dataUrl);
+ const blob = new Blob([ svgContent ], { type: "image/svg+xml;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
+ triggerDownload(`${nameWithoutExtension}.svg`, url);
+ // Defer revocation so the in-flight download isn't cancelled (as downloadImage in image.ts).
+ setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
/**
@@ -657,10 +660,17 @@ async function downloadSvgAsPng(nameWithoutExtension: string, svgContent: string
throw new Error("Could not determine the dimensions of the SVG.");
}
- // Decode through an <img> element — the browser's own SVG renderer.
+ // Decode through an <img> element — the browser's own SVG renderer. A blob URL avoids the
+ // encoding overhead and URL length limits of a data: URL for large diagrams.
+ const blob = new Blob([ svgContent ], { type: "image/svg+xml;charset=utf-8" });
+ const url = URL.createObjectURL(blob);
const image = new Image();
- image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`;
- await image.decode();
+ image.src = url;
+ try {
+ await image.decode();
+ } finally {
+ URL.revokeObjectURL(url);
+ }
const canvas = document.createElement("canvas");
canvas.width = Math.round(size.width * scale);
diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsx
index 28c0b64b42..111c150c5b 100644
--- a/apps/client/src/widgets/type_widgets/MindMap.tsx
+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx
@@ -12,6 +12,7 @@ import { HTMLAttributes, RefObject } from "preact";
import { useCallback, useEffect, useRef } from "preact/hooks";
import { sanitizeNoteContentHtml } from "../../services/sanitize_content";
+import toast from "../../services/toast";
import utils from "../../services/utils";
import { useColorScheme, useEditorSpacedUpdate, useEffectiveReadOnly, useSyncedRef, useTriliumEvent, useTriliumEvents, useTriliumOption } from "../react/hooks";
import { refToJQuerySelector } from "../react/react_utils";
@@ -143,11 +144,16 @@ export default function MindMap({ note, ntxId, noteContext }: TypeWidgetProps) {
// Export as PNG or SVG.
useTriliumEvents([ "exportSvg", "exportPng" ], async ({ ntxId: eventNtxId }, eventName) => {
if (eventNtxId !== ntxId || !apiRef.current) return;
- const svg = await renderMindMapPreviewSvg(apiRef.current);
- if (eventName === "exportSvg") {
- utils.downloadSvg(note.title, svg);
- } else {
- await utils.downloadSvgAsPng(note.title, svg);
+ try {
+ const svg = await renderMindMapPreviewSvg(apiRef.current);
+ if (eventName === "exportSvg") {
+ utils.downloadSvg(note.title, svg);
+ } else {
+ await utils.downloadSvgAsPng(note.title, svg);
+ }
+ } catch (e) {
+ console.warn(e);
+ toast.showError(t(eventName === "exportSvg" ? "svg.export_to_svg" : "svg.export_to_png"));
}
});
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
index c5bf6fc93b..46e8c87761 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
@@ -18,12 +18,12 @@ const XHTML_NS = "http://www.w3.org/1999/xhtml";
*
* 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.
+ * https://github.com/SSShooter/mind-elixir-core/issues/359) — but a screenshot pass is
+ * far too slow to run on every save (it once did, via snapdom — see #10478), so Trilium
+ * deliberately uses the native exporter everywhere: this helper also feeds the
+ * user-triggered SVG/PNG export actions in MindMap.tsx. If a future mind-elixir release
+ * removes `exportSvg()` (a loud, type-level break), vendor the exporter instead of
+ * switching back to a screenshot library.
*/
export async function renderMindMapPreviewSvg(mind: MindElixirInstance): Promise<string> {
const svgText = await mind.exportSvg().text();
@@ -74,11 +74,17 @@ export function injectSvgLabels(mind: MindElixirInstance, svgText: string): stri
function buildLabelForeignObject(label: HTMLElement): SVGElement {
const style = getComputedStyle(label);
+ // 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.
+ 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", style.width);
- foreignObject.setAttribute("height", style.height);
+ foreignObject.setAttribute("width", String(Math.ceil(width)));
+ foreignObject.setAttribute("height", String(Math.ceil(height)));
const div = document.createElementNS(XHTML_NS, "div") as HTMLElement;
div.setAttribute("style",