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
refactor(client): export SVG/PNG from rendered SVG, drop snapdom dependency
Elian Doran44f852b016f1
diff --git a/apps/client/package.json b/apps/client/package.jsonindex 423b61d25c..348bac720b 100644--- a/apps/client/package.json+++ b/apps/client/package.json@@ -43,7 +43,6 @@"@univerjs/preset-sheets-note": "0.25.1","@univerjs/preset-sheets-sort": "0.25.1","@univerjs/presets": "0.25.1",- "@zumer/snapdom": "2.15.0","autocomplete.js": "0.38.1","bootstrap": "5.3.8","boxicons": "2.1.4",diff --git a/apps/client/src/services/utils.spec.ts b/apps/client/src/services/utils.spec.tsindex 52b0ba1a6f..784cf58e6e 100644--- a/apps/client/src/services/utils.spec.ts+++ b/apps/client/src/services/utils.spec.ts@@ -31,16 +31,6 @@ import utils, {toggleBodyClass} from "./utils.js";-// `snapdom` is used by downloadAsSvg / downloadAsPng; stub it so no real rendering happens.-vi.mock("@zumer/snapdom", () => ({- snapdom: vi.fn(async () => ({- url: "data:image/svg+xml;base64,AAA",- toPng: vi.fn(async () => ({ src: "data:image/png;base64,BBB" }))- }))-}));--import { snapdom } from "@zumer/snapdom";-// `logInfo` / `logError` are normally attached to window/globalThis by ws.ts, which is mocked// out by the test setup. Provide no-op globals so the few code paths that log don't crash.beforeEach(() => {@@ -674,34 +664,55 @@ describe("createImageSrcUrl", () => {});});-describe("snapdom downloads (default export)", () => {- it("downloadAsSvg parses an SVG string with the SVG mime type, renders it and triggers a download", async () => {- const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});- // happy-dom's image/svg+xml documentElement lacks a writable `.style`, so return a real- // HTML element from the parser while still asserting the SVG mime branch was taken.- const parseSpy = vi.spyOn(DOMParser.prototype, "parseFromString").mockImplementation(() => {- const doc = document.implementation.createHTMLDocument("");- return doc;+describe("SVG downloads (default export)", () => {+ function captureDownload() {+ const downloads: { name: string | null, href: string | null }[] = [];+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function(this: HTMLAnchorElement) {+ downloads.push({ name: this.getAttribute("download"), href: this.getAttribute("href") });+ });+ return downloads;+ }++ it("downloadSvg downloads the SVG string as a data URL", () => {+ const downloads = captureDownload();+ 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>`);+ });++ it("downloadSvgAsPng rasterizes at the given scale and downloads a PNG", async () => {+ const downloads = captureDownload();+ const drawImage = vi.fn();+ const canvasSizes: { width: number, height: number }[] = [];+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({ drawImage } as unknown as RenderingContext);+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockImplementation(function(this: HTMLCanvasElement) {+ canvasSizes.push({ width: this.width, height: this.height });+ return "data:image/png;base64,BBB";+ });+ vi.stubGlobal("Image", class {+ src = "";+ decode = vi.fn(async () => {});});- await utils.downloadAsSvg("diagram", " <svg><rect/></svg>");- expect(parseSpy).toHaveBeenCalledWith(" <svg><rect/></svg>", "image/svg+xml");- expect(snapdom).toHaveBeenCalled();- expect(clickSpy).toHaveBeenCalled();- });- it("downloadAsSvg accepts an existing element without attaching it", async () => {- const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});- const el = document.createElement("div");- await utils.downloadAsSvg("diagram", el);- expect(snapdom).toHaveBeenCalled();- expect(clickSpy).toHaveBeenCalled();+ try {+ await utils.downloadSvgAsPng("diagram", `<svg width="100" height="50"></svg>`);+ } finally {+ vi.unstubAllGlobals();+ }++ 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" }]);});- it("downloadAsPng renders an HTML string to PNG and downloads it", async () => {- const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});- await utils.downloadAsPng("diagram", "<div>hello</div>");- expect(snapdom).toHaveBeenCalled();- expect(clickSpy).toHaveBeenCalled();+ it("downloadSvgAsPng rejects when the SVG has no usable dimensions", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ await expect(utils.downloadSvgAsPng("diagram", `<svg xmlns="http://www.w3.org/2000/svg"/>`))+ .rejects.toThrow("dimensions");});});diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 0b3711c235..b769200a31 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -610,65 +610,14 @@ export function createImageSrcUrl(note: FNote) {/**- * Helper function to prepare an element for snapdom rendering.- * Handles string parsing and temporary DOM attachment for style computation.- *- * @param source - Either an SVG/HTML string to be parsed, or an existing SVG/HTML element.- * @returns An object containing the prepared element and a cleanup function.- * The cleanup function removes temporarily attached elements from the DOM,- * or is a no-op if the element was already in the DOM.- */-function prepareElementForSnapdom(source: string | SVGElement | HTMLElement): {- element: SVGElement | HTMLElement;- cleanup: () => void;-} {- if (typeof source === 'string') {- const parser = new DOMParser();-- // Detect if content is SVG or HTML- const isSvg = source.trim().startsWith('<svg');- const mimeType = isSvg ? SVG_MIME : 'text/html';-- const doc = parser.parseFromString(source, mimeType);- const element = doc.documentElement;-- // Temporarily attach to DOM for proper style computation- element.style.position = 'absolute';- element.style.left = '-9999px';- element.style.top = '-9999px';- document.body.appendChild(element);-- return {- element,- cleanup: () => document.body.removeChild(element)- };- }-- return {- element: source,- cleanup: () => {} // No-op for existing elements- };-}--/**- * Downloads an SVG using snapdom for proper rendering. Can accept either an SVG string, an SVG element, or an HTML element.+ * Given a string representation of an SVG, triggers a download of the file on the client device.** @param nameWithoutExtension the name of the file. The .svg suffix is automatically added to it.- * @param svgSource either an SVG string, an SVGElement, or an HTMLElement to be downloaded.+ * @param svgContent the content of the SVG file to download.*/-async function downloadAsSvg(nameWithoutExtension: string, svgSource: string | SVGElement | HTMLElement) {- const { snapdom } = await import("@zumer/snapdom");- const { element, cleanup } = prepareElementForSnapdom(svgSource);-- try {- const result = await snapdom(element, {- backgroundColor: "transparent",- scale: 2- });- triggerDownload(`${nameWithoutExtension}.svg`, result.url);- } finally {- cleanup();- }+function downloadSvg(nameWithoutExtension: string, svgContent: string) {+ const dataUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`;+ triggerDownload(`${nameWithoutExtension}.svg`, dataUrl);}/**@@ -690,32 +639,51 @@ function triggerDownload(fileName: string, dataUrl: string) {document.body.removeChild(element);}/**- * Downloads an SVG as PNG using snapdom. Can accept either an SVG string, an SVG element, or an HTML element.+ * Given a string representation of an SVG, rasterizes it to PNG and triggers a download of the+ * file on the client device.+ *+ * The SVG must carry usable dimensions (numeric `width`/`height` attributes or a `viewBox`).+ * Note that rasterization happens in the browser's SVG-as-image context: document fonts are not+ * applied (only system fonts resolve) and external resources referenced by the SVG are not+ * loaded, so any embedded images must use data URLs.** @param nameWithoutExtension the name of the file. The .png suffix is automatically added to it.- * @param svgSource either an SVG string, an SVGElement, or an HTMLElement to be converted to PNG.+ * @param svgContent the content of the SVG file to rasterize.+ * @param scale the rasterization scale factor (2 doubles the resolution).*/-async function downloadAsPng(nameWithoutExtension: string, svgSource: string | SVGElement | HTMLElement) {- const { snapdom } = await import("@zumer/snapdom");- const { element, cleanup } = prepareElementForSnapdom(svgSource);+async function downloadSvgAsPng(nameWithoutExtension: string, svgContent: string, scale = 2) {+ const size = getSizeFromSvg(svgContent);+ if (!size) {+ throw new Error("Could not determine the dimensions of the SVG.");+ }- try {- const result = await snapdom(element, {- backgroundColor: "transparent",- scale: 2- });- const pngImg = await result.toPng();- await triggerDownload(`${nameWithoutExtension}.png`, pngImg.src);- } finally {- cleanup();+ // Decode through an <img> element — the browser's own SVG renderer.+ const image = new Image();+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgContent)}`;+ await image.decode();++ const canvas = document.createElement("canvas");+ canvas.width = Math.round(size.width * scale);+ canvas.height = Math.round(size.height * scale);+ const context = canvas.getContext("2d");+ if (!context || !canvas.width || !canvas.height) {+ throw new Error("The SVG has no drawable dimensions.");}+ context.drawImage(image, 0, 0, canvas.width, canvas.height);++ triggerDownload(`${nameWithoutExtension}.png`, canvas.toDataURL("image/png"));}export function getSizeFromSvg(svgContent: string) {const svgDocument = (new DOMParser()).parseFromString(svgContent, SVG_MIME);- // Try to use width & height attributes if available.+ // Try to use width & height attributes if available. Relative units (e.g. mermaid's+ // width="100%") carry no absolute size, so fall through to the viewBox for those.let width = svgDocument.documentElement?.getAttribute("width");let height = svgDocument.documentElement?.getAttribute("height");+ if (width?.includes("%") || height?.includes("%")) {+ width = null;+ height = null;+ }// If not, use the viewbox.if (!width || !height) {@@ -728,10 +696,10 @@ export function getSizeFromSvg(svgContent: string) {}if (width && height) {- return {- width: parseFloat(width),- height: parseFloat(height)- };+ const size = { width: parseFloat(width), height: parseFloat(height) };+ if (Number.isFinite(size.width) && Number.isFinite(size.height)) {+ return size;+ }}console.warn("SVG export error", svgDocument.documentElement);return null;@@ -926,8 +894,8 @@ export default {areObjectsEqual,copyHtmlToClipboard,createImageSrcUrl,- downloadAsSvg,- downloadAsPng,+ downloadSvg,+ downloadSvgAsPng,triggerDownload,compareVersions,isUpdateAvailable,diff --git a/apps/client/src/widgets/type_widgets/MindMap.tsx b/apps/client/src/widgets/type_widgets/MindMap.tsxindex 9901d45e48..28c0b64b42 100644--- a/apps/client/src/widgets/type_widgets/MindMap.tsx+++ b/apps/client/src/widgets/type_widgets/MindMap.tsx@@ -143,13 +143,12 @@ 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 nodes = apiRef.current.nodes;+ const svg = await renderMindMapPreviewSvg(apiRef.current);if (eventName === "exportSvg") {- await utils.downloadAsSvg(note.title, nodes);+ utils.downloadSvg(note.title, svg);} else {- await utils.downloadAsPng(note.title, nodes);+ await utils.downloadSvgAsPng(note.title, svg);}-});const onKeyDown = useCallback((e: KeyboardEvent) => {diff --git a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsxindex 4e4978eae1..4e90b48dbc 100644--- a/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx+++ b/apps/client/src/widgets/type_widgets/helpers/SvgSplitEditor.tsx@@ -89,14 +89,13 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvg}).catch(e => console.error("Failed to get attachments for SVGSplitEditor", e));}, [ note, svg, attachmentTitle, onSave ]);- // Import/export- useTriliumEvent("exportSvg", async({ ntxId: eventNtxId }) => {+ // Import/export. The renderer's `svg` string is exported rather than the on-screen element,+ // which svg-pan-zoom has wrapped in a viewport transform reflecting the current pan/zoom.+ useTriliumEvent("exportSvg", ({ ntxId: eventNtxId }) => {if (eventNtxId !== ntxId || !svg) return;try {- const svgEl = containerRef.current?.querySelector("svg");- if (!svgEl) throw new Error("SVG element not found");- await utils.downloadAsSvg(note.title, svgEl);+ utils.downloadSvg(note.title, svg);} catch (e) {console.warn(e);toast.showError(t("svg.export_to_svg"));@@ -106,9 +105,7 @@ export default function SvgSplitEditor({ ntxId, note, attachmentTitle, renderSvguseTriliumEvent("exportPng", async ({ ntxId: eventNtxId }) => {if (eventNtxId !== ntxId || !svg) return;try {- const svgEl = containerRef.current?.querySelector("svg");- if (!svgEl) throw new Error("SVG element not found");- await utils.downloadAsPng(note.title, svgEl);+ await utils.downloadSvgAsPng(note.title, svg);} catch (e) {console.warn(e);toast.showError(t("svg.export_to_png"));diff --git a/apps/standalone/package.json b/apps/standalone/package.jsonindex b1d0810f58..075aaba1eb 100644--- a/apps/standalone/package.json+++ b/apps/standalone/package.json@@ -34,7 +34,6 @@"@triliumnext/highlightjs": "workspace:*","@triliumnext/share-theme": "workspace:*","@triliumnext/split.js": "workspace:*",- "@zumer/snapdom": "2.15.0","autocomplete.js": "0.38.1","bootstrap": "5.3.8","boxicons": "2.1.4",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f00821cf33..7c7f3e35cc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -275,9 +275,6 @@ importers:'@univerjs/presets':specifier: 0.25.1- '@zumer/snapdom':- specifier: 2.15.0- version: 2.15.0autocomplete.js:specifier: 0.38.1version: 0.38.1@@ -882,9 +879,6 @@ importers:'@triliumnext/split.js':specifier: workspace:*version: link:../../packages/splitjs- '@zumer/snapdom':- specifier: 2.15.0- version: 2.15.0aes-js:specifier: 3.1.2version: 3.1.2@@ -6679,9 +6673,6 @@ packages:resolution: {integrity: sha512-RQ4h9F6DOiHxpdocUDrOl6xBM+yOtz+LkUol47AVWcfebGBDpZ7w7Xvz9PS24JgXvLGiXXzSAfdCdVy1tPlaFA==}engines: {bun: '>=0.7.0', deno: '>=1.0.0', node: '>=18.0.0'}- '@zumer/[email protected]':- resolution: {integrity: sha512-rdayfg832lYhy2v2DRr4LwzhIT0ZMeGKYicVmtzbji95KhUd7Z1g6/5jTsDEU4q32a6ywbIpAixO45hubsEftQ==}-resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==}@@ -20751,8 +20742,6 @@ snapshots:'@zip.js/[email protected]': {}- '@zumer/[email protected]': {}-