Virtual whiteboard for sketching hand-drawn like diagrams
feat(packages/excalidraw): replace the export functions with `exportScene` (#12347)
David Luzare1b7aacb356a
diff --git a/examples/with-script-in-browser/components/ExampleApp.tsx b/examples/with-script-in-browser/components/ExampleApp.tsxindex 8ee104f6d0..b336c0662b 100644--- a/examples/with-script-in-browser/components/ExampleApp.tsx+++ b/examples/with-script-in-browser/components/ExampleApp.tsx@@ -80,9 +80,7 @@ export default function ExampleApp({excalidrawLib,}: AppProps) {const {- exportToCanvas,- exportToSvg,- exportToBlob,+ exportScene,exportToClipboard,useHandleLibrary,MIME_TYPES,@@ -115,6 +113,10 @@ export default function ExampleApp({const [canvasUrl, setCanvasUrl] = useState<string>("");const [exportWithDarkMode, setExportWithDarkMode] = useState(false);const [exportEmbedScene, setExportEmbedScene] = useState(false);+ const exportConfig = {+ theme: exportWithDarkMode ? "dark" : "light",+ padding: 10,+ } as const;const [theme, setTheme] = useState<Theme>("light");const [disableImageTool, setDisableImageTool] = useState(false);const [isCollaborating, setIsCollaborating] = useState(false);@@ -387,10 +389,12 @@ export default function ExampleApp({return false;}await exportToClipboard({- elements: excalidrawAPI.getSceneElements(),- appState: excalidrawAPI.getAppState(),- files: excalidrawAPI.getFiles(),type,+ data: {+ elements: excalidrawAPI.getSceneElements(),+ appState: excalidrawAPI.getAppState(),+ files: excalidrawAPI.getFiles(),+ },});window.alert(`Copied to clipboard as ${type} successfully`);};@@ -888,16 +892,14 @@ export default function ExampleApp({if (!excalidrawAPI) {return;}- const svg = await exportToSvg({- elements: excalidrawAPI?.getSceneElements(),- appState: {- ...initialData.appState,- exportWithDarkMode,- exportEmbedScene,- width: 300,- height: 100,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: excalidrawAPI.getSceneElements(),+ appState: initialData.appState,+ files: excalidrawAPI.getFiles(),},- files: excalidrawAPI?.getFiles(),+ config: { ...exportConfig, embedScene: exportEmbedScene },});appRef.current.querySelector(".export-svg").innerHTML =svg.outerHTML;@@ -912,15 +914,14 @@ export default function ExampleApp({if (!excalidrawAPI) {return;}- const blob = await exportToBlob({- elements: excalidrawAPI?.getSceneElements(),- mimeType: "image/png",- appState: {- ...initialData.appState,- exportEmbedScene,- exportWithDarkMode,+ const blob = await exportScene({+ type: "png",+ data: {+ elements: excalidrawAPI.getSceneElements(),+ appState: initialData.appState,+ files: excalidrawAPI.getFiles(),},- files: excalidrawAPI?.getFiles(),+ config: { ...exportConfig, embedScene: exportEmbedScene },});setBlobUrl(window.URL.createObjectURL(blob));}}@@ -935,13 +936,14 @@ export default function ExampleApp({if (!excalidrawAPI) {return;}- const canvas = await exportToCanvas({- elements: excalidrawAPI.getSceneElements(),- appState: {- ...initialData.appState,- exportWithDarkMode,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: excalidrawAPI.getSceneElements(),+ appState: initialData.appState,+ files: excalidrawAPI.getFiles(),},- files: excalidrawAPI.getFiles(),+ config: exportConfig,});const ctx = canvas.getContext("2d")!;ctx.font = "30px Excalifont";@@ -956,13 +958,14 @@ export default function ExampleApp({if (!excalidrawAPI) {return;}- const canvas = await exportToCanvas({- elements: excalidrawAPI.getSceneElements(),- appState: {- ...initialData.appState,- exportWithDarkMode,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: excalidrawAPI.getSceneElements(),+ appState: initialData.appState,+ files: excalidrawAPI.getFiles(),},- files: excalidrawAPI.getFiles(),+ config: exportConfig,});const ctx = canvas.getContext("2d")!;ctx.font = "30px Excalifont";diff --git a/excalidraw-app/components/AI.tsx b/excalidraw-app/components/AI.tsxindex 9a4472f107..cc8b28cb9c 100644--- a/excalidraw-app/components/AI.tsx+++ b/excalidraw-app/components/AI.tsx@@ -1,12 +1,12 @@import {DiagramToCodePlugin,- exportToBlob,+ exportScene,getNonDeletedElements,getTextFromElements,- MIME_TYPES,parseSSEStream,TTDDialog,TTDStreamFetch,+ THEME,} from "@excalidraw/excalidraw";import { getDataURL } from "@excalidraw/excalidraw/data/blob";import { safelyParseJSON } from "@excalidraw/common";@@ -34,16 +34,17 @@ export const AIComponents = ({);}- const blob = await exportToBlob({- elements: getNonDeletedElements(children),- appState: {- ...appState,- exportBackground: true,- viewBackgroundColor: appState.viewBackgroundColor,+ const blob = await exportScene({+ type: "jpeg",+ data: {+ elements: getNonDeletedElements(children),+ appState,+ files: excalidrawAPI.getFiles(),+ },+ config: {+ exportingFrame: frame,+ theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,},- exportingFrame: frame,- files: excalidrawAPI.getFiles(),- mimeType: MIME_TYPES.jpg,});const dataURL = await getDataURL(blob);diff --git a/packages/element/tests/cropElement.test.tsx b/packages/element/tests/cropElement.test.tsxindex cab7fe35e7..1489e8cfa6 100644--- a/packages/element/tests/cropElement.test.tsx+++ b/packages/element/tests/cropElement.test.tsx@@ -3,11 +3,7 @@ import { vi } from "vitest";import { KEYS, cloneJSON } from "@excalidraw/common";-import {- Excalidraw,- exportToCanvas,- exportToSvg,-} from "@excalidraw/excalidraw";+import { Excalidraw, exportScene } from "@excalidraw/excalidraw";import {actionFlipHorizontal,actionFlipVertical,@@ -532,23 +528,33 @@ describe("Cropping and other features", async () => {Keyboard.keyDown(KEYS.ESCAPE);const widthToHeightRatio = image.width / image.height;- const canvas = await exportToCanvas({- elements: [image],- // @ts-ignore- appState: h.state,- files: h.app.files,- exportPadding: 0,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: [image],+ // @ts-ignore+ appState: h.state,+ files: h.app.files,+ },+ config: {+ padding: 0,+ },});const exportedCanvasRatio = canvas.width / canvas.height;expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);- const svg = await exportToSvg({- elements: [image],- // @ts-ignore- appState: h.state,- files: h.app.files,- exportPadding: 0,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: [image],+ // @ts-ignore+ appState: h.state,+ files: h.app.files,+ },+ config: {+ padding: 0,+ },});const svgWidth = svg.getAttribute("width");const svgHeight = svg.getAttribute("height");diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.mdindex cd4eab1f51..ab3b75908a 100644--- a/packages/excalidraw/CHANGELOG.md+++ b/packages/excalidraw/CHANGELOG.md@@ -13,6 +13,33 @@ Please add the latest change on the top under the correct section.## Unreleased+### Export API: `exportScene` (2026-10-18) [#12347](https://github.com/excalidraw/excalidraw/pull/12347)++Breaking. `exportToCanvas`, `exportToBlob` and `exportToSvg` (in both `@excalidraw/excalidraw` and `@excalidraw/utils`) are replaced by a single `exportScene`, and every rendering option moved from `appState` into an explicit `config`.++- `exportScene({ type, data, config })` with `type` `"canvas"`, `"png"`, `"jpeg"` or `"svg"` resolves to an `HTMLCanvasElement`, a `Blob` or an `SVGSVGElement`. `exportToClipboard({ type: "png" | "svg" | "json", data, config })` stays. Types: `ExportSceneData`, `ExportSceneConfig`, `ExportSceneOptions`.+- `data` is `{ elements, appState?, files? }`, the shape of a `.excalidraw` file. Only the scene settings a file stores are read from `appState`: `viewBackgroundColor` as the default background, and the grid settings that `embedScene` embeds. Any other key is ignored, so passing a live `appState` can't affect the output.+- Migration:++ | Before | Now |+ | --- | --- |+ | `exportToCanvas({ elements, appState, files, … })` | `exportScene({ type: "canvas", data: { elements, appState, files }, config })` |+ | `exportToBlob({ …, mimeType, quality })` | `exportScene({ type: "png" \| "jpeg", …, config })` — `quality` is JPEG-only |+ | `exportToSvg({ … })` | `exportScene({ type: "svg", … })` |+ | `appState.exportBackground: false` | `config.canvasBackgroundColor: false` (a color string overrides the background; JPEG always gets one) |+ | `appState.exportWithDarkMode` | `config.theme: "dark"` |+ | `appState.exportScale` | `config.scale` (also multiplies a `maxWidthOrHeight` result) |+ | `appState.exportEmbedScene` | `config.embedScene` (png, svg) |+ | `appState.frameRendering` | `config.frames: { name?, outline?, clip? }` |+ | `exportPadding` | `config.padding` (default 10, as before) |+ | `getDimensions: (w, h) => ({ width, height, scale })` | `config.width`/`height`, `maxWidthOrHeight` or `widthOrHeight`, plus `config.scale` — a number, or `(width, height) => number` receiving the export size at scale 1 (padding included), e.g. to cap the output by a pixel budget |+ | `maxWidthOrHeight`, `exportingFrame`, `renderEmbeddables`, `skipInliningFonts`, `reuseImages` | same names, in `config` |++- New sizing options: `width`/`height` (only one given: the other follows the content's aspect ratio), `widthOrHeight` (scales the longest side to exactly that size), `fit: "contain" | "none"` and `position: "center" | "topLeft"` within a `width`/`height` frame, and `x`/`y`/`origin` to export a region (cropped, with padding on all sides). The size options are mutually exclusive in the types, and `fit`, `position` and `x`/`y` only combine with `width`/`height`.+- `config.environment` for non-browser hosts: `createCanvas` (e.g. `node-canvas`) and `loadFonts`.+- Canvas dimensions are rounded instead of truncated, so float noise no longer costs a pixel (a 20.5px frame-label band now rounds up), and are at least 1px (flat content with no padding used to produce an empty canvas that couldn't be encoded).+- In dark exports, frame names now use the editor's dark frame-name color (they were dark-filtered twice and came out lighter).+### Selection API (2026-10-10) [#12258](https://github.com/excalidraw/excalidraw/pull/12258)- New `excalidrawAPI.selection`: `select(elements, opts?)`, `add(elements, opts?)`, `remove(elements, opts?)` and `clear(opts?)`, taking elements or their ids, one or many. Missing and deleted elements are skipped.@@ -20,12 +47,12 @@ Please add the latest change on the top under the correct section.- Options: `deep` selects the elements themselves rather than their groups, editing their group if they share one (as Ctrl/Cmd+click does); `includeLocked` selects locked elements too; `captureUpdate` records the change for undo as for `updateScene()` — by default it's recorded along with the next undoable change.- Like `updateScene()`, the change applies on the next render: read it back through `onChange()` or `getAppState()` after that. It works in view mode too, where the selection shows without the transform handles.-### Wheel navigation (2026-09-13) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)+### Wheel navigation (2026-09-13) [#12099](https://github.com/excalidraw/excalidraw/pull/12099)- Scrolling while holding the wheel (middle) mouse button zooms the canvas around the pointer, the same as ctrl/cmd+wheel — a wheel-button pan can be zoomed one-handed, without reaching for a modifier.- New `appState.inputDevice` preference (`"auto" | "mouse" | "trackpad"`, default `"auto"`, persisted in browser storage) selecting the wheel mappings. With `"trackpad"` a plain wheel pans; with `"mouse"` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is delivered) zooms with either device. Shift+wheel pans horizontally, and ctrl/cmd+shift+wheel pans vertically. The wheel-button zoom above is unaffected. `"auto"` is reserved for detecting the device from the wheel events and resolves to `"trackpad"` until that is implemented (`resolveInputDevice()`). Set it from the new "Input device" radio in the main menu's preferences submenu, also exposed as `MainMenu.DefaultItems.Preferences.InputDevice`.-### Sticky notes (2026-09-06) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)+### Sticky notes (2026-09-06) [#12064](https://github.com/excalidraw/excalidraw/pull/12064)- New `stickynote` element type and toolbar tool (`N`): an always-filled, flat-rendered note whose label auto-fits — the font shrinks from the user's size down to a minimum, and only then does the note grow in height (it never shrinks below the height the user gave it). Click to place a 250×250 note, drag to size it (previewed at the dragged size, snapped to a font-aware minimum on release); text editing starts right away.- Element model: the note carries `baseHeight` (the user's height; `height ≥ baseHeight`), its label carries `baseFontSize` (the user's font ceiling, `null`/absent on any other text) while `fontSize` holds the fitted size. Read a text element's user-facing size through `getBaseFontSize(text, elementsMap)`.@@ -38,11 +65,11 @@ Please add the latest change on the top under the correct section.## Excalidraw API-### `setViewport` stops following a collaborator (2026-09-26) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)+### `setViewport` stops following a collaborator (2026-09-26) [#12184](https://github.com/excalidraw/excalidraw/pull/12184)- `setViewport` now asks to stop following a collaborator whenever it navigates (`onUserFollow` with `action: "UNFOLLOW"`, if `userToFollow` is set), as a user's pan or zoom does. `setViewport(null)` (clearing a lock) and a target that doesn't resolve don't navigate, and leave following alone.-### `onDuplicate` can replace and veto duplicates (2026-09-18) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)+### `onDuplicate` can replace and veto duplicates (2026-09-18) [#12124](https://github.com/excalidraw/excalidraw/pull/12124)- `props.onDuplicate` may now return new objects for the duplicated elements in every duplication path. Previously the editor kept using the objects it created, so on paste (and library insert) the frame assignment and bound text redraw went to objects that were no longer in the scene, and alt-drag dragged an element that wasn't in the scene. The returned changes are now merged into the editor's duplicates, so they're part of the duplication's own undo entry and durable increment (no follow-up `updateScene` needed).- When pasting or inserting onto a frame, the duplicates passed to `onDuplicate` already have their `frameId` set (and are ordered under the frame).diff --git a/packages/excalidraw/actions/actionClipboard.tsx b/packages/excalidraw/actions/actionClipboard.tsxindex df5a261730..a1ed98d2b6 100644--- a/packages/excalidraw/actions/actionClipboard.tsx+++ b/packages/excalidraw/actions/actionClipboard.tsx@@ -152,7 +152,6 @@ export const actionCopyAsSvg = register({appState,app.files,{- ...appState,exportingFrame,name: app.getName(),},@@ -219,7 +218,6 @@ export const actionCopyAsPng = register({);try {await exportCanvas("clipboard", exportedElements, appState, app.files, {- ...appState,exportingFrame,name: app.getName(),});diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex 57fbd75f3b..18c06ac8c6 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -2771,9 +2771,7 @@ class App extends React.Component<AppProps, AppState> {this.state,this.files,{- exportBackground: this.state.exportBackground,name: this.getName(),- viewBackgroundColor: this.state.viewBackgroundColor,exportingFrame: opts.exportingFrame,},)diff --git a/packages/excalidraw/components/ImageExportDialog.tsx b/packages/excalidraw/components/ImageExportDialog.tsxindex 48afbaa966..5d0e2bc137 100644--- a/packages/excalidraw/components/ImageExportDialog.tsx+++ b/packages/excalidraw/components/ImageExportDialog.tsx@@ -1,4 +1,3 @@-import { exportToCanvas } from "@excalidraw/utils/export";import React, { useEffect, useRef, useState } from "react";import {@@ -26,6 +25,7 @@ import { useCopyStatus } from "../hooks/useCopiedIndicator";import { t } from "../i18n";import { isSomeElementSelected } from "../scene";+import { exportScene, getExportConfigFromAppState } from "../scene/export";import { copyIcon, downloadIcon, helpIcon } from "./icons";import { Dialog } from "./Dialog";@@ -127,20 +127,25 @@ const ImageExportModal = ({return requestId !== previewRenderRequestIdRef.current;};- exportToCanvas({- elements: exportedElements,- appState: {- ...appStateSnapshot,- name: projectName,- exportBackground: exportWithBackground,- exportWithDarkMode,- exportScale,- exportEmbedScene: embedScene,+ exportScene({+ type: "canvas",+ data: {+ elements: exportedElements,+ appState: appStateSnapshot,+ files,+ },+ config: {+ ...getExportConfigFromAppState({+ ...appStateSnapshot,+ exportBackground: exportWithBackground,+ exportWithDarkMode,+ // the preview fits `maxWidthOrHeight`+ exportScale: 1,+ }),+ padding: DEFAULT_EXPORT_PADDING,+ maxWidthOrHeight: Math.max(maxWidth, maxHeight),+ exportingFrame,},- files,- exportPadding: DEFAULT_EXPORT_PADDING,- maxWidthOrHeight: Math.max(maxWidth, maxHeight),- exportingFrame,}).then(async (canvas) => {if (isStaleRequest()) {diff --git a/packages/excalidraw/components/PasteChartDialog.tsx b/packages/excalidraw/components/PasteChartDialog.tsxindex 19c3271766..596afc59df 100644--- a/packages/excalidraw/components/PasteChartDialog.tsx+++ b/packages/excalidraw/components/PasteChartDialog.tsx@@ -7,7 +7,7 @@ import type { ChartType } from "@excalidraw/element/types";import { trackEvent } from "../analytics";import { isSpreadsheetValidForChartType, renderSpreadsheet } from "../charts";import { t } from "../i18n";-import { exportToSvg } from "../scene/export";+import { exportScene } from "../scene/export";import { useUIAppState } from "../context/ui-appState";@@ -72,18 +72,18 @@ const ChartPreviewBtn = (props: {const previewNode = previewRef.current!;(async () => {- svg = await exportToSvg(- elements,- {- exportBackground: false,- viewBackgroundColor: "#fff",- exportWithDarkMode: theme === "dark",+ svg = await exportScene({+ type: "svg",+ data: {+ elements,+ files: null,},- null, // files- {+ config: {skipInliningFonts: true,+ theme,+ canvasBackgroundColor: false,},- );+ });svg.querySelector(".style-fonts")?.remove();previewNode.replaceChildren();previewNode.appendChild(svg);@@ -134,18 +134,18 @@ const PlainTextPreviewBtn = (props: {const previewNode = previewRef.current!;(async () => {- const svg = await exportToSvg(- [textElement],- {- exportBackground: false,- viewBackgroundColor: "#fff",- exportWithDarkMode: theme === "dark",+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: [textElement],+ files: null,},- null,- {+ config: {skipInliningFonts: true,+ theme,+ canvasBackgroundColor: false,},- );+ });svg.querySelector(".style-fonts")?.remove();previewNode.replaceChildren();previewNode.appendChild(svg);diff --git a/packages/excalidraw/components/PublishLibrary.tsx b/packages/excalidraw/components/PublishLibrary.tsxindex c9376895da..40e9c524b5 100644--- a/packages/excalidraw/components/PublishLibrary.tsx+++ b/packages/excalidraw/components/PublishLibrary.tsx@@ -1,10 +1,10 @@-import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";import { useCallback, useEffect, useRef, useState } from "react";import {EDITOR_LS_KEYS,EXPORT_DATA_TYPES,MIME_TYPES,+ THEME,VERSIONS,chunk,getExportSource,@@ -13,6 +13,7 @@ import {import { EditorLocalStorage } from "../data/EditorLocalStorage";import { canvasToBlob, resizeImageFile } from "../data/blob";import { t } from "../i18n";+import { exportScene } from "../scene/export";import { Dialog } from "./Dialog";import DialogActionButton from "./DialogActionButton";@@ -62,10 +63,15 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {// draw items// ---------------------------------------------------------------------------for (const [index, item] of libraryItems.entries()) {- const itemCanvas = await exportToCanvas({- elements: item.elements,- files: null,- maxWidthOrHeight: BOX_SIZE,+ const itemCanvas = await exportScene({+ type: "canvas",+ data: {+ elements: item.elements,+ files: null,+ },+ config: {+ maxWidthOrHeight: BOX_SIZE,+ },});const { width, height } = itemCanvas;@@ -126,15 +132,17 @@ const SingleLibraryItem = ({return;}(async () => {- const svg = await exportToSvg({- elements: libItem.elements,- appState: {- ...appState,- viewBackgroundColor: "#fff",- exportBackground: true,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: libItem.elements,+ files: null,+ },+ config: {+ skipInliningFonts: true,+ canvasBackgroundColor: "#fff",+ theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,},- files: null,- skipInliningFonts: true,});node.innerHTML = svg.outerHTML;})();diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.tsindex 6f92f99702..acf38dac9a 100644--- a/packages/excalidraw/components/TTDDialog/common.ts+++ b/packages/excalidraw/components/TTDDialog/common.ts@@ -1,12 +1,8 @@-import {- DEFAULT_EXPORT_PADDING,- EDITOR_LS_KEYS,- THEME,-} from "@excalidraw/common";+import { DEFAULT_EXPORT_PADDING, EDITOR_LS_KEYS } from "@excalidraw/common";import { convertToExcalidrawElements } from "@excalidraw/element";-import { exportToCanvas } from "@excalidraw/utils";+import { exportScene } from "@excalidraw/utils";import type {NonDeletedExcalidrawElement,@@ -104,15 +100,18 @@ export const convertMermaidToExcalidraw = async ({files,};- const canvas = await exportToCanvas({- elements: data.current.elements,- files: data.current.files,- exportPadding: DEFAULT_EXPORT_PADDING,- maxWidthOrHeight:- Math.max(parent.offsetWidth, parent.offsetHeight) *- window.devicePixelRatio,- appState: {- exportWithDarkMode: theme === THEME.DARK,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: data.current.elements,+ files: data.current.files,+ },+ config: {+ padding: DEFAULT_EXPORT_PADDING,+ maxWidthOrHeight:+ Math.max(parent.offsetWidth, parent.offsetHeight) *+ window.devicePixelRatio,+ theme,},});diff --git a/packages/excalidraw/data/index.ts b/packages/excalidraw/data/index.tsindex eef9d286f7..d98fc2ff51 100644--- a/packages/excalidraw/data/index.ts+++ b/packages/excalidraw/data/index.ts@@ -29,7 +29,7 @@ import {import { t } from "../i18n";import { getSelectedElements, isSomeElementSelected } from "../scene";-import { exportToCanvas, exportToSvg } from "../scene/export";+import { exportScene, getExportConfigFromAppState } from "../scene/export";import { canvasToBlob } from "./blob";import { fileSave } from "./filesystem";@@ -101,16 +101,12 @@ export const exportCanvas = async (appState: AppState,files: BinaryFiles,{- exportBackground,exportPadding = DEFAULT_EXPORT_PADDING,- viewBackgroundColor,name = appState.name || DEFAULT_FILENAME,fileHandle = null,exportingFrame = null,}: {- exportBackground: boolean;exportPadding?: number;- viewBackgroundColor: string;/** filename, if applicable */name?: string;fileHandle?: FileSystemFileHandle | null;@@ -120,20 +116,26 @@ export const exportCanvas = async (if (elements.length === 0) {throw new Error(t("alerts.cannotExportEmptyCanvas"));}++ const config = {+ ...getExportConfigFromAppState(appState),+ padding: exportPadding,+ exportingFrame,+ };+if (type === "svg" || type === "clipboard-svg") {- const svgPromise = exportToSvg(- elements,- {- exportBackground,- exportWithDarkMode: appState.exportWithDarkMode,- viewBackgroundColor,- exportPadding,- exportScale: appState.exportScale,- exportEmbedScene: appState.exportEmbedScene && type === "svg",+ const svgPromise = exportScene({+ type: "svg",+ data: {+ elements,+ appState,+ files,},- files,- { exportingFrame },- );+ config: {+ ...config,+ embedScene: appState.exportEmbedScene && type === "svg",+ },+ });if (type === "svg") {return fileSave(@@ -163,11 +165,14 @@ export const exportCanvas = async (}}- const tempCanvas = exportToCanvas(elements, appState, files, {- exportBackground,- viewBackgroundColor,- exportPadding,- exportingFrame,+ const tempCanvas = exportScene({+ type: "canvas",+ data: {+ elements,+ appState,+ files,+ },+ config,});if (type === "png") {diff --git a/packages/excalidraw/data/resave.ts b/packages/excalidraw/data/resave.tsindex abeeb16a68..aca88d9ebc 100644--- a/packages/excalidraw/data/resave.ts+++ b/packages/excalidraw/data/resave.ts@@ -28,8 +28,6 @@ export const resaveAsImageWithScene = async (let { elements, appState, files } = await data;- const { exportBackground, viewBackgroundColor } = appState;-appState = {...appState,exportEmbedScene: true,@@ -42,8 +40,6 @@ export const resaveAsImageWithScene = async ();await exportCanvas(fileHandleType, exportedElements, appState, files, {- exportBackground,- viewBackgroundColor,name: filename,fileHandle,exportingFrame,diff --git a/packages/excalidraw/hooks/useLibraryItemSvg.ts b/packages/excalidraw/hooks/useLibraryItemSvg.tsindex cb6d4dc325..f1ef7915ae 100644--- a/packages/excalidraw/hooks/useLibraryItemSvg.ts+++ b/packages/excalidraw/hooks/useLibraryItemSvg.ts@@ -1,7 +1,6 @@-import { exportToSvg } from "@excalidraw/utils/export";import { useEffect, useState } from "react";-import { COLOR_PALETTE } from "@excalidraw/common";+import { exportScene } from "../scene/export";import { atom, useAtom } from "../editor-jotai";@@ -12,17 +11,16 @@ export type SvgCache = Map<LibraryItem["id"], SVGSVGElement>;export const libraryItemSvgsCache = atom<SvgCache>(new Map());const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => {- // TODO should pass theme (appState.exportWithDark) - we're still using- // CSS filter here- return await exportToSvg({- elements,- appState: {- exportBackground: false,- viewBackgroundColor: COLOR_PALETTE.white,+ return await exportScene({+ type: "svg",+ data: {+ elements,+ files: null,+ },+ config: {+ skipInliningFonts: true,+ canvasBackgroundColor: false,},- files: null,- renderEmbeddables: false,- skipInliningFonts: true,});};diff --git a/packages/excalidraw/index-node.ts b/packages/excalidraw/index-node.tsindex 3b94991493..0249ba7eec 100644--- a/packages/excalidraw/index-node.ts+++ b/packages/excalidraw/index-node.ts@@ -1,5 +1,4 @@-import { getDefaultAppState } from "./appState";-import { exportToCanvas } from "./scene/export";+import { exportScene } from "./scene/export";const fs = require("fs");@@ -59,26 +58,24 @@ const elements = [registerFont("./public/Virgil.woff2", { family: "Virgil" });registerFont("./public/Cascadia.woff2", { family: "Cascadia" });-const canvas = exportToCanvas(- elements as any,- {- ...getDefaultAppState(),- offsetTop: 0,- offsetLeft: 0,- width: 0,- height: 0,- },- {}, // files- {- exportBackground: true,- viewBackgroundColor: "#ffffff",- },- createCanvas,-);+(async () => {+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: elements as any,+ appState: {},+ files: {},+ },+ config: {+ canvasBackgroundColor: "#ffffff",+ environment: { createCanvas },+ },+ });-const out = fs.createWriteStream("test.png");-const stream = (canvas as any).createPNGStream();-stream.pipe(out);-out.on("finish", () => {- console.info("test.png was created.");-});+ const out = fs.createWriteStream("test.png");+ const stream = (canvas as any).createPNGStream();+ stream.pipe(out);+ out.on("finish", () => {+ console.info("test.png was created.");+ });+})();diff --git a/packages/excalidraw/index.tsx b/packages/excalidraw/index.tsxindex 217c4e782a..3f66b76367 100644--- a/packages/excalidraw/index.tsx+++ b/packages/excalidraw/index.tsx@@ -421,12 +421,13 @@ export {export { reconcileElements } from "./data/reconcile";-export {- exportToCanvas,- exportToBlob,- exportToSvg,- exportToClipboard,-} from "@excalidraw/utils/export";+export { exportScene, exportToClipboard } from "./scene/export";++export type {+ ExportSceneData,+ ExportSceneConfig,+ ExportSceneOptions,+} from "./scene/export";export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";export {diff --git a/packages/excalidraw/renderer/staticScene.ts b/packages/excalidraw/renderer/staticScene.tsindex 65cfeb3d5b..4307e502ba 100644--- a/packages/excalidraw/renderer/staticScene.ts+++ b/packages/excalidraw/renderer/staticScene.ts@@ -325,6 +325,18 @@ const _renderStaticScene = ({);}+ if (renderConfig.clipToFrame) {+ const frame = renderConfig.clipToFrame;+ context.beginPath();+ context.rect(+ frame.x + appState.scrollX,+ frame.y + appState.scrollY,+ frame.width,+ frame.height,+ );+ context.clip();+ }+const groupsToBeAddedToFrame = new Set<string>();visibleElements.forEach((element) => {diff --git a/packages/excalidraw/scene/export.ts b/packages/excalidraw/scene/export.tsindex 9216e42722..84300e9c01 100644--- a/packages/excalidraw/scene/export.ts+++ b/packages/excalidraw/scene/export.ts@@ -1,24 +1,27 @@import rough from "roughjs/bin/rough";import {- DEFAULT_EXPORT_PADDING,FRAME_STYLE,FONT_FAMILY,SVG_NS,THEME,MIME_TYPES,EXPORT_DATA_TYPES,+ COLOR_WHITE,+ DEFAULT_EXPORT_PADDING,arrayToMap,distance,getFontString,toBrandedType,applyDarkModeFilter,+ removeDarkModeFilter,} from "@excalidraw/common";import { getCommonBounds, getElementAbsoluteCoords } from "@excalidraw/element";import {getInitializedImageElements,+ getNonDeletedElements,updateImageCache,} from "@excalidraw/element";@@ -39,28 +42,52 @@ import { type Mutable } from "@excalidraw/common/utility-types";import { newTextElement } from "@excalidraw/element";-import type { Bounds } from "@excalidraw/common";-import type {ExcalidrawFrameLikeElement,ExcalidrawTextElement,NonDeleted,NonDeletedExcalidrawElement,NonDeletedSceneElementsMap,+ Theme,} from "@excalidraw/element/types";-import { getDefaultAppState } from "../appState";+import { cleanAppStateForExport } from "../appState";import { base64ToString, decode, encode, stringToBase64 } from "../data/encode";import { serializeAsJSON } from "../data/json";+import { restoreAppState, restoreElements } from "../data/restore";+import { encodePngMetadata } from "../data/image";import { Fonts } from "../fonts";import { renderStaticScene } from "../renderer/staticScene";import { renderSceneToSvg } from "../renderer/staticSvgScene";+import {+ copyBlobToClipboardAsPng,+ copyTextToSystemClipboard,+ copyToClipboard,+} from "../clipboard";+import type { RenderableElementsMap } from "./types";-import type { AppState, BinaryFiles } from "../types";+import type { AppState, BinaryFiles, NormalizedZoomValue } from "../types";++// Default minimum export size in pixels+const DEFAULT_SMALLEST_EXPORT_SIZE = 20;++/**+ * Padding is taken from the target size when fitting into one: keep at least+ * `DEFAULT_SMALLEST_EXPORT_SIZE` of each target dimension for the content.+ */+const clampPadding = (padding: number, targets: readonly number[]) =>+ Math.max(+ 0,+ Math.min(+ padding,+ ...targets.map((target) => (target - DEFAULT_SMALLEST_EXPORT_SIZE) / 2),+ ),+ );+const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;const truncateText = (element: NonDeleted<ExcalidrawTextElement>,@@ -82,9 +109,9 @@ const truncateText = (if (metrics.width > maxWidth) {// we iterate from the right, removing characters one by one instead- // of bulding the string up. This assumes that it's more likely+ // of building the string up. This assumes that it's more likely// your frame names will overflow by not that many characters- // (if ever), so it sohuld be faster this way.+ // (if ever), so it should be faster this way.for (let i = text.length; i > 0; i--) {const newText = `${text.slice(0, i)}...`;if (ctx.measureText(newText).width <= maxWidth) {@@ -104,7 +131,7 @@ const truncateText = (*/const addFrameLabelsAsTextElements = (elements: readonly NonDeletedExcalidrawElement[],- opts: Pick<AppState, "exportWithDarkMode">,+ opts: { theme: Theme },) => {const nextElements: NonDeletedExcalidrawElement[] = [];for (const element of elements) {@@ -117,9 +144,13 @@ const addFrameLabelsAsTextElements = (fontSize: FRAME_STYLE.nameFontSize,lineHeight:FRAME_STYLE.nameLineHeight as ExcalidrawTextElement["lineHeight"],- strokeColor: opts.exportWithDarkMode- ? FRAME_STYLE.nameColorDarkTheme- : FRAME_STYLE.nameColorLightTheme,+ strokeColor:+ opts.theme === THEME.DARK+ ? // the renderer applies the dark mode filter to element+ // colors, so revert it upfront to end up with the color+ // the editor uses for frame names+ removeDarkModeFilter(FRAME_STYLE.nameColorDarkTheme)+ : FRAME_STYLE.nameColorLightTheme,text: getFrameLikeTitle(element),});textElement.y -= textElement.height;@@ -136,27 +167,24 @@ const addFrameLabelsAsTextElements = (const getFrameRenderingConfig = (exportingFrame: ExcalidrawFrameLikeElement | null,- frameRendering: AppState["frameRendering"] | null,-): AppState["frameRendering"] => {- frameRendering = frameRendering || getDefaultAppState().frameRendering;- return {- enabled: exportingFrame ? true : frameRendering.enabled,- outline: exportingFrame ? false : frameRendering.outline,- name: exportingFrame ? false : frameRendering.name,- clip: exportingFrame ? true : frameRendering.clip,- };-};+ frames: ExportSceneBaseConfig["frames"],+): AppState["frameRendering"] => ({+ enabled: true,+ outline: exportingFrame ? false : frames?.outline ?? true,+ name: exportingFrame ? false : frames?.name ?? true,+ clip: exportingFrame ? true : frames?.clip ?? true,+});const prepareElementsForRender = ({elements,exportingFrame,frameRendering,- exportWithDarkMode,+ theme,}: {elements: readonly NonDeletedExcalidrawElement[];exportingFrame: ExcalidrawFrameLikeElement | null | undefined;frameRendering: AppState["frameRendering"];- exportWithDarkMode: AppState["exportWithDarkMode"];+ theme: Theme;}) => {let nextElements: readonly NonDeletedExcalidrawElement[];@@ -167,9 +195,7 @@ const prepareElementsForRender = ({arrayToMap(elements),);} else if (frameRendering.enabled && frameRendering.name) {- nextElements = addFrameLabelsAsTextElements(elements, {- exportWithDarkMode,- });+ nextElements = addFrameLabelsAsTextElements(elements, { theme });} else {nextElements = elements;}@@ -177,43 +203,328 @@ const prepareElementsForRender = ({return nextElements;};-export const exportToCanvas = async (- elements: readonly NonDeletedExcalidrawElement[],- appState: AppState,- files: BinaryFiles,- {- exportBackground,- exportPadding = DEFAULT_EXPORT_PADDING,- viewBackgroundColor,- exportingFrame,- }: {- exportBackground: boolean;- exportPadding?: number;- viewBackgroundColor: string;- exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;- },- createCanvas: (- width: number,- height: number,- ) => { canvas: HTMLCanvasElement; scale: number } = (width, height) => {- const canvas = document.createElement("canvas");- canvas.width = width * appState.exportScale;- canvas.height = height * appState.exportScale;- return { canvas, scale: appState.exportScale };- },- loadFonts: () => Promise<void> = async () => {- await Fonts.loadElementsFonts(elements);- },-) => {- // load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)- await loadFonts();+// ---------------------------------------------------------------------------+// Types for the new API+// ---------------------------------------------------------------------------++export type ExportSceneData = {+ elements: readonly NonDeletedExcalidrawElement[];+ /**+ * The scene settings a `.excalidraw` file stores (`viewBackgroundColor`,+ * grid settings) — not editor state. Used as the default background+ * (`canvasBackgroundColor`) and embedded with the scene (`embedScene`).+ * Anything else passed in is ignored; rendering options go to `config`.+ */+ appState?: ReturnType<typeof cleanAppStateForExport>;+ files?: BinaryFiles | null;+};++type ExportEnvironment = {+ /**+ * Creates the canvas to export into.+ *+ * Do not set `canvas.width/height` or modify the canvas context as that's+ * handled by Excalidraw.+ *+ * Defaults to `document.createElement("canvas")`.+ */+ createCanvas?: () => HTMLCanvasElement;+ /**+ * Loads the fonts the exported elements use, before rendering.+ *+ * Defaults to loading them through the browser's+ * [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace).+ */+ loadFonts?: () => Promise<void>;+};++type ExportSceneBaseConfig = {+ /**+ * @default "light"+ */+ theme?: Theme;+ /**+ * Canvas background. Valid values are:+ *+ * - `undefined` - the background of "appState.viewBackgroundColor" is used.+ * - `false` - no background is used (transparent). Not supported for JPEG,+ * which falls back to the default.+ * - `string` - should be a valid CSS color.+ *+ * Specified in light-theme terms: `theme: "dark"` transforms it like any+ * other scene color. Only affects the rendered image, not the embedded+ * scene (`embedScene`).+ *+ * @default undefined+ */+ canvasBackgroundColor?: string | false;+ /**+ * Canvas padding in pixels. Affected by `scale`.+ *+ * When `fit` is `none`, padding is added around the content bounding box,+ * or around the `width`/`height` frame if set — in which case the content+ * may overflow the frame, thus right or bottom padding may be ignored.+ *+ * When `fit` is `contain`, or `maxWidthOrHeight`/`widthOrHeight` is set,+ * padding is subtracted from the target size (so the export doesn't exceed+ * it, `scale` aside), and serves as a minimum distance between the content+ * and the canvas edges — it may be exceeded on one axis to maintain the+ * aspect ratio. It is recommended to set `position` to `center` when using+ * `fit: "contain"`.+ *+ * @default 10+ */+ padding?: number;+ // -------------------------------------------------------------------------+ /**+ * A multiplier to increase/decrease the frame dimensions+ * (content resolution).+ *+ * For example, if your canvas is 300x150 and you set scale to 2, the+ * resulting size will be 600x300.+ *+ * Can be a function, which receives the export dimensions at scale 1+ * (padding included) and returns the multiplier — e.g. to cap the output+ * by a pixel budget.+ *+ * @default 1+ */+ scale?: number | ((width: number, height: number) => number);+ /**+ * Host environment overrides, e.g. for test environments or Node.js.+ */+ environment?: ExportEnvironment;++ exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;+ /**+ * Which frame decorations to render. Ignored when exporting a single frame+ * (`exportingFrame`), which renders neither its name nor outline, and clips+ * to it.+ *+ * @default { name: true, outline: true, clip: true }+ */+ frames?: { name?: boolean; outline?: boolean; clip?: boolean };+};++/**+ * The ways to size the export — only one can be used. The positioning options+ * (`fit`, `position`, `x`, `y`, `origin`) belong to `width`/`height` (or no+ * size option).+ */+type ExportSizeOptions = {+ /**+ * Makes sure the canvas content fits into a frame of width/height no larger+ * than this value, while maintaining the aspect ratio.+ *+ * Final dimensions can get smaller/larger if used in conjunction with+ * `scale`.+ *+ * Can't be combined with `width`/`height`, `widthOrHeight`, or the+ * positioning options (`fit`, `position`, `x`, `y`, `origin`).+ */+ maxWidthOrHeight?: number;+ /**+ * Scale the canvas content to be exactly this many pixels wide/tall,+ * maintaining the aspect ratio.+ *+ * Final dimensions can get smaller/larger if used in conjunction with+ * `scale`.+ *+ * Can't be combined with `width`/`height`, `maxWidthOrHeight`, or the+ * positioning options (`fit`, `position`, `x`, `y`, `origin`).+ */+ widthOrHeight?: number;+ /**+ * Width of the frame. Supply `x` or `y` if you want to offset the canvas+ * content.+ *+ * If `width` omitted but `height` supplied, `width` is calculated from the+ * content's aspect ratio when `fit` is `contain` (the default), or is the+ * content bounding box width when `fit` is `none`.+ *+ * Defaults to the content bounding box width when both `width` and `height`+ * are omitted.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`.+ */+ width?: number;+ /**+ * Height of the frame.+ *+ * If `height` omitted but `width` supplied, `height` is calculated from the+ * content's aspect ratio when `fit` is `contain` (the default), or is the+ * content bounding box height when `fit` is `none`.+ *+ * Defaults to the content bounding box height when both `width` and `height`+ * are omitted.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`.+ */+ height?: number;+ // -------------------------------------------------------------------------+ /**+ * Left edge of the exported region (`padding` is added around it). By+ * default the coordinate is relative to the canvas. You can switch to+ * content coordinates by setting `origin` to `content`.+ *+ * Defaults to the `x` position of the content bounding box.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`, and is+ * ignored with `fit: "contain"`, so setting `x` or `y` makes `fit` default+ * to `none` (cropping the region).+ */+ x?: number;+ /**+ * Top edge of the exported region (`padding` is added around it). By+ * default the coordinate is relative to the canvas. You can switch to+ * content coordinates by setting `origin` to `content`.+ *+ * Defaults to the `y` position of the content bounding box.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`, and is+ * ignored with `fit: "contain"`, so setting `x` or `y` makes `fit` default+ * to `none` (cropping the region).+ */+ y?: number;+ /**+ * Indicates the coordinate system of the `x` and `y` values.+ *+ * - `canvas` - `x` and `y` are relative to the canvas [0, 0] position.+ * - `content` - `x` and `y` are relative to the content bounding box.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`.+ *+ * @default "canvas"+ */+ origin?: "canvas" | "content";+ /**+ * How the content should be scaled into the `width`/`height` frame.+ *+ * Behavior aligns with the `object-fit` CSS property.+ *+ * - `none` - no scaling.+ * - `contain` - scale to fit the frame. Includes `padding`.+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`.+ *+ * @default "contain" if `width` or `height` is set (and `x`/`y` aren't),+ * otherwise "none"+ */+ fit?: "none" | "contain";+ /**+ * When either `x` or `y` are not specified, indicates how the canvas should+ * be aligned on the respective axis.+ *+ * - `topLeft` - canvas aligned to top left.+ * - `center` - canvas is centered on the axis which is not specified+ * (or both).+ *+ * Can't be combined with `maxWidthOrHeight` or `widthOrHeight`.+ *+ * @default "center"+ */+ position?: "center" | "topLeft";+};++type ExportSizeOption<K extends keyof ExportSizeOptions> = Pick<+ ExportSizeOptions,+ K+> & {+ // remapping over `keyof` (rather than `Exclude<keyof …>`) keeps the+ // properties' JSDoc in editor hovers & completions+ [P in keyof ExportSizeOptions as P extends K ? never : P]?: never;+};++type ExportSizeConfig =+ | ExportSizeOption<+ "width" | "height" | "fit" | "position" | "x" | "y" | "origin"+ >+ | ExportSizeOption<"maxWidthOrHeight">+ | ExportSizeOption<"widthOrHeight">;++export type ExportSceneConfig = ExportSceneBaseConfig & ExportSizeConfig;++/**+ * The export config the editor's export settings translate to. Internal: hosts+ * pass their own config.+ */+export const getExportConfigFromAppState = (+ appState: Pick<+ AppState,+ | "exportWithDarkMode"+ | "exportBackground"+ | "viewBackgroundColor"+ | "exportScale"+ | "frameRendering"+ >,+) => ({+ theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,+ canvasBackgroundColor: appState.exportBackground+ ? appState.viewBackgroundColor+ : (false as const),+ scale: appState.exportScale,+ frames: appState.frameRendering.enabled+ ? appState.frameRendering+ : { name: false, outline: false, clip: false },+});++// ---------------------------------------------------------------------------+// Internal helper to configure export dimensions+// ---------------------------------------------------------------------------++const configExportDimension = async ({+ data,+ config,+}: {+ data: ExportSceneData;+ config?: ExportSceneConfig;+}) => {+ // clone (widened, as the size options get normalized below)+ const cfg: ExportSceneBaseConfig & ExportSizeOptions = Object.assign(+ {},+ config,+ );++ const { exportingFrame } = cfg;++ // restore elements (normalizes & drops invisible elements) and filter out+ // deleted ones. The type contract requires non-deleted elements already,+ // but types alone don't protect JS consumers passing raw scene data.+ // These are also what SVG export embeds (`embedScene`).+ const elements = getNonDeletedElements(+ restoreElements(data.elements, null, { deleteInvisibleElements: true }),+ );++ // initialize defaults+ // ---------------------------------------------------------------------------++ // only the scene settings a file stores are taken from `data.appState`, so+ // that editor state passed in (e.g. a live AppState) can't affect the+ // output; everything else the renderers read is a default+ const appState = restoreAppState(+ cleanAppStateForExport(data.appState ?? {}),+ null,+ );++ const theme = cfg.theme ?? THEME.LIGHT;++ // the background the scene is rendered against. Used even when the+ // background isn't painted, to fake holes in elements (e.g. outline+ // arrowheads covering the arrow's shaft), so they keep looking the same.+ const backgroundColor =+ cfg.canvasBackgroundColor || appState.viewBackgroundColor || COLOR_WHITE;+ // "transparent" = no background (also when the scene's background is set+ // to transparent)+ const paintedBackgroundColor =+ cfg.canvasBackgroundColor === false ? "transparent" : backgroundColor;const frameRendering = getFrameRenderingConfig(exportingFrame ?? null,- appState.frameRendering ?? null,+ cfg.frames,);- // for canvas export, don't clip if exporting a specific frame as it would- // clip the corners of the content+ // when exporting a frame, everything drawn is clipped to the frame as a+ // whole, with square corners (see `exportToCanvas`/`exportToSvg`) — the+ // per-element frame clips would round the corners of the contentif (exportingFrame) {frameRendering.clip = false;}@@ -221,29 +532,272 @@ export const exportToCanvas = async (const elementsForRender = prepareElementsForRender({elements,exportingFrame,- exportWithDarkMode: appState.exportWithDarkMode,+ theme,frameRendering,});if (exportingFrame) {- exportPadding = 0;+ cfg.padding = 0;+ }++ // treat non-positive dimension constraints as unset (matches the previous+ // API behavior where `maxWidthOrHeight: 0` was ignored), otherwise they'd+ // result in degenerate (zero/negative) canvas dimensions+ if (cfg.maxWidthOrHeight != null && cfg.maxWidthOrHeight <= 0) {+ cfg.maxWidthOrHeight = undefined;+ }+ if (cfg.widthOrHeight != null && cfg.widthOrHeight <= 0) {+ cfg.widthOrHeight = undefined;+ }++ // an explicit `x`/`y` region is cropped rather than scaled by default+ cfg.fit =+ cfg.fit ??+ (cfg.x == null &&+ cfg.y == null &&+ (cfg.width != null ||+ cfg.height != null ||+ cfg.maxWidthOrHeight != null ||+ cfg.widthOrHeight != null)+ ? "contain"+ : "none");++ cfg.padding = cfg.padding ?? DEFAULT_EXPORT_PADDING;++ cfg.origin = cfg.origin ?? "canvas";+ cfg.position = cfg.position ?? "center";++ if (cfg.maxWidthOrHeight != null && cfg.widthOrHeight != null) {+ if (!import.meta.env.PROD) {+ console.warn("`maxWidthOrHeight` is ignored when `widthOrHeight` is set");+ }+ cfg.maxWidthOrHeight = undefined;+ }++ if (+ (cfg.x != null || cfg.y != null) &&+ (cfg.fit === "contain" ||+ cfg.maxWidthOrHeight != null ||+ cfg.widthOrHeight != null)+ ) {+ if (!import.meta.env.PROD) {+ console.warn(+ '`x`/`y` are ignored when the content is scaled to fit (`fit: "contain"`, `maxWidthOrHeight`, or `widthOrHeight`)',+ );+ }+ cfg.x = undefined;+ cfg.y = undefined;+ }++ // ---------------------------------------------------------------------------++ // load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)+ if (cfg.environment?.loadFonts) {+ await cfg.environment.loadFonts();+ } else {+ await Fonts.loadElementsFonts(elements);}- const [minX, minY, width, height] = getCanvasSize(+ // value used to scale the canvas context. By default, we use this to+ // make the canvas fit into the frame (e.g. for `cfg.fit` set to `contain`).+ // If `cfg.scale` is set, we multiply the resulting canvasScale by it to+ // scale the output further.+ let exportScale = 1;++ const origCanvasSize = getCanvasSize(exportingFrame ? [exportingFrame] : getRootElements(elementsForRender),- exportPadding,);- const { canvas, scale = 1 } = createCanvas(width, height);+ // variables for original content bounding box+ const [origX, origY, origWidth, origHeight] = origCanvasSize;+ // variables for target bounding box+ let [x, y, width, height] = origCanvasSize;++ x = cfg.x ?? x;+ y = cfg.y ?? y;+ width = cfg.width ?? width;+ height = cfg.height ?? height;++ // clamp against the target being fitted into (not the content: a flat+ // content axis mustn't zero the padding), before deriving from it+ if (cfg.widthOrHeight != null) {+ cfg.padding = clampPadding(cfg.padding, [cfg.widthOrHeight]);+ } else if (cfg.maxWidthOrHeight != null) {+ cfg.padding = clampPadding(cfg.padding, [cfg.maxWidthOrHeight]);+ } else if (cfg.fit === "contain") {+ cfg.padding = clampPadding(+ cfg.padding,+ cfg.width != null || cfg.height != null+ ? [cfg.width, cfg.height].filter((size): size is number => size != null)+ : [width, height],+ );+ }++ // with `contain`, derive a missing `width`/`height` from the content's+ // aspect ratio (keeping the padding the same on all sides)+ if (cfg.fit === "contain") {+ if (cfg.width != null && cfg.height == null && origWidth > 0) {+ height =+ ((cfg.width - cfg.padding * 2) * origHeight) / origWidth ++ cfg.padding * 2;+ } else if (cfg.height != null && cfg.width == null && origHeight > 0) {+ width =+ ((cfg.height - cfg.padding * 2) * origWidth) / origHeight ++ cfg.padding * 2;+ }+ }++ if (cfg.maxWidthOrHeight != null || cfg.widthOrHeight != null) {+ if (cfg.padding) {+ if (cfg.maxWidthOrHeight != null) {+ cfg.maxWidthOrHeight -= cfg.padding * 2;+ } else if (cfg.widthOrHeight != null) {+ cfg.widthOrHeight -= cfg.padding * 2;+ }+ }++ const max = Math.max(width, height);+ if (cfg.widthOrHeight != null) {+ // calculate by how much do we need to scale the canvas to fit into the+ // target dimension (e.g. target: max 50px, actual: 70x100px => scale: 0.5)+ exportScale = cfg.widthOrHeight / max;+ } else if (cfg.maxWidthOrHeight != null) {+ exportScale = cfg.maxWidthOrHeight < max ? cfg.maxWidthOrHeight / max : 1;+ }++ width *= exportScale;+ height *= exportScale;+ } else if (cfg.fit === "contain") {+ width -= cfg.padding * 2;+ height -= cfg.padding * 2;++ // scale the orig canvas to fit in the target region (a content axis of+ // zero extent, e.g. a horizontal line's height, doesn't constrain it)+ exportScale = Math.min(+ origWidth > 0 ? width / origWidth : Infinity,+ origHeight > 0 ? height / origHeight : Infinity,+ );+ if (!Number.isFinite(exportScale)) {+ exportScale = 1;+ }+ }++ x = cfg.x ?? origX;+ y = cfg.y ?? origY;++ // if we switch to "content" coords, we need to offset cfg-supplied+ // coords by the x/y of content bounding box+ if (cfg.origin === "content") {+ if (cfg.x != null) {+ x += origX;+ }+ if (cfg.y != null) {+ y += origY;+ }+ }++ // Centering the content to the frame.+ // We divide width/height by canvasScale so that we calculate in the original+ // aspect ratio dimensions.+ // Only on the axes not pinned by `x`/`y`, so that a region gets padding on+ // all sides.+ if (cfg.position === "center") {+ if (cfg.x == null) {+ x -= width / exportScale / 2 - origWidth / 2;+ }+ if (cfg.y == null) {+ y -= height / exportScale / 2 - origHeight / 2;+ }+ }++ // rescale padding based on current canvasScale factor so that the resulting+ // padding is kept the same as supplied by user (with the exception of+ // `cfg.scale` being set, which also scales the padding)+ const normalizedPadding = cfg.padding / exportScale;++ // a `scale` function sizes the export by its dimensions at scale 1+ const scale =+ typeof cfg.scale === "function"+ ? cfg.scale(width + cfg.padding * 2, height + cfg.padding * 2)+ : cfg.scale ?? 1;++ // scale the whole frame by `scale` (on top of whatever canvasScale we+ // calculated above)+ exportScale *= scale;++ width *= scale;+ height *= scale;++ const exportWidth = width + cfg.padding * 2 * scale;+ const exportHeight = height + cfg.padding * 2 * scale;++ return {+ config: cfg,+ // the restored & non-deleted-filtered elements — use these (not+ // `data.elements`) for all rendering purposes+ elements,+ normalizedPadding,+ contentWidth: width,+ contentHeight: height,+ exportWidth,+ exportHeight,+ exportScale,+ x,+ y,+ elementsForRender,+ appState,+ frameRendering,+ backgroundColor,+ paintedBackgroundColor,+ theme,+ };+};++// ---------------------------------------------------------------------------+// exportToCanvas+// ---------------------------------------------------------------------------++const exportToCanvas = async ({+ data,+ config,+}: {+ data: ExportSceneData;+ config?: ExportSceneConfig;+}) => {+ const {+ config: cfg,+ elements,+ normalizedPadding,+ contentWidth: width,+ contentHeight: height,+ exportWidth,+ exportHeight,+ exportScale,+ x,+ y,+ elementsForRender,+ appState,+ frameRendering,+ backgroundColor,+ paintedBackgroundColor,+ theme,+ } = await configExportDimension({ data, config });- const defaultAppState = getDefaultAppState();+ const canvas = cfg.environment?.createCanvas+ ? cfg.environment.createCanvas()+ : document.createElement("canvas");++ // round rather than letting the canvas truncate, which would turn float+ // noise (e.g. 28.999999999999996) into a pixel lost+ canvas.width = Math.max(1, Math.round(exportWidth));+ canvas.height = Math.max(1, Math.round(exportHeight));const { imageCache } = await updateImageCache({imageCache: new Map(),fileIds: getInitializedImageElements(elementsForRender).map((element) => element.fileId,),- files,+ files: data.files || {},});renderStaticScene({@@ -256,19 +810,25 @@ export const exportToCanvas = async (arrayToMap(syncInvalidIndices(elements)),),visibleElements: elementsForRender,- scale,+ scale: exportScale,appState: {...appState,frameRendering,- viewBackgroundColor: exportBackground ? viewBackgroundColor : null,- scrollX: -minX + exportPadding,- scrollY: -minY + exportPadding,- zoom: defaultAppState.zoom,+ width,+ height,+ offsetLeft: 0,+ offsetTop: 0,+ scrollX: -x + normalizedPadding,+ scrollY: -y + normalizedPadding,+ zoom: { value: DEFAULT_ZOOM_VALUE },shouldCacheIgnoreZoom: false,- theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,+ theme,+ // "transparent" makes bootstrapCanvas clear the canvas+ viewBackgroundColor: paintedBackgroundColor,},renderConfig: {- canvasBackgroundColor: viewBackgroundColor,+ canvasBackgroundColor: backgroundColor,+ clipToFrame: cfg.exportingFrame ?? null,imageCache,renderGrid: false,isExporting: true,@@ -276,75 +836,79 @@ export const exportToCanvas = async (embedsValidationStatus: new Map(),elementsPendingErasure: new Set(),pendingFlowchartNodes: null,- theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,+ theme,},});return canvas;};-const createHTMLComment = (text: string) => {- // surrounding with spaces to maintain prettified consistency with previous- // iterations- // <!-- comment -->- return document.createComment(` ${text} `);-};--export const exportToSvg = async (- elements: readonly NonDeletedExcalidrawElement[],- appState: {- exportBackground: boolean;- exportPadding?: number;- exportScale?: number;- viewBackgroundColor: string;- exportWithDarkMode?: boolean;- exportEmbedScene?: boolean;- frameRendering?: AppState["frameRendering"];- },- files: BinaryFiles | null,- opts?: {+// ---------------------------------------------------------------------------+// exportToSvg+// ---------------------------------------------------------------------------++type ExportToSvgConfig = Pick<+ ExportSceneBaseConfig,+ | "canvasBackgroundColor"+ | "padding"+ | "theme"+ | "exportingFrame"+ | "scale"+ | "frames"+> &+ ExportSizeConfig & {+ /**+ * Host environment overrides, e.g. for test environments or Node.js.+ */+ environment?: Pick<ExportEnvironment, "loadFonts">;/*** if true, all embeddables passed in will be rendered when possible.*/renderEmbeddables?: boolean;- exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;skipInliningFonts?: true;reuseImages?: boolean;- },-): Promise<SVGSVGElement> => {- const frameRendering = getFrameRenderingConfig(- opts?.exportingFrame ?? null,- appState.frameRendering ?? null,- );-- let {- exportPadding = DEFAULT_EXPORT_PADDING,- exportWithDarkMode = false,- viewBackgroundColor,- exportScale = 1,- exportEmbedScene,- } = appState;+ /**+ * Embeds the scene into the SVG, so that it can be imported back into+ * Excalidraw.+ */+ embedScene?: boolean;+ };- const { exportingFrame = null } = opts || {};+const createHTMLComment = (text: string) => {+ // surrounding with spaces to maintain prettified consistency with previous+ // iterations+ // <!-- comment -->+ return document.createComment(` ${text} `);+};- const elementsForRender = prepareElementsForRender({+const exportToSvg = async ({+ data,+ config,+}: {+ data: ExportSceneData;+ config?: ExportToSvgConfig;+}) => {+ const {+ config: cfg,elements,- exportingFrame,- exportWithDarkMode,+ normalizedPadding,+ exportWidth,+ exportHeight,+ exportScale,+ x,+ y,+ elementsForRender,+ appState,frameRendering,- });+ backgroundColor,+ paintedBackgroundColor,+ theme,+ } = await configExportDimension({ data, config });- if (exportingFrame) {- exportPadding = 0;- }-- const [minX, minY, width, height] = getCanvasSize(- exportingFrame ? [exportingFrame] : getRootElements(elementsForRender),- exportPadding,- );+ const offsetX = -(x - normalizedPadding);+ const offsetY = -(y - normalizedPadding);- const offsetX = -minX + exportPadding;- const offsetY = -minY + exportPadding;+ const exportWithDarkMode = theme === THEME.DARK;// ---------------------------------------------------------------------------// initialize SVG root element@@ -354,9 +918,12 @@ export const exportToSvg = async (svgRoot.setAttribute("version", "1.1");svgRoot.setAttribute("xmlns", SVG_NS);- svgRoot.setAttribute("viewBox", `0 0 ${width} ${height}`);- svgRoot.setAttribute("width", `${width * exportScale}`);- svgRoot.setAttribute("height", `${height * exportScale}`);+ svgRoot.setAttribute(+ "viewBox",+ `0 0 ${exportWidth / exportScale} ${exportHeight / exportScale}`,+ );+ svgRoot.setAttribute("width", `${exportWidth}`);+ svgRoot.setAttribute("height", `${exportHeight}`);const defsElement = svgRoot.ownerDocument.createElementNS(SVG_NS, "defs");@@ -375,15 +942,16 @@ export const exportToSvg = async (// we need to serialize the "original" elements before we put them through// the tempScene hack which duplicates and regenerates ids- if (exportEmbedScene) {+ if (config?.embedScene) {try {encodeSvgBase64Payload({metadataElement,- // when embedding scene, we want to embed the origionally supplied- // elements which don't contain the temp frame labels.- // But it also requires that the exportToSvg is being supplied with- // only the elements that we're exporting, and no extra.- payload: serializeAsJSON(elements, appState, files || {}, "local"),+ // when embedding scene, we want to embed the (restored) supplied+ // elements which don't contain the temp frame labels. Restoring+ // keeps the ids stable. But it also requires that the exportToSvg is+ // being supplied with only the elements that we're exporting, and+ // no extra.+ payload: serializeAsJSON(elements, appState, data.files || {}, "local"),});} catch (error: any) {console.error(error);@@ -395,6 +963,13 @@ export const exportToSvg = async (// ---------------------------------------------------------------------------const frameElements = getFrameLikeElements(elements);+ const { exportingFrame } = cfg;+ if (+ exportingFrame &&+ !frameElements.some((frame) => frame.id === exportingFrame.id)+ ) {+ frameElements.push(exportingFrame);+ }if (frameElements.length) {const elementsMap = arrayToMap(elements);@@ -421,7 +996,7 @@ export const exportToSvg = async (rect.setAttribute("width", `${frame.width}`);rect.setAttribute("height", `${frame.height}`);- if (!exportingFrame) {+ if (!cfg.exportingFrame) {rect.setAttribute("rx", `${FRAME_STYLE.radius}`);rect.setAttribute("ry", `${FRAME_STYLE.radius}`);}@@ -436,9 +1011,10 @@ export const exportToSvg = async (// inline font faces// ---------------------------------------------------------------------------- const fontFaces = !opts?.skipInliningFonts- ? await Fonts.generateFontFaceDeclarations(elements)- : [];+ const fontFaces =+ config?.skipInliningFonts !== true+ ? await Fonts.generateFontFaceDeclarations(elements)+ : [];const delimiter = "\n "; // 6 spaces@@ -455,15 +1031,15 @@ export const exportToSvg = async (// ---------------------------------------------------------------------------// render background rect- if (appState.exportBackground && viewBackgroundColor) {+ if (paintedBackgroundColor !== "transparent") {const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");rect.setAttribute("x", "0");rect.setAttribute("y", "0");- rect.setAttribute("width", `${width}`);- rect.setAttribute("height", `${height}`);+ rect.setAttribute("width", `${exportWidth / exportScale}`);+ rect.setAttribute("height", `${exportHeight / exportScale}`);rect.setAttribute("fill",- applyDarkModeFilter(viewBackgroundColor, exportWithDarkMode),+ applyDarkModeFilter(paintedBackgroundColor, exportWithDarkMode),);svgRoot.appendChild(rect);}@@ -474,14 +1050,23 @@ export const exportToSvg = async (const rsvg = rough.svg(svgRoot);- const renderEmbeddables = opts?.renderEmbeddables ?? false;+ const renderEmbeddables = config?.renderEmbeddables ?? false;++ // when exporting a frame, clip everything drawn to it (its clip path has+ // square corners), as the export may be larger than the frame+ let elementsRoot: SVGElement = svgRoot;+ if (cfg.exportingFrame) {+ elementsRoot = svgRoot.ownerDocument.createElementNS(SVG_NS, "g");+ elementsRoot.setAttribute("clip-path", `url(#${cfg.exportingFrame.id})`);+ svgRoot.appendChild(elementsRoot);+ }renderSceneToSvg(elementsForRender,toBrandedType<RenderableElementsMap>(arrayToMap(elementsForRender)),rsvg,- svgRoot,- files || {},+ elementsRoot,+ data.files || {},{offsetX,offsetY,@@ -489,7 +1074,7 @@ export const exportToSvg = async (exportWithDarkMode,renderEmbeddables,frameRendering,- canvasBackgroundColor: viewBackgroundColor,+ canvasBackgroundColor: backgroundColor,embedsValidationStatus: renderEmbeddables? new Map(elementsForRender@@ -497,8 +1082,8 @@ export const exportToSvg = async (.map((element) => [element.id, true]),): new Map(),- reuseImages: opts?.reuseImages ?? true,- theme: exportWithDarkMode ? THEME.DARK : THEME.LIGHT,+ reuseImages: config?.reuseImages ?? true,+ theme,},);@@ -507,6 +1092,10 @@ export const exportToSvg = async (return svgRoot;};+// ---------------------------------------------------------------------------+// SVG payload encoding/decoding+// ---------------------------------------------------------------------------+export const encodeSvgBase64Payload = ({payload,metadataElement,@@ -562,26 +1151,153 @@ export const decodeSvgBase64Payload = ({ svg }: { svg: string }) => {throw new Error("INVALID");};+// ---------------------------------------------------------------------------+// getCanvasSize+// ---------------------------------------------------------------------------+// calculate smallest area to fit the contents inconst getCanvasSize = (elements: readonly NonDeletedExcalidrawElement[],- exportPadding: number,-): Bounds => {+): [x: number, y: number, width: number, height: number] => {const [minX, minY, maxX, maxY] = getCommonBounds(elements);- const width = distance(minX, maxX) + exportPadding * 2;- const height = distance(minY, maxY) + exportPadding * 2;+ const width = distance(minX, maxX);+ const height = distance(minY, maxY);return [minX, minY, width, height];};-export const getExportSize = (- elements: readonly NonDeletedExcalidrawElement[],- exportPadding: number,- scale: number,-): [number, number] => {- const [, , width, height] = getCanvasSize(elements, exportPadding).map(- (dimension) => Math.trunc(dimension * scale),- );+// ---------------------------------------------------------------------------+// exportToBlob+// ---------------------------------------------------------------------------++export { MIME_TYPES };++type ExportToPngConfig = ExportSceneConfig & {+ /**+ * Embeds the scene into the PNG metadata, so that it can be imported back+ * into Excalidraw.+ */+ embedScene?: boolean;+};++type ExportToJpegConfig = ExportSceneConfig & {+ /**+ * Encoding quality between 0 and 1.+ *+ * @default 0.92+ */+ quality?: number;+};++const exportToBlob = async (+ opts: { data: ExportSceneData } & (+ | { type: "png"; config?: ExportToPngConfig }+ | { type: "jpeg"; config?: ExportToJpegConfig }+ ),+): Promise<Blob> => {+ const { data } = opts;+ let config: ExportSceneConfig | undefined = opts.config;++ // JPEG has no alpha channel (transparent pixels would turn black)+ if (opts.type === "jpeg" && config?.canvasBackgroundColor === false) {+ console.warn(+ `"canvasBackgroundColor: false" is not supported for JPEG, using the default background`,+ );+ config = { ...config, canvasBackgroundColor: undefined };+ }++ const canvas = await exportToCanvas({ data, config });++ return new Promise((resolve, reject) => {+ canvas.toBlob(+ async (blob) => {+ if (!blob) {+ return reject(new Error("couldn't export to blob"));+ }+ if (opts.type === "png" && opts.config?.embedScene) {+ blob = await encodePngMetadata({+ blob,+ metadata: serializeAsJSON(+ // NOTE as long as we're using the Scene hack, we need to ensure+ // we pass the original, uncloned elements when serializing+ // so that we keep ids stable (restoring keeps the ids)+ restoreElements(data.elements, null),+ data.appState ?? {},+ data.files || {},+ "local",+ ),+ });+ }+ resolve(blob);+ },+ opts.type === "png" ? MIME_TYPES.png : MIME_TYPES.jpg,+ opts.type === "jpeg" ? opts.config?.quality || 0.92 : undefined,+ );+ });+};++// ---------------------------------------------------------------------------+// exportScene+// ---------------------------------------------------------------------------- return [width, height];+export type ExportSceneOptions = { data: ExportSceneData } & (+ | { type: "canvas"; config?: ExportSceneConfig }+ | { type: "png"; config?: ExportToPngConfig }+ | { type: "jpeg"; config?: ExportToJpegConfig }+ | { type: "svg"; config?: ExportToSvgConfig }+);++/**+ * Exports the scene to a canvas, a PNG or JPEG blob, or an SVG element.+ */+export function exportScene(+ opts: Extract<ExportSceneOptions, { type: "canvas" }>,+): Promise<HTMLCanvasElement>;+export function exportScene(+ opts: Extract<ExportSceneOptions, { type: "png" | "jpeg" }>,+): Promise<Blob>;+export function exportScene(+ opts: Extract<ExportSceneOptions, { type: "svg" }>,+): Promise<SVGSVGElement>;+export function exportScene(+ opts: ExportSceneOptions,+): Promise<HTMLCanvasElement | Blob | SVGSVGElement>;+export function exportScene(+ opts: ExportSceneOptions,+): Promise<HTMLCanvasElement | Blob | SVGSVGElement> {+ switch (opts.type) {+ case "canvas":+ return exportToCanvas(opts);+ case "png":+ case "jpeg":+ return exportToBlob(opts);+ case "svg":+ return exportToSvg(opts);+ }+}++// ---------------------------------------------------------------------------+// exportToClipboard+// ---------------------------------------------------------------------------++export const exportToClipboard = async (+ opts: { data: ExportSceneData } & (+ | { type: "png"; config?: ExportToPngConfig }+ | { type: "svg"; config?: ExportToSvgConfig }+ | { type: "json"; config?: never }+ ),+) => {+ if (opts.type === "svg") {+ const svg = await exportScene(opts);+ await copyTextToSystemClipboard(svg.outerHTML);+ } else if (opts.type === "png") {+ await copyBlobToClipboardAsPng(exportScene(opts));+ } else if (opts.type === "json") {+ await copyToClipboard(+ getNonDeletedElements(restoreElements(opts.data.elements, null)),+ opts.data.files ?? null,+ );+ } else {+ throw new Error("Invalid export type");+ }};diff --git a/packages/excalidraw/scene/types.ts b/packages/excalidraw/scene/types.tsindex 52d4439b32..eb2f507caa 100644--- a/packages/excalidraw/scene/types.ts+++ b/packages/excalidraw/scene/types.ts@@ -1,6 +1,7 @@import type { UserIdleState, EditorInterface } from "@excalidraw/common";import type {ExcalidrawElement,+ ExcalidrawFrameLikeElement,NonDeletedElementsMap,NonDeletedExcalidrawElement,NonDeletedSceneElementsMap,@@ -27,6 +28,8 @@ export type RenderableElementsMap = NonDeletedElementsMap &export type StaticCanvasRenderConfig = {canvasBackgroundColor: AppState["viewBackgroundColor"];+ /** export only: clips everything drawn to this frame (square corners) */+ clipToFrame?: ExcalidrawFrameLikeElement | null;// extra options passed to the renderer// ---------------------------------------------------------------------------imageCache: AppClassProperties["imageCache"];diff --git a/packages/excalidraw/tests/__snapshots__/MermaidToExcalidraw.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/MermaidToExcalidraw.test.tsx.snapindex f74342ad2f..c838f8a2f4 100644--- a/packages/excalidraw/tests/__snapshots__/MermaidToExcalidraw.test.tsx.snap+++ b/packages/excalidraw/tests/__snapshots__/MermaidToExcalidraw.test.tsx.snap@@ -1,6 +1,6 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html-exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active tool is mermaid 1`] = `"<div class="Modal Dialog ttd-dialog" role="dialog" aria-modal="true" aria-labelledby="dialog-title"><div class="Modal__background"></div><div class="Modal__content" style="--max-width: 1520px;" tabindex="0"><div class="Island"><div class="Dialog__content"><div dir="ltr" data-orientation="horizontal" class="ttd-dialog-tabs-root"><p class="dialog-mermaid-title">Mermaid to Excalidraw</p><div data-state="active" data-orientation="horizontal" role="tabpanel" aria-labelledby="radix-:r4:-trigger-mermaid" id="radix-:r4:-content-mermaid" tabindex="0" class="ttd-dialog-content"><div class="ttd-dialog-desc">Currently only <a href="https://mermaid.js.org/syntax/flowchart.html" target="_blank" rel="noreferrer">Flowchart</a>, <a href="https://mermaid.js.org/syntax/sequenceDiagram.html" target="_blank" rel="noreferrer">Sequence</a>, <a href="https://mermaid.js.org/syntax/classDiagram.html" target="_blank" rel="noreferrer">Class</a>, and <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" target="_blank" rel="noreferrer">Entity Relationship</a> Diagrams are supported. The other types will be rendered as image in Excalidraw.</div><div class="ttd-dialog-panels"><div class="ttd-dialog-panel"><div class="ttd-dialog-panel-button-container invisible" style="justify-content: flex-start;"></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-output-wrapper "><div class="ttd-dialog-output-canvas-container"><div class="ttd-dialog-output-canvas-content"><canvas width="89" height="158" dir="ltr"></canvas></div></div></div><div class="ttd-dialog-panel-button-container" style="justify-content: flex-start;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>"`;+exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active tool is mermaid 1`] = `"<div class="Modal Dialog ttd-dialog" role="dialog" aria-modal="true" aria-labelledby="dialog-title"><div class="Modal__background"></div><div class="Modal__content" style="--max-width: 1520px;" tabindex="0"><div class="Island"><div class="Dialog__content"><div dir="ltr" data-orientation="horizontal" class="ttd-dialog-tabs-root"><p class="dialog-mermaid-title">Mermaid to Excalidraw</p><div data-state="active" data-orientation="horizontal" role="tabpanel" aria-labelledby="radix-:r4:-trigger-mermaid" id="radix-:r4:-content-mermaid" tabindex="0" class="ttd-dialog-content"><div class="ttd-dialog-desc">Currently only <a href="https://mermaid.js.org/syntax/flowchart.html" target="_blank" rel="noreferrer">Flowchart</a>, <a href="https://mermaid.js.org/syntax/sequenceDiagram.html" target="_blank" rel="noreferrer">Sequence</a>, <a href="https://mermaid.js.org/syntax/classDiagram.html" target="_blank" rel="noreferrer">Class</a>, and <a href="https://mermaid.js.org/syntax/entityRelationshipDiagram.html" target="_blank" rel="noreferrer">Entity Relationship</a> Diagrams are supported. The other types will be rendered as image in Excalidraw.</div><div class="ttd-dialog-panels"><div class="ttd-dialog-panel"><div class="ttd-dialog-panel-button-container invisible" style="justify-content: flex-start;"></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-output-wrapper "><div class="ttd-dialog-output-canvas-container"><div class="ttd-dialog-output-canvas-content"><canvas width="90" height="158" dir="ltr"></canvas></div></div></div><div class="ttd-dialog-panel-button-container" style="justify-content: flex-start;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>"`;exports[`Test <MermaidToExcalidraw/> > should show error in preview when mermaid library throws error 1`] = `"flowchart TDdiff --git a/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/export.test.tsx.snapindex 475a336842..19213cfc28 100644--- a/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap+++ b/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap@@ -1,7 +1,7 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.htmlexports[`export > export svg-embedded scene > svg-embdedded scene export output 1`] = `-"<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36"><!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nHVTwY7TMFx1MDAxML3zXHUwMDE1UfaK2LRcYlx1MDAwZb3twq7Yw1wiRJE4IFx1MDAwZW48TUZ1bcuebFuqSnxcdTAwMDY3fpFPYOyEuE6XVorkN555b96Mjy+KoqSDhXJRlLCvhULpxK58XHUwMDE58CdwXHUwMDFljebQPJ696VxcXHUwMDFkb7ZEdnF9rVxmJ7TG0+J1VVV9XHUwMDEyKNiCJs/XvvG5KI7xy1x1MDAxMZQh9SZei8A/XoI9JXTPUDWeXHUwMDBl2WmHklpGZm9HqFx1MDAwNWxayjGhXHUwMDFiXHUwMDA1WaInZzbwzijjXHUwMDAy49VcZsI/ka5EvWmc6bRcdTAwMWPvkFx1MDAxM9pb4biZdG+NSi3pXHUwMDEwq7NcdTAwMWbsVjnh+DpInE/w/2UxadNq8MGw2YhcdTAwMWEraqTQ/KxKXVx1MDAwNIX2QUZvvydNTmzhIZirO6VGXHUwMDE4tYT9XHUwMDE0jC1cdTAwMGVsWcBcdTAwMDPITEFcdTAwMWH+XHUwMDA19tHoOrdcdTAwMTf9e547xVx1MDAxMmuhPCRjXHUwMDAz4V3aiYy0s1LQhLd2cIEp1JtpLu/e5lx1MDAxOb64S+zyn9+/fp6NzWha4o8gel6dXHLdw32KZOVDxr3YolxuM3iTlb9R2Fx1MDAwNF9KXHUwMDA167PVYHNcYvk9jGEyNkVrridQg7tcdTAwMWOUcdigXHUwMDE26suz0kVH5jP4XlwiuVx1MDAwZc5dgVx1MDAwZuP2v5onlUqsQH0yXHUwMDFlqZ9goIuxXHUwMDEzf+PilMLaJbHRXHUwMDFj7Vx1MDAxZigvXHUwMDE3yolHPUZgk1x1MDAwN1x1MDAxMXo0XHUwMDEy7rRYqelcdTAwMDDKJ4Td7eVbulrH39DVMLvHTlx1MDAxMS55b+ogMyzHMeg7RX380GCATn9cdTAwMDFWrz23In0=<!-- payload-end --></metadata><defs><style class="style-fonts">+"<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36"><!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nHVTy27bMFx1MDAxMLz3K1x1MDAwNOVcdTAwMWE0sov24FuSJmhcdTAwMGVcdIq6QFx1MDAwZkVcdTAwMGa0uJZcdTAwMTamSYJcXMV2XHJcdTAwMDP9jN76i/2ELilFlOTUXHUwMDA2XHUwMDA0cPYxw9nl8U2W5XSwkC+yXHUwMDFj9qVQKJ3Y5ZdcdTAwMDF/XHUwMDA259FoXHUwMDBlzePZm8aVMbMmsourK2W4oDaeXHUwMDE274qiaItAwVx1MDAxNjR5TvvO5yw7xi9HUIbS65hcdTAwMTaBXHUwMDE3XoI9JXTPUNGfXHUwMDBlo9NcdTAwMGUl1YzMPvRQXHJY1TTGhK5cdTAwMTSMXG49ObOBW6OMXHUwMDBijFx1MDAxNzNcYv9Eulx1MDAxMuWmcqbRss8hJ7S3wvFlUt5cdTAwMWGVWtIhdmc/2K18wvGtkzif4P+rYtKq1uCDYbNcdTAwMWU1VpRI4fKzXCLdXCIotFx1MDAwZjJ6+yNpcmJcdTAwMGJcdTAwMGbBXFzdKNXDqCVcdTAwMDQvc1GM2LTs2EbZXHUwMDFlQI5cdTAwMTSk4Z9hT0aXY3vRf+S5U2yxXHUwMDE2ykMyNlx1MDAxMN5ccnZcIulurFx1MDAxNDRhLVx1MDAxZJxhXG71ZiqXN2/zXG5b3CS+8t8/v39ccoZmNC3xZ5A8L1x1MDAwNiP3cJ9cIqP2oeJebFGFXHS8XHUwMDFmtb9WWFx1MDAwNVdyXHUwMDA168FisDWE/Fx1MDAxYfowXHUwMDE5m6Il91x1MDAxM6jBnY/JOKxQXHUwMDBi9fVV6aIh81x1MDAwNXwrkVxcXHUwMDAzQ1fgU7/7b+dJpVx1MDAxMitQn41HaudcdTAwMTfoYuzE32h/LqxdXHUwMDEyXHUwMDFizdH2efJqoZx41GJcdTAwMDQ2eVx1MDAxMKFHI+FOi5WaXHUwMDBlIH9G2N2cv6SLdfx1t+pm99gowiVvTVx1MDAxOWSG1ThcdTAwMDZ9p6iPn1x1MDAxOXTQ6Vx1MDAxZmLlO84ifQ==<!-- payload-end --></metadata><defs><style class="style-fonts"></style></defs><rect x="0" y="0" width="36" height="36" fill="#ffffff"></rect><g transform="translate(10 10) rotate(0 8 8)" data-id="A"><text x="0" y="17.619999999999997" font-family="Excalifont, Xiaolai, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">😀</text></g></svg>"`;diff --git a/packages/excalidraw/tests/export.test.tsx b/packages/excalidraw/tests/export.test.tsxindex 365db0c6b1..b186d401e9 100644--- a/packages/excalidraw/tests/export.test.tsx+++ b/packages/excalidraw/tests/export.test.tsx@@ -2,9 +2,11 @@ import React from "react";import { SVG_NS } from "@excalidraw/common";-import type { FileId } from "@excalidraw/element/types";+import type { FileId, FractionalIndex } from "@excalidraw/element/types";import { getDefaultAppState } from "../appState";+import * as clipboardModule from "../clipboard";+import { exportCanvas, prepareElementsForExport } from "../data";import { getDataURL } from "../data/blob";import { encodePngMetadata } from "../data/image";import { serializeAsJSON } from "../data/json";@@ -12,7 +14,7 @@ import { Excalidraw } from "../index";import {decodeSvgBase64Payload,encodeSvgBase64Payload,- exportToSvg,+ exportScene,} from "../scene/export";import { API } from "./helpers/api";@@ -26,6 +28,9 @@ const testElements = [type: "text",id: "A",text: "😀",+ // a valid index, as in a real scene (restoring on export would+ // otherwise re-index it, bumping its version with a random nonce)+ index: "a0" as FractionalIndex,}),// can't get jsdom text measurement to work so this is a temp hack// to ensure the element isn't stripped as invisible@@ -82,12 +87,42 @@ describe("export", () => {]);});+ it("exports SVG at the export scale", async () => {+ const copySpy = vi+ .spyOn(clipboardModule, "copyTextToSystemClipboard")+ .mockResolvedValue();+ const exportedWidthAt = async (exportScale: number) => {+ const appState = { ...h.state, exportScale };+ const { exportedElements } = prepareElementsForExport(+ testElements,+ appState,+ false,+ );+ await exportCanvas(+ "clipboard-svg",+ exportedElements,+ appState,+ {},+ { exportingFrame: null },+ );+ const svg = copySpy.mock.lastCall![0] as string;+ return Number(/<svg[^>]* width="([\d.]+)"/.exec(svg)![1]);+ };++ expect(await exportedWidthAt(2)).toBe((await exportedWidthAt(1)) * 2);+ copySpy.mockRestore();+ });+it("export svg-embedded scene", async () => {- const svg = await exportToSvg(- testElements,- { ...getDefaultAppState(), exportEmbedScene: true },- {},- );+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: testElements,+ appState: getDefaultAppState(),+ files: {},+ },+ config: { embedScene: true },+ });const svgText = svg.outerHTML;expect(svgText).toMatchSnapshot(`svg-embdedded scene export output`);@@ -194,7 +229,7 @@ describe("export", () => {angle: normalizeAngle(315),}),];- const appState = { ...getDefaultAppState(), exportBackground: false };+ const appState = getDefaultAppState();const files = {file_A: {id: "file_A" as FileId,@@ -205,7 +240,15 @@ describe("export", () => {},} as const;- const svg = await exportToSvg(elements, appState, files);+ const svg = await exportScene({+ type: "svg",+ data: {+ elements,+ appState,+ files,+ },+ config: { canvasBackgroundColor: false },+ });const svgText = svg.outerHTML;diff --git a/packages/excalidraw/tests/renderOverrides.test.tsx b/packages/excalidraw/tests/renderOverrides.test.tsxindex a2307a6695..6d5b0b9715 100644--- a/packages/excalidraw/tests/renderOverrides.test.tsx+++ b/packages/excalidraw/tests/renderOverrides.test.tsx@@ -15,7 +15,7 @@ import { Excalidraw } from "../index";import { getDefaultAppState } from "../appState";import * as StaticScene from "../renderer/staticScene";import { Renderer } from "../scene/Renderer";-import { exportToSvg } from "../scene/export";+import { exportScene } from "../scene/export";import { getNormalizedZoom } from "../scene";import { getElementRenderOffsets } from "../renderOverrides";@@ -274,14 +274,22 @@ describe("setElementRenderOverrides", () => {it("leaves exported geometry and opacity unchanged", async () => {const { element, submit } = await setup();- const exportScene = async () =>- (await exportToSvg(h.app.api.getSceneElements(), h.state, null))- .outerHTML;- const before = await exportScene();+ const exportSvg = async () =>+ (+ await exportScene({+ type: "svg",+ data: {+ elements: h.app.api.getSceneElements(),+ appState: h.state,+ files: null,+ },+ })+ ).outerHTML;+ const before = await exportSvg();submit(new Map([[element.id, { opacity: 0, offset: { x: 1000, y: 1000 } }]]),);- expect(await exportScene()).toBe(before);+ expect(await exportSvg()).toBe(before);});it("clears on reset and ignores submissions after unmount", async () => {diff --git a/packages/excalidraw/tests/scene/__snapshots__/export.test.ts.snap b/packages/excalidraw/tests/scene/__snapshots__/export.test.ts.snapindex 25d6dc3b22..ce3cb68410 100644--- a/packages/excalidraw/tests/scene/__snapshots__/export.test.ts.snap+++ b/packages/excalidraw/tests/scene/__snapshots__/export.test.ts.snap@@ -61,7 +61,7 @@ exports[`exportToSvg > with a CJK font 1`] = `/></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id4"stroke-linecap="round"transform="translate(10 10) rotate(0 50 50)">@@ -79,7 +79,7 @@ exports[`exportToSvg > with a CJK font 1`] = `/></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id5"transform="translate(10 10) rotate(0 50 50)"><text@@ -97,7 +97,7 @@ exports[`exportToSvg > with a CJK font 1`] = `</text></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id6"transform="translate(10 10) rotate(0 50 50)"><text@@ -115,7 +115,7 @@ exports[`exportToSvg > with a CJK font 1`] = `</text></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id7"transform="translate(10 10) rotate(0 50 50)"><text@@ -178,7 +178,7 @@ exports[`exportToSvg > with default arguments 1`] = `/></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id1"stroke-linecap="round"transform="translate(10 10) rotate(0 50 50)">@@ -196,7 +196,7 @@ exports[`exportToSvg > with default arguments 1`] = `/></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id2"transform="translate(10 10) rotate(0 50 50)"><text@@ -214,7 +214,7 @@ exports[`exportToSvg > with default arguments 1`] = `</text></g><g- data-id="vWrqOAfkind2qcm7LDAGZ"+ data-id="id3"transform="translate(10 10) rotate(0 50 50)"><text@@ -240,12 +240,12 @@ exports[`exportToSvg > with elements that have a link 1`] = ``;exports[`exportToSvg > with exportEmbedScene 1`] = `-"<!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nO1WXW/TMFx1MDAxNH3fr4jC68SctF1L31xuYzBcdIF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aWaZDXHUwMDA2acNkyNbU/Fx1MDAxOanNWlx1MDAxNN6amKow5SBfasBwXHUwMDA0n+v9eFx1MDAxN/uacanFXHUwMDBmUFWTbbZcdTAwMTieXHUwMDAx+y5cdTAwMTTV1dhtxNc3OD5v8JE2uHfe4P/fYN/pyWywebtRhbgoptpcZsVYq3020qSkQ2aFaSj8585B94LAXHLHM9adVLiksPpwYFx1MDAwZlP37DreXHL5vmSaTo3CXHUwMDEyW6aV0dbW574ydlFhXHUwMDA3Pf9cdTAwMDUqLIdcdTAwMTQifQ==<!-- payload-end --></metadata><defs><style class="style-fonts">@font-face { font-family: Excalifont; src: url(data:font/woff2;base64,d09GMgABAAAAAAf0AA4AAAAADbQAAAegAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhYbgjgcNAZgAHwRCAqPYItcCxoAATYCJAMwBCAFgxgHIBujClGUblKX7Edh3Pg8OJbt5MlDFPwWk6FmJ08terdayeDx9O8Fa5eunTJ1ykAUGuAvgOF5bPfuH0nXrvQrNkFoNlERBLIQDd/mj2kP7fdg8avL4M/sm4cbu4L2i1VQVjShz/+90/YE3IJFmOC+f0Z1Xhs3bVxiJZZGa1IgY5sHCJ2EM2iBndkLWsZvFxCAhRBGCknKEOQenHCpmE2fVQTl1atzWyjvzs3aQPnWd20PJQZeG3mQp1lnLimFBAhOKFIQSrGa+vOB69gLCRkjLr4NIjd5rXiz8hhu+LIe9DZCgkJjmZEy34MkhXNBJ8GhNMMnJUgmSYA0AowAwT2zRor05iZAeN/80c4UkYlgSTOaKgOQCUOSE5F+z6+DXqndDTk4CEHP2v3/aKw7lXQXgAUAQP5+kgIpTYMHT9MEjIyWxJ5V5jAzgnrNtNBKWx101tXee86rA5O1f1fiIzEtJsS4GBMjYlikIhEvwwXDjYgiApUFdjgCFAA1m2GorwgdA5a6fzxxX0ei+Eqw6MspHfbmte7eLSh2FSEREgnySedVN+VfsbKAVQygCrGALXgDQoSA0kZqfB2OiyyaZolc/i3tnXswySlmifL9eo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ZEo1ChY4xNg8DaB0RxDqnbMNjXJJRzF9iInqahtm67M8dOHFvXaYbn+wrGxKG3YZI+2V4CW58ovdfV1tFHXFJJiPH7T1FAJxEgYo5BKkA5iDIVQluOqZYWhQapGF6TAFhaFAAoTBIZsCFHi/0oV3gpVKwbAA==); }@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAI0AA4AAAAABLQAAAHeAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQDBAQgBYQkByAb5wPIrgpsY9TYDjGuJ1F+MUed8Q+Do8lDKF1uhErOw/f7/X7tcy+iEk0SUSWRLDGExBCqZYuETCJVS3jlW/rvPv/y4Fra6szKjvjBubd/Nui7lGEMuAbidbw+g/MfFilLa6qnnWkvd4H/FmjEiWUJBzzQH2jiP/jExvFAH6P5ILeGybomYjxExoeP5okC5TpFmecWVieTSw4FIFBuSJ4Vngd7SlWTd4eom7xMLI/zNBO/FJHO0i6T1Zo29kTTT5Ecc9Nf4b9kP/+RT8dQL/MVxGuKXlYhlEpoZMEgy8mRiGYc/001h9DIJhNS9DEhEBBF8QsQokANCJCI5QoKZLddfb/er5n9XZpln/DYYniZkJR+fpjdo1gCwS/pEkByzEzFRPwywYywwWaOVQCAJFDhTCbyMtz5NzKM+ZdJtQeZmfPVzlkWafcoio0oVoJK/QGDNsMiWn6lPh7sAJo3ujXOJwmjmUNvVJIPNzgSgQhtMDoJAmM/EPVmRd2Cwb7gUMZdoCNqiprKqu32bGxtjOs0w8O+gFG9obdhkj7ZHgJXvyi9V1VWUUeciDjE+P07FJBxPiCij0EiQBmINBFCV4aukhKBBImYd0UfgKZEAIBAxeEBHTKU6I9yhpVChXUCAAAA); }@font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAIsAA4AAAAABLQAAAHYAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGx4cLgZgP1NUQVREAAQRCAoAKgsEAAE2AiQ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9Nr9rO2mFcC8rUMi6qITgWjClaVl+6tZxG4/ezyvYhiVKOKkiUQBNKW3wCR1gQCConGgYL6Vik5uYHBH+T6E3yc6OHLTplP/6g2k2hXQPgla1sH3lJf6DTJbxPEedV9bQIAqqDHcZWmC+/+j44tH3TR772uDr2oN6zbTDun2m3YKIReywFCxkEb6b7Skm4ghBglR9vyebxlKPLNt+27HjvxxGew/DGCDtQsGvyXTehdSPR6qVWpddg/nU/LMs3gtu7yCJFbt56xvjyH9E/ovVql2tAfnq0bv/9CILBNpk8584BQPeMxltJeuez6zONGyYS47AK4ke1Awmg5eZRnZSUd); }- @font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchKQ/TyMjWWPhbGVsLhp9GSH50tTI0kpiVprztv5Fg//7Ue7b76siAPJNIlodGtQN2PVLBMSh9QsiSdPzOBa2yGm7yb77eytNyKhUQpUht7Tv2xOByU3QenAtgPMB7F4fyAboXSW9/+/n6v/TjQN8ThtnIUEjdIpZXKR+wRP5pOEmJw+KE2scl5CrJImJdM0EiorlZ5YdBMRC560xeTjuPbtLy7QCkiSUAq1ViHQbDaL3Q2bEgVwd6KYhuDuYjSLwJ09yP8F4sIpGoEjBEIpaZS81yy5rcQrjzVpEJ1J/k3+gsP/ff8Il5G/2fNPGkF4pUAjvJfNawrz6+6nByVFqa9kYlFhOgoleq5SgazextGgsaNdiThmeeBJXBYr4z15AL5i/ioJvcwoWg7EgX1xjpO37MHbHk9cvNKHBpa8cWVIoeH9ZVoeX1Sk6ykIsL08SRz2FoqiqiH0H80ZBl8mbYqf/59QLgvtScQdiPfpNCbtCqFRQq+nzZp37cyEJfB7ESNYvPedtBiOKeCsCogqfiETZge9IpzwbzwL6HdlV21S19DYFITRWJv8H8yErsk/8lQez2N5NH4HI3ko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G1nAEQvSyjvhlccIYEk6RqBT+rLBhq++6mCeaVmSnhRSRLhqn858kQhmckK8KdDho33l762L3oRbXFaJswnP/GldY6NuVtHvpKmyw2lmyXZVhDWdtPtWkoNUMGcLYD5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); }</style></defs><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><path d="M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M2.68 54.01 C17.68 37.03, 33.95 20.86, 40.74 10.24 M2.68 54.01 C16.59 38.38, 31.52 22.36, 40.74 10.24 M5.7 56.63 C19.86 43.02, 33.12 27.27, 52.94 2.29 M5.7 56.63 C23.06 37.39, 40.39 16.53, 52.94 2.29 M8.72 59.26 C23.62 43.85, 37.66 28.7, 55.96 4.92 M8.72 59.26 C27.67 38.75, 44.88 17.7, 55.96 4.92 M11.74 61.88 C23.55 50.54, 31.34 37.36, 58.98 7.54 M11.74 61.88 C25.4 47.12, 38.59 32.54, 58.98 7.54 M14.76 64.51 C25.64 54.29, 34.7 42.69, 61.34 10.92 M14.76 64.51 C25.83 51.81, 38 38.36, 61.34 10.92 M17.12 67.88 C34.34 49.26, 48.5 31.65, 64.36 13.55 M17.12 67.88 C33.86 49.33, 49.44 31.94, 64.36 13.55 M20.14 70.51 C28.87 60.06, 40.4 48.29, 66.72 16.92 M20.14 70.51 C29.76 60.14, 39.05 48.61, 66.72 16.92 M23.16 73.13 C37.73 55.91, 51.72 40.01, 69.74 19.55 M23.16 73.13 C35.28 60.9, 46.76 46.19, 69.74 19.55 M26.18 75.76 C38.75 61.93, 48.87 47, 72.76 22.17 M26.18 75.76 C41.17 57.48, 56.57 40.42, 72.76 22.17 M29.2 78.38 C38.58 66.84, 49.28 56.06, 75.12 25.55 M29.2 78.38 C45.23 60.41, 60.56 42.59, 75.12 25.55 M31.56 81.76 C48.47 62.24, 65.95 45.31, 78.14 28.18 M31.56 81.76 C45.84 64.05, 61.69 48.32, 78.14 28.18 M34.58 84.39 C53.9 64.75, 70.59 44.84, 81.16 30.8 M34.58 84.39 C52.97 64.26, 69.66 43.17, 81.16 30.8 M37.6 87.01 C48.25 74.78, 55.5 66.41, 83.52 34.18 M37.6 87.01 C48.99 71.83, 62.27 58.43, 83.52 34.18 M40.62 89.63 C50.34 79.26, 59.13 68.4, 86.54 36.8 M40.62 89.63 C54.92 72.51, 68.88 57.45, 86.54 36.8 M43.64 92.26 C53.65 80.81, 66.89 67.98, 89.56 39.43 M43.64 92.26 C58.66 75.45, 72.42 57.89, 89.56 39.43 M46 95.64 C61.79 76.78, 78.15 59.99, 91.92 42.81 M46 95.64 C61.9 78.99, 77.17 61.29, 91.92 42.81 M49.02 98.26 C62.86 82.2, 75.55 68.59, 94.94 45.43 M49.02 98.26 C66.35 78.07, 84.72 56.67, 94.94 45.43 M61.22 90.32 C67.86 83.05, 77.21 73.12, 97.96 48.06 M61.22 90.32 C71.29 78.99, 79.23 69.82, 97.96 48.06" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M51 0 C63.55 12.43, 75.75 25.91, 100 51 M51 0 C68.7 19, 85.84 36.05, 100 51 M100 51 C86.33 62.39, 74.98 74.41, 51 100 M100 51 C82.86 68.81, 63.17 88.61, 51 100 M51 100 C30.58 80.76, 12.2 63.63, 0 51 M51 100 C32.58 80.36, 11.39 62.79, 0 51 M0 51 C13.05 38.39, 26.48 26.08, 51 0 M0 51 C14.03 37.59, 27.42 24.3, 51 0" stroke="#000000" stroke-width="1" fill="none"></path></g><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><path d="M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M4.65 33.19 C11.77 27.87, 17.81 20.43, 26.3 8.29 M4.65 33.19 C12.84 24.59, 20.75 14.56, 26.3 8.29 M4.39 39.59 C14.94 29.16, 24.78 18.84, 37.19 1.85 M4.39 39.59 C17.83 25.46, 29.51 10.78, 37.19 1.85 M4.13 45.99 C13.58 37.43, 18.93 27.04, 40.86 3.72 M4.13 45.99 C14.89 34.56, 25.16 23.35, 40.86 3.72 M3.86 52.38 C13.79 43.36, 21.85 32.91, 45.85 4.08 M3.86 52.38 C13.79 40.95, 24.84 28.8, 45.85 4.08 M0.98 61.8 C19.05 42.22, 34.04 23.64, 50.84 4.44 M0.98 61.8 C18.6 42.22, 35.05 23.82, 50.84 4.44 M2.69 65.93 C13.07 53.65, 26.22 40.02, 56.48 4.05 M2.69 65.93 C13.71 53.84, 24.49 40.6, 56.48 4.05 M5.05 69.31 C22.52 48.71, 39.47 29.41, 61.47 4.41 M5.05 69.31 C19.68 54.34, 33.61 36.81, 61.47 4.41 M7.41 72.69 C23.29 55.19, 36.64 36.55, 66.46 4.77 M7.41 72.69 C26.51 49.67, 46.1 27.78, 66.46 4.77 M9.12 76.83 C21.59 61.65, 35.54 47.13, 70.13 6.64 M9.12 76.83 C30.41 52.84, 51 28.96, 70.13 6.64 M11.48 80.21 C33.9 54.33, 56.91 31.04, 73.81 8.51 M11.48 80.21 C30.8 56.74, 51.74 35.15, 73.81 8.51 M13.84 83.58 C39.61 56.49, 62.81 29.08, 77.48 10.38 M13.84 83.58 C38.7 55.9, 61.91 27.31, 77.48 10.38 M16.21 86.96 C30.75 70.22, 41.87 57.39, 80.5 13 M16.21 86.96 C32.53 65.84, 50.87 46.62, 80.5 13 M19.88 88.83 C33.21 74.39, 45.68 59.3, 84.17 14.87 M19.88 88.83 C40.06 65.13, 59.82 43.4, 84.17 14.87 M23.56 90.7 C37.96 74.48, 55.4 56.83, 87.85 16.74 M23.56 90.7 C44.27 67.09, 63.87 42.81, 87.85 16.74 M26.57 93.33 C48.43 67.31, 71.05 43.33, 90.21 20.12 M26.57 93.33 C48.35 69.95, 69.55 45.41, 90.21 20.12 M30.25 95.2 C48.46 74.18, 65.49 55.57, 91.92 24.25 M30.25 95.2 C53.67 67.88, 78.29 39.3, 91.92 24.25 M33.92 97.07 C45.33 84.45, 59.49 68.99, 94.28 27.63 M33.92 97.07 C49.95 78.85, 63.69 63.01, 94.28 27.63 M37.6 98.93 C57.98 79.1, 72.57 56.11, 95.99 31.77 M37.6 98.93 C52.82 81.56, 70.36 62.86, 95.99 31.77 M42.59 99.3 C62.5 72.18, 86.66 48.61, 98.35 35.14 M42.59 99.3 C56.8 81.15, 71.26 63.76, 98.35 35.14 M48.23 98.9 C67.5 76.43, 86.2 53.85, 100.71 38.52 M48.23 98.9 C66.04 79.87, 82.62 59.16, 100.71 38.52 M53.87 98.51 C66.57 83.45, 76.58 72.74, 100.45 44.92 M53.87 98.51 C64.66 85.25, 76.57 72.6, 100.45 44.92 M58.86 98.87 C72.85 81.35, 88.43 63.51, 100.85 50.56 M58.86 98.87 C74.11 80.25, 90.51 62.43, 100.85 50.56 M63.19 99.98 C76.96 84.2, 90.81 65.29, 100.59 56.96 M63.19 99.98 C71.88 89.37, 81.43 79.1, 100.59 56.96 M74.08 93.55 C81.37 85.47, 87.74 76.3, 99.67 64.11 M74.08 93.55 C79.97 87.9, 85.67 81.47, 99.67 64.11" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M38.1 1.46 C45.72 -1.06, 55.49 -0.08, 63.58 2.19 C71.68 4.46, 80.88 9.29, 86.67 15.09 C92.46 20.89, 96.33 29.02, 98.32 36.99 C100.32 44.97, 101 54.87, 98.62 62.96 C96.24 71.05, 90.17 79.66, 84.03 85.55 C77.89 91.43, 69.57 96.06, 61.79 98.28 C54 100.51, 45.12 100.97, 37.32 98.91 C29.52 96.84, 21.11 92.03, 14.99 85.89 C8.88 79.75, 2.75 70.16, 0.63 62.05 C-1.48 53.94, -0.22 45.19, 2.3 37.23 C4.82 29.28, 9.28 20.51, 15.77 14.3 C22.25 8.1, 36.21 2.25, 41.23 0.02 C46.25 -2.21, 45.49 0.09, 45.88 0.91 M40.94 1.53 C48.29 -0.28, 59.04 0.38, 66.96 3.27 C74.89 6.16, 83.12 12.22, 88.48 18.88 C93.85 25.53, 97.82 35.15, 99.18 43.21 C100.54 51.28, 99.41 59.58, 96.65 67.29 C93.89 74.99, 88.87 84.03, 82.63 89.47 C76.39 94.91, 67.44 98.55, 59.2 99.93 C50.97 101.3, 41.25 100.52, 33.2 97.7 C25.15 94.87, 16.16 89.68, 10.9 82.99 C5.64 76.3, 2.84 65.86, 1.64 57.57 C0.45 49.28, 0.99 40.72, 3.74 33.24 C6.5 25.76, 11.77 18.2, 18.18 12.7 C24.59 7.2, 38.36 1.99, 42.22 0.24 C46.09 -1.5, 41.49 1.56, 41.37 2.2" stroke="#000000" stroke-width="1" fill="none"></path></g><g transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><text x="0" y="17.619999999999997" font-family="Excalifont, Xiaolai, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">original text</text></g><g transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><text x="0" y="19.08" font-family="Nunito, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">original text</text></g>"+ @font-face { font-family: Nunito; src: url(data:font/woff2;base64,d09GMgABAAAAAAY8AA8AAAAADAwAAAXkAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGhwbgkocZAZgP1NUQVREAHwRCAqKAIgNCyAAATYCJAM8BCAFhCQHIBv4CVFUchK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KAlHdorbyYAqXy4dZC4kLxJgacdvLOs6r63voK3kZcIV4l/PcsiCT15U/TMevMcVIg6UbhoHmy7WOT1wXDhEE1Z2cY6E4DErivD4ug6TNFezbFAHTdGQiPT+rAfBAhwrgCPZOdT6SsdeXdHTmEap+SEbKnmYUKl1kF9ixbBTvAjDi8Q7YTIeJvVGXPKVlMwVSfFrRErAQx6USuEfFmB4AXxvPKPOeytqahwT5VCsEgL5NVYIh7RnYQnQZ8M1wmpj5aGh4k8+gIk4brwGIaTM7D1T/l89ALkmOy2yKTb5MBsigGfagSxd+I0mLtr2Goo0qyBK3Se3V1eCadQGKKzhwsmjoL8DbcjsH/TZ2UwJIYLL2cX9CiYCEVZUDVWa5Td7EUMhYQMR+3ReC44nK7341kBYyFC0+J0Zy0R0AJ2+LirQcHa3APhUgt78p9aYOtMXb8kQ/JHUseYN+SQyliokRGB+U+fVV+/elyG/lb4jcj1HRtNAyNBRcYlDEpJLEhIroFYlYR+19qt2YF3+7UU6JVDcHxum1ZyNvFzxG3vxGV4PxIB3izP535BXlNqlEKCWQPBN0h6G1nAEQvSyjvhlccIYEk6RqBT+rLBhq++6mCeaVmSnhRSRLhqn858kQhmckK8KdDho33l762L3oRbXFaJswnP/GldY6NuVtHvpKmyw2lmyXZVhDWdtPtWkoNUMGcLYD5WxmaYg9eyDLXQhSUMDU0sLUawuaKqvbGhqbIKVYjiQaQQL2njT0LoS/m7lCr4lQzTmuxjCoadioqGD8nYpaSnBrVwZcjQGguzd9Lz9OWZlztV+GGmLZo3W0dAyABUGMFy9YkQGraQZyvui5GUQK8TxDTs4JGuoWSSGjZraeB5NvHiPSv+dQ4gKw8agodG7ECucqIZ2GpDaFVWXt4wC); }</style></defs><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="vWrqOAfkind2qcm7LDAGZ"><path d="M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M0.32 50.63 C0.32 50.63, 0.32 50.63, 0.32 50.63 M2.68 54.01 C17.68 37.03, 33.95 20.86, 40.74 10.24 M2.68 54.01 C16.59 38.38, 31.52 22.36, 40.74 10.24 M5.7 56.63 C19.86 43.02, 33.12 27.27, 52.94 2.29 M5.7 56.63 C23.06 37.39, 40.39 16.53, 52.94 2.29 M8.72 59.26 C23.62 43.85, 37.66 28.7, 55.96 4.92 M8.72 59.26 C27.67 38.75, 44.88 17.7, 55.96 4.92 M11.74 61.88 C23.55 50.54, 31.34 37.36, 58.98 7.54 M11.74 61.88 C25.4 47.12, 38.59 32.54, 58.98 7.54 M14.76 64.51 C25.64 54.29, 34.7 42.69, 61.34 10.92 M14.76 64.51 C25.83 51.81, 38 38.36, 61.34 10.92 M17.12 67.88 C34.34 49.26, 48.5 31.65, 64.36 13.55 M17.12 67.88 C33.86 49.33, 49.44 31.94, 64.36 13.55 M20.14 70.51 C28.87 60.06, 40.4 48.29, 66.72 16.92 M20.14 70.51 C29.76 60.14, 39.05 48.61, 66.72 16.92 M23.16 73.13 C37.73 55.91, 51.72 40.01, 69.74 19.55 M23.16 73.13 C35.28 60.9, 46.76 46.19, 69.74 19.55 M26.18 75.76 C38.75 61.93, 48.87 47, 72.76 22.17 M26.18 75.76 C41.17 57.48, 56.57 40.42, 72.76 22.17 M29.2 78.38 C38.58 66.84, 49.28 56.06, 75.12 25.55 M29.2 78.38 C45.23 60.41, 60.56 42.59, 75.12 25.55 M31.56 81.76 C48.47 62.24, 65.95 45.31, 78.14 28.18 M31.56 81.76 C45.84 64.05, 61.69 48.32, 78.14 28.18 M34.58 84.39 C53.9 64.75, 70.59 44.84, 81.16 30.8 M34.58 84.39 C52.97 64.26, 69.66 43.17, 81.16 30.8 M37.6 87.01 C48.25 74.78, 55.5 66.41, 83.52 34.18 M37.6 87.01 C48.99 71.83, 62.27 58.43, 83.52 34.18 M40.62 89.63 C50.34 79.26, 59.13 68.4, 86.54 36.8 M40.62 89.63 C54.92 72.51, 68.88 57.45, 86.54 36.8 M43.64 92.26 C53.65 80.81, 66.89 67.98, 89.56 39.43 M43.64 92.26 C58.66 75.45, 72.42 57.89, 89.56 39.43 M46 95.64 C61.79 76.78, 78.15 59.99, 91.92 42.81 M46 95.64 C61.9 78.99, 77.17 61.29, 91.92 42.81 M49.02 98.26 C62.86 82.2, 75.55 68.59, 94.94 45.43 M49.02 98.26 C66.35 78.07, 84.72 56.67, 94.94 45.43 M61.22 90.32 C67.86 83.05, 77.21 73.12, 97.96 48.06 M61.22 90.32 C71.29 78.99, 79.23 69.82, 97.96 48.06" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M51 0 C63.55 12.43, 75.75 25.91, 100 51 M51 0 C68.7 19, 85.84 36.05, 100 51 M100 51 C86.33 62.39, 74.98 74.41, 51 100 M100 51 C82.86 68.81, 63.17 88.61, 51 100 M51 100 C30.58 80.76, 12.2 63.63, 0 51 M51 100 C32.58 80.36, 11.39 62.79, 0 51 M0 51 C13.05 38.39, 26.48 26.08, 51 0 M0 51 C14.03 37.59, 27.42 24.3, 51 0" stroke="#000000" stroke-width="1" fill="none"></path></g><g stroke-linecap="round" transform="translate(10 10) rotate(0 50 50)" data-id="id20"><path d="M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M16.06 13.96 C16.06 13.96, 16.06 13.96, 16.06 13.96 M4.65 33.19 C11.77 27.87, 17.81 20.43, 26.3 8.29 M4.65 33.19 C12.84 24.59, 20.75 14.56, 26.3 8.29 M4.39 39.59 C14.94 29.16, 24.78 18.84, 37.19 1.85 M4.39 39.59 C17.83 25.46, 29.51 10.78, 37.19 1.85 M4.13 45.99 C13.58 37.43, 18.93 27.04, 40.86 3.72 M4.13 45.99 C14.89 34.56, 25.16 23.35, 40.86 3.72 M3.86 52.38 C13.79 43.36, 21.85 32.91, 45.85 4.08 M3.86 52.38 C13.79 40.95, 24.84 28.8, 45.85 4.08 M0.98 61.8 C19.05 42.22, 34.04 23.64, 50.84 4.44 M0.98 61.8 C18.6 42.22, 35.05 23.82, 50.84 4.44 M2.69 65.93 C13.07 53.65, 26.22 40.02, 56.48 4.05 M2.69 65.93 C13.71 53.84, 24.49 40.6, 56.48 4.05 M5.05 69.31 C22.52 48.71, 39.47 29.41, 61.47 4.41 M5.05 69.31 C19.68 54.34, 33.61 36.81, 61.47 4.41 M7.41 72.69 C23.29 55.19, 36.64 36.55, 66.46 4.77 M7.41 72.69 C26.51 49.67, 46.1 27.78, 66.46 4.77 M9.12 76.83 C21.59 61.65, 35.54 47.13, 70.13 6.64 M9.12 76.83 C30.41 52.84, 51 28.96, 70.13 6.64 M11.48 80.21 C33.9 54.33, 56.91 31.04, 73.81 8.51 M11.48 80.21 C30.8 56.74, 51.74 35.15, 73.81 8.51 M13.84 83.58 C39.61 56.49, 62.81 29.08, 77.48 10.38 M13.84 83.58 C38.7 55.9, 61.91 27.31, 77.48 10.38 M16.21 86.96 C30.75 70.22, 41.87 57.39, 80.5 13 M16.21 86.96 C32.53 65.84, 50.87 46.62, 80.5 13 M19.88 88.83 C33.21 74.39, 45.68 59.3, 84.17 14.87 M19.88 88.83 C40.06 65.13, 59.82 43.4, 84.17 14.87 M23.56 90.7 C37.96 74.48, 55.4 56.83, 87.85 16.74 M23.56 90.7 C44.27 67.09, 63.87 42.81, 87.85 16.74 M26.57 93.33 C48.43 67.31, 71.05 43.33, 90.21 20.12 M26.57 93.33 C48.35 69.95, 69.55 45.41, 90.21 20.12 M30.25 95.2 C48.46 74.18, 65.49 55.57, 91.92 24.25 M30.25 95.2 C53.67 67.88, 78.29 39.3, 91.92 24.25 M33.92 97.07 C45.33 84.45, 59.49 68.99, 94.28 27.63 M33.92 97.07 C49.95 78.85, 63.69 63.01, 94.28 27.63 M37.6 98.93 C57.98 79.1, 72.57 56.11, 95.99 31.77 M37.6 98.93 C52.82 81.56, 70.36 62.86, 95.99 31.77 M42.59 99.3 C62.5 72.18, 86.66 48.61, 98.35 35.14 M42.59 99.3 C56.8 81.15, 71.26 63.76, 98.35 35.14 M48.23 98.9 C67.5 76.43, 86.2 53.85, 100.71 38.52 M48.23 98.9 C66.04 79.87, 82.62 59.16, 100.71 38.52 M53.87 98.51 C66.57 83.45, 76.58 72.74, 100.45 44.92 M53.87 98.51 C64.66 85.25, 76.57 72.6, 100.45 44.92 M58.86 98.87 C72.85 81.35, 88.43 63.51, 100.85 50.56 M58.86 98.87 C74.11 80.25, 90.51 62.43, 100.85 50.56 M63.19 99.98 C76.96 84.2, 90.81 65.29, 100.59 56.96 M63.19 99.98 C71.88 89.37, 81.43 79.1, 100.59 56.96 M74.08 93.55 C81.37 85.47, 87.74 76.3, 99.67 64.11 M74.08 93.55 C79.97 87.9, 85.67 81.47, 99.67 64.11" stroke="#15aabf" stroke-width="0.5" fill="none"></path><path d="M38.1 1.46 C45.72 -1.06, 55.49 -0.08, 63.58 2.19 C71.68 4.46, 80.88 9.29, 86.67 15.09 C92.46 20.89, 96.33 29.02, 98.32 36.99 C100.32 44.97, 101 54.87, 98.62 62.96 C96.24 71.05, 90.17 79.66, 84.03 85.55 C77.89 91.43, 69.57 96.06, 61.79 98.28 C54 100.51, 45.12 100.97, 37.32 98.91 C29.52 96.84, 21.11 92.03, 14.99 85.89 C8.88 79.75, 2.75 70.16, 0.63 62.05 C-1.48 53.94, -0.22 45.19, 2.3 37.23 C4.82 29.28, 9.28 20.51, 15.77 14.3 C22.25 8.1, 36.21 2.25, 41.23 0.02 C46.25 -2.21, 45.49 0.09, 45.88 0.91 M40.94 1.53 C48.29 -0.28, 59.04 0.38, 66.96 3.27 C74.89 6.16, 83.12 12.22, 88.48 18.88 C93.85 25.53, 97.82 35.15, 99.18 43.21 C100.54 51.28, 99.41 59.58, 96.65 67.29 C93.89 74.99, 88.87 84.03, 82.63 89.47 C76.39 94.91, 67.44 98.55, 59.2 99.93 C50.97 101.3, 41.25 100.52, 33.2 97.7 C25.15 94.87, 16.16 89.68, 10.9 82.99 C5.64 76.3, 2.84 65.86, 1.64 57.57 C0.45 49.28, 0.99 40.72, 3.74 33.24 C6.5 25.76, 11.77 18.2, 18.18 12.7 C24.59 7.2, 38.36 1.99, 42.22 0.24 C46.09 -1.5, 41.49 1.56, 41.37 2.2" stroke="#000000" stroke-width="1" fill="none"></path></g><g transform="translate(10 10) rotate(0 50 50)" data-id="id21"><text x="0" y="17.619999999999997" font-family="Excalifont, Xiaolai, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">original text</text></g><g transform="translate(10 10) rotate(0 50 50)" data-id="id22"><text x="0" y="19.08" font-family="Nunito, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">original text</text></g>"`;diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.tsindex 5ce8b1fc84..36be2ee33e 100644--- a/packages/excalidraw/tests/scene/export.test.ts+++ b/packages/excalidraw/tests/scene/export.test.ts@@ -1,10 +1,9 @@-import { exportToCanvas, exportToSvg } from "@excalidraw/utils";-import {applyDarkModeFilter,BOUND_TEXT_PADDING,FONT_FAMILY,FRAME_STYLE,+ THEME,} from "@excalidraw/common";import { pointFrom } from "@excalidraw/math";@@ -18,8 +17,11 @@ import type {import type { LocalPoint } from "@excalidraw/math";+import { getDefaultAppState } from "../../appState";+import * as staticSceneModule from "../../renderer/staticScene";+import { exportScene } from "../../scene/export";+import { prepareElementsForExport } from "../../data";-import * as exportUtils from "../../scene/export";import {diamondFixture,ellipseFixture,@@ -28,6 +30,8 @@ import {} from "../fixtures/elementFixture";import { API } from "../helpers/api";+import type { ExportSceneData } from "../../scene/export";+describe("exportToSvg", () => {const ELEMENT_HEIGHT = 100;const ELEMENT_WIDTH = 100;@@ -59,39 +63,45 @@ describe("exportToSvg", () => {},] as NonDeletedExcalidrawElement[];- const DEFAULT_OPTIONS = {- exportBackground: false,+ const DEFAULT_APP_STATE = {viewBackgroundColor: "#ffffff",- files: {},};it("with default arguments", async () => {- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- DEFAULT_OPTIONS,- null,- );+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: DEFAULT_APP_STATE,+ files: {},+ },+ config: { canvasBackgroundColor: false },+ });expect(svgElement).toMatchSnapshot();});it("with a CJK font", async () => {- const svgElement = await exportUtils.exportToSvg(- [- ...ELEMENTS,- {- ...textFixture,- height: ELEMENT_HEIGHT,- width: ELEMENT_WIDTH,- text: "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",- originalText:- "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",- index: "a4" as FractionalIndex,- } as NonDeleted<ExcalidrawTextElement>,- ],- DEFAULT_OPTIONS,- null,- );+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: [+ ...ELEMENTS,+ {+ ...textFixture,+ height: ELEMENT_HEIGHT,+ width: ELEMENT_WIDTH,+ text: "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",+ originalText:+ "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",+ index: "a4" as FractionalIndex,+ } as NonDeleted<ExcalidrawTextElement>,+ ],+ appState: DEFAULT_APP_STATE,+ files: {},+ },+ config: { canvasBackgroundColor: false },+ });expect(svgElement).toMatchSnapshot();// extend the timeout, as it needs to first load the fonts from disk and then perform whole woff2 decode, subset and encode (without workers)@@ -100,15 +110,17 @@ describe("exportToSvg", () => {it("with background color", async () => {const BACKGROUND_COLOR = "#abcdef";- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- {- ...DEFAULT_OPTIONS,- exportBackground: true,- viewBackgroundColor: BACKGROUND_COLOR,+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: {+ ...DEFAULT_APP_STATE,+ viewBackgroundColor: BACKGROUND_COLOR,+ },+ files: {},},- null,- );+ });expect(svgElement.querySelector("rect")).toHaveAttribute("fill",@@ -117,14 +129,20 @@ describe("exportToSvg", () => {});it("with dark mode", async () => {- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- {- ...DEFAULT_OPTIONS,- exportWithDarkMode: true,+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: {+ ...DEFAULT_APP_STATE,+ },+ files: {},},- null,- );+ config: {+ canvasBackgroundColor: false,+ theme: THEME.DARK,+ },+ });const textElements = svgElement.querySelectorAll("text");expect(textElements.length).toBeGreaterThan(0);@@ -138,14 +156,18 @@ describe("exportToSvg", () => {});it("with exportPadding", async () => {- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- {- ...DEFAULT_OPTIONS,- exportPadding: 0,+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: DEFAULT_APP_STATE,+ files: {},},- null,- );+ config: {+ canvasBackgroundColor: false,+ padding: 0,+ },+ });expect(svgElement).toHaveAttribute("height", ELEMENT_HEIGHT.toString());expect(svgElement).toHaveAttribute("width", ELEMENT_WIDTH.toString());@@ -158,15 +180,19 @@ describe("exportToSvg", () => {it("with scale", async () => {const SCALE = 2;- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- {- ...DEFAULT_OPTIONS,- exportPadding: 0,- exportScale: SCALE,+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: DEFAULT_APP_STATE,+ files: {},},- null,- );+ config: {+ canvasBackgroundColor: false,+ padding: 0,+ scale: SCALE,+ },+ });expect(svgElement).toHaveAttribute("height",@@ -179,23 +205,28 @@ describe("exportToSvg", () => {});it("with exportEmbedScene", async () => {- const svgElement = await exportUtils.exportToSvg(- ELEMENTS,- {- ...DEFAULT_OPTIONS,- exportEmbedScene: true,+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: ELEMENTS,+ appState: DEFAULT_APP_STATE,+ files: {},},- null,- );+ config: { canvasBackgroundColor: false, embedScene: true },+ });expect(svgElement.innerHTML).toMatchSnapshot();});it("with elements that have a link", async () => {- const svgElement = await exportUtils.exportToSvg(- [rectangleWithLinkFixture] as NonDeletedExcalidrawElement[],- DEFAULT_OPTIONS,- null,- );+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: [rectangleWithLinkFixture] as NonDeletedExcalidrawElement[],+ appState: DEFAULT_APP_STATE,+ files: {},+ },+ config: { canvasBackgroundColor: false },+ });expect(svgElement.innerHTML).toMatchSnapshot();});@@ -221,11 +252,15 @@ describe("exportToSvg", () => {containerId: "arrow-11439",});- const svgElement = await exportUtils.exportToSvg(- [arrow, label] as NonDeletedExcalidrawElement[],- DEFAULT_OPTIONS,- null,- );+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: [arrow, label] as NonDeletedExcalidrawElement[],+ appState: DEFAULT_APP_STATE,+ files: null,+ },+ config: { canvasBackgroundColor: false },+ });const mask = svgElement.querySelector("mask");expect(mask).not.toBeNull();@@ -258,11 +293,15 @@ describe("exportToSvg", () => {containerId: "arrow-hole",});- const svgElement = await exportUtils.exportToSvg(- [arrow, label] as NonDeletedExcalidrawElement[],- { ...DEFAULT_OPTIONS, exportPadding: 0 },- null,- );+ const svgElement = await exportScene({+ type: "svg",+ data: {+ elements: [arrow, label] as NonDeletedExcalidrawElement[],+ appState: DEFAULT_APP_STATE,+ files: null,+ },+ config: { padding: 0, canvasBackgroundColor: false },+ });// the mask's first rect is the visible region, sized to the arrow plus// its offset within the export; the second is the hole cut for the label@@ -326,10 +365,13 @@ describe("exportToCanvas", () => {containerId: "arrow-11591",});- const canvas = await exportToCanvas({- elements: [rectangle, arrow, label],- files: null,- appState: { exportBackground: true, viewBackgroundColor: "#ffffff" },+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements: [rectangle, arrow, label],+ appState: { viewBackgroundColor: "#ffffff" },+ files: null,+ },});const context = canvas.getContext("2d") as any;@@ -359,14 +401,163 @@ describe("exportToCanvas", () => {});});+describe("export background", () => {+ // an outline arrowhead fakes its hollow interior by filling it with the+ // background color — the arrow's shaft runs into the arrowhead+ const sceneWithOutlineArrow = (viewBackgroundColor = "#ffffff") => ({+ elements: [+ API.createElement({+ type: "arrow",+ width: 100,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],+ endArrowhead: "triangle_outline",+ }),+ ],+ appState: { viewBackgroundColor },+ files: null,+ });+ const getBackgroundRects = (svg: SVGSVGElement) =>+ Array.from(svg.children).filter((child) => child.tagName === "rect");+ const getCanvasFillStyles = (canvas: HTMLCanvasElement) =>+ (canvas.getContext("2d") as any)+ .__getEvents()+ .filter((event: any) => event.type === "fillStyle")+ .map((event: any) => event.props.value);++ it("exportToSvg paints no background for `false` or a transparent scene background", async () => {+ const svg = await exportScene({+ type: "svg",+ data: sceneWithOutlineArrow(),+ config: { canvasBackgroundColor: false },+ });+ expect(getBackgroundRects(svg)).toEqual([]);++ const svgOfTransparentScene = await exportScene({+ type: "svg",+ data: sceneWithOutlineArrow("transparent"),+ });+ expect(getBackgroundRects(svgOfTransparentScene)).toEqual([]);+ });++ it("exportToSvg fills outline arrowheads with the configured background", async () => {+ const svg = await exportScene({+ type: "svg",+ data: sceneWithOutlineArrow(),+ config: { canvasBackgroundColor: "#000000" },+ });+ expect(getBackgroundRects(svg)[0]).toHaveAttribute("fill", "#000000");+ expect(svg.querySelector('g path[fill="#000000"]')).not.toBeNull();+ });++ it("transparent exports keep filling outline arrowheads with the scene background", async () => {+ const canvas = await exportScene({+ type: "canvas",+ data: sceneWithOutlineArrow(),+ config: { canvasBackgroundColor: false },+ });+ expect(getCanvasFillStyles(canvas)).toContain("#ffffff");++ const svg = await exportScene({+ type: "svg",+ data: sceneWithOutlineArrow(),+ config: { canvasBackgroundColor: false },+ });+ expect(svg.querySelector('g path[fill="#ffffff"]')).not.toBeNull();+ });++ it("JPEG export paints the default background instead of `false`", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const canvas = document.createElement("canvas");++ await exportScene({+ type: "jpeg",+ data: sceneWithOutlineArrow("#abcdef"),+ config: { environment: { createCanvas: () => canvas } },+ });+ // the default background needs no warning+ expect(warn).not.toHaveBeenCalled();++ const canvasWithoutBackground = document.createElement("canvas");+ await exportScene({+ type: "jpeg",+ data: sceneWithOutlineArrow("#abcdef"),+ config: {+ canvasBackgroundColor: false,+ environment: { createCanvas: () => canvasWithoutBackground },+ },+ });+ expect(warn).toHaveBeenCalledTimes(1);+ expect(getCanvasFillStyles(canvasWithoutBackground)).toContain("#abcdef");++ warn.mockRestore();+ });+});++describe("export inputs", () => {+ it("takes only the scene settings from data.appState", async () => {+ const renderSpy = vi.spyOn(staticSceneModule, "renderStaticScene");++ await exportScene({+ type: "canvas",+ data: {+ elements: [API.createElement({ type: "rectangle" })],+ // a live AppState, as JS callers (and the editor) may pass+ appState: {+ ...getDefaultAppState(),+ viewBackgroundColor: "#abcdef",+ openDialog: { name: "elementLinkSelector", sourceElementId: "x" },+ croppingElementId: "x",+ } as ExportSceneData["appState"],+ },+ });++ const { appState } = renderSpy.mock.calls[0][0];+ expect(appState.viewBackgroundColor).toBe("#abcdef");+ expect(appState.openDialog).toBe(null);+ expect(appState.croppingElementId).toBe(null);+ renderSpy.mockRestore();+ });++ it("loads fonts through environment.loadFonts", async () => {+ const loadFonts = vi.fn(async () => {});++ await exportScene({+ type: "svg",+ data: { elements: [API.createElement({ type: "text", text: "hi" })] },+ config: { environment: { loadFonts } },+ });++ expect(loadFonts).toHaveBeenCalledTimes(1);+ });++ it("renders frame decorations per config.frames", async () => {+ const elements = [API.createElement({ type: "frame" })];+ const countFrameNames = (svg: SVGSVGElement) =>+ Array.from(svg.querySelectorAll("text")).filter(+ (text) => text.textContent === "Frame",+ ).length;++ const svg = await exportScene({ type: "svg", data: { elements } });+ const svgWithoutNames = await exportScene({+ type: "svg",+ data: { elements },+ config: { frames: { name: false } },+ });++ expect(countFrameNames(svg)).toBe(1);+ expect(countFrameNames(svgWithoutNames)).toBe(0);+ });+});+describe("exporting frames", () => {const getFrameNameHeight = (exportType: "canvas" | "svg") => {const height =FRAME_STYLE.nameFontSize * FRAME_STYLE.nameLineHeight +FRAME_STYLE.nameOffsetY;- // canvas truncates dimensions to integers+ // canvas rounds dimensions to integersif (exportType === "canvas") {- return Math.trunc(height);+ return Math.round(height);}return height;};@@ -393,10 +584,16 @@ describe("exporting frames", () => {}),];- const canvas = await exportToCanvas({- elements,- files: null,- exportPadding: 0,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements,+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ },});expect(canvas.width).toEqual(200);@@ -422,11 +619,17 @@ describe("exporting frames", () => {}),];- const canvas = await exportToCanvas({- elements,- files: null,- exportPadding: 0,- exportingFrame: frame,+ const canvas = await exportScene({+ type: "canvas",+ data: {+ elements,+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame: frame,+ },});expect(canvas.width).toEqual(frame.width);@@ -437,6 +640,52 @@ describe("exporting frames", () => {// exportToSvg (so we can test for element existence)// ---------------------------------------------------------------------------describe("exportToSvg", () => {+ it("colors frame names like the editor in the configured theme", async () => {+ const frame = API.createElement({ type: "frame" });++ const svg = await exportScene({+ type: "svg",+ data: { elements: [frame], files: null },+ config: { theme: THEME.DARK },+ });++ const label = Array.from(svg.querySelectorAll("text")).find(+ (text) => text.textContent === "Frame",+ );+ expect(label).toHaveAttribute("fill", FRAME_STYLE.nameColorDarkTheme);+ });++ it("clips a frame export larger than the frame to the frame", async () => {+ const frame = API.createElement({+ type: "frame",+ width: 100,+ height: 100,+ });+ const child = API.createElement({+ type: "rectangle",+ x: 50,+ y: 20,+ width: 150,+ height: 40,+ frameId: frame.id,+ });+ const data = { elements: [frame, child] };+ const config = { exportingFrame: frame, width: 200, height: 100 };++ const svg = await exportScene({ type: "svg", data, config });+ expect(+ svg.querySelector(+ `g[clip-path="url(#${frame.id})"] [data-id="${child.id}"]`,+ ),+ ).not.toBeNull();++ const canvas = await exportScene({ type: "canvas", data, config });+ const clips = (canvas.getContext("2d") as any)+ .__getEvents()+ .filter((event: any) => event.type === "clip");+ expect(clips).toHaveLength(1);+ });+it("exporting frame should include overlapping elements, but crop to frame", async () => {const frame = API.createElement({type: "frame",@@ -461,11 +710,17 @@ describe("exporting frames", () => {y: 0,});- const svg = await exportToSvg({- elements: [rectOverlapping, frame, frameChild],- files: null,- exportPadding: 0,- exportingFrame: frame,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: [rectOverlapping, frame, frameChild],+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame: frame,+ },});// frame itself isn't exported@@ -505,11 +760,17 @@ describe("exporting frames", () => {y: 0,});- const svg = await exportToSvg({- elements: [frameChild, frame, elementOutside],- files: null,- exportPadding: 0,- exportingFrame: frame,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: [frameChild, frame, elementOutside],+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame: frame,+ },});// frame itself isn't exported@@ -573,11 +834,17 @@ describe("exporting frames", () => {true,);- const svg = await exportToSvg({- elements: exportedElements,- files: null,- exportPadding: 0,- exportingFrame,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: exportedElements,+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame,+ },});// frames themselves should be exported when multiple frames selected@@ -618,11 +885,17 @@ describe("exporting frames", () => {false,);- const svg = await exportToSvg({- elements: exportedElements,- files: null,- exportPadding: 0,- exportingFrame,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: exportedElements,+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame,+ },});// frame itself isn't exported@@ -677,11 +950,17 @@ describe("exporting frames", () => {true,);- const svg = await exportToSvg({- elements: exportedElements,- files: null,- exportPadding: 0,- exportingFrame,+ const svg = await exportScene({+ type: "svg",+ data: {+ elements: exportedElements,+ appState: {},+ files: null,+ },+ config: {+ padding: 0,+ exportingFrame,+ },});// frame shouldn't be exporteddiff --git a/packages/excalidraw/tests/stickyNotes.test.tsx b/packages/excalidraw/tests/stickyNotes.test.tsxindex 1a22503493..e432db0bbc 100644--- a/packages/excalidraw/tests/stickyNotes.test.tsx+++ b/packages/excalidraw/tests/stickyNotes.test.tsx@@ -18,7 +18,6 @@ import {resizeSingleElement,updateStickyNoteLayout,} from "@excalidraw/element";-import { exportToCanvas } from "@excalidraw/utils";import type {ExcalidrawArrowElement,@@ -39,7 +38,7 @@ import { activeEyeDropperAtom } from "../components/EyeDropper";import { getShapeActionPredicates } from "../components/shapeActionPredicates";import { editorJotaiStore } from "../editor-jotai";import { Excalidraw } from "../index";-import { exportToSvg } from "../scene/export";+import { exportScene } from "../scene/export";import { API } from "./helpers/api";import { Keyboard, Pointer, UI } from "./helpers/ui";@@ -1157,16 +1156,19 @@ describe("sticky notes", () => {}),];- const svg = await exportToSvg(- elements,- { exportBackground: false, viewBackgroundColor: "#ffffff" },- {},- );+ const svg = await exportScene({+ type: "svg",+ data: { elements, files: {} },+ config: { canvasBackgroundColor: false },+ });expect([...svg.querySelectorAll("text")].map((text) => text.textContent),).toEqual(["7 Mar 2025"]);- const canvas = await exportToCanvas({ elements, files: {} });+ const canvas = await exportScene({+ type: "canvas",+ data: { elements, files: {} },+ });expect(canvas.getContext("2d")?.fillText).toHaveBeenCalledWith("7 Mar 2025",expect.any(Number),diff --git a/packages/utils/CHANGELOG.md b/packages/utils/CHANGELOG.mdindex 875d8e82fe..73b35ae10a 100644--- a/packages/utils/CHANGELOG.md+++ b/packages/utils/CHANGELOG.md@@ -2,6 +2,10 @@## [Unreleased]+### Breaking++- `exportToCanvas`, `exportToBlob` and `exportToSvg` are replaced by `exportScene({ type: "canvas" | "png" | "jpeg" | "svg", data, config })`, with the rendering options moved from `appState` into `config`. See the "Export API: `exportScene`" entry in the [`@excalidraw/excalidraw` changelog](../excalidraw/CHANGELOG.md) for the migration.+First release of `@excalidraw/utils` to provide utilities functions.- Added `exportToBlob` and `exportToSvg` to export an Excalidraw diagram definition, respectively, to a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and to a [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement) ([#2246](https://github.com/excalidraw/excalidraw/pull/2246))diff --git a/packages/utils/src/export.ts b/packages/utils/src/export.tsdeleted file mode 100644index 27a70da2c6..0000000000--- a/packages/utils/src/export.ts+++ /dev/null@@ -1,225 +0,0 @@-import { MIME_TYPES } from "@excalidraw/common";-import { getDefaultAppState } from "@excalidraw/excalidraw/appState";-import {- copyBlobToClipboardAsPng,- copyTextToSystemClipboard,- copyToClipboard,-} from "@excalidraw/excalidraw/clipboard";-import { encodePngMetadata } from "@excalidraw/excalidraw/data/image";-import { getNonDeletedElements } from "@excalidraw/element";-import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";-import {- restoreAppState,- restoreElements,-} from "@excalidraw/excalidraw/data/restore";-import {- exportToCanvas as _exportToCanvas,- exportToSvg as _exportToSvg,-} from "@excalidraw/excalidraw/scene/export";--import type {- ExcalidrawFrameLikeElement,- NonDeleted,- NonDeletedExcalidrawElement,-} from "@excalidraw/element/types";-import type { AppState, BinaryFiles } from "@excalidraw/excalidraw/types";--export { MIME_TYPES };--type ExportOpts = {- /** restored before exporting */- elements: readonly NonDeletedExcalidrawElement[];- appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;- files: BinaryFiles | null;- maxWidthOrHeight?: number;- exportingFrame?: NonDeleted<ExcalidrawFrameLikeElement> | null;- getDimensions?: (- width: number,- height: number,- ) => { width: number; height: number; scale?: number };-};--export const exportToCanvas = ({- elements,- appState,- files,- maxWidthOrHeight,- getDimensions,- exportPadding,- exportingFrame,-}: ExportOpts & {- exportPadding?: number;-}) => {- const restoredElements = getNonDeletedElements(- restoreElements(elements, null, {- deleteInvisibleElements: true,- }),- );- const restoredAppState = restoreAppState(appState, null);-- const { exportBackground, viewBackgroundColor } = restoredAppState;- return _exportToCanvas(- restoredElements,- { ...restoredAppState, offsetTop: 0, offsetLeft: 0, width: 0, height: 0 },- files || {},- { exportBackground, exportPadding, viewBackgroundColor, exportingFrame },- (width: number, height: number) => {- const canvas = document.createElement("canvas");-- if (maxWidthOrHeight) {- if (typeof getDimensions === "function") {- console.warn(- "`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.",- );- }-- const max = Math.max(width, height);-- // if content is less then maxWidthOrHeight, fallback on supplied scale- const scale =- maxWidthOrHeight < max- ? maxWidthOrHeight / max- : appState?.exportScale ?? 1;-- canvas.width = width * scale;- canvas.height = height * scale;-- return {- canvas,- scale,- };- }-- const ret = getDimensions?.(width, height) || { width, height };-- canvas.width = ret.width;- canvas.height = ret.height;-- return {- canvas,- scale: ret.scale ?? 1,- };- },- );-};--export const exportToBlob = async (- opts: ExportOpts & {- mimeType?: string;- quality?: number;- exportPadding?: number;- },-): Promise<Blob> => {- let { mimeType = MIME_TYPES.png, quality } = opts;-- if (mimeType === MIME_TYPES.png && typeof quality === "number") {- console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);- }-- // typo in MIME type (should be "jpeg")- if (mimeType === "image/jpg") {- mimeType = MIME_TYPES.jpg;- }-- if (mimeType === MIME_TYPES.jpg && !opts.appState?.exportBackground) {- console.warn(- `Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,- );- opts = {- ...opts,- appState: { ...opts.appState, exportBackground: true },- };- }-- const canvas = await exportToCanvas(opts);-- quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;-- return new Promise((resolve, reject) => {- canvas.toBlob(- async (blob) => {- if (!blob) {- return reject(new Error("couldn't export to blob"));- }- if (- blob &&- mimeType === MIME_TYPES.png &&- opts.appState?.exportEmbedScene- ) {- blob = await encodePngMetadata({- blob,- metadata: serializeAsJSON(- // NOTE as long as we're using the Scene hack, we need to ensure- // we pass the original, uncloned elements when serializing- // so that we keep ids stable (restoring keeps the ids)- restoreElements(opts.elements, null),- opts.appState,- opts.files || {},- "local",- ),- });- }- resolve(blob);- },- mimeType,- quality,- );- });-};--export const exportToSvg = async ({- elements,- appState = getDefaultAppState(),- files = {},- exportPadding,- renderEmbeddables,- exportingFrame,- skipInliningFonts,- reuseImages,-}: Omit<ExportOpts, "getDimensions"> & {- exportPadding?: number;- renderEmbeddables?: boolean;- skipInliningFonts?: true;- reuseImages?: boolean;-}): Promise<SVGSVGElement> => {- const restoredElements = getNonDeletedElements(- restoreElements(elements, null, {- deleteInvisibleElements: true,- }),- );- const restoredAppState = restoreAppState(appState, null);-- const exportAppState = {- ...restoredAppState,- exportPadding,- };-- return _exportToSvg(restoredElements, exportAppState, files, {- exportingFrame,- renderEmbeddables,- skipInliningFonts,- reuseImages,- });-};--export const exportToClipboard = async (- opts: ExportOpts & {- mimeType?: string;- quality?: number;- type: "png" | "svg" | "json";- },-) => {- if (opts.type === "svg") {- const svg = await exportToSvg(opts);- await copyTextToSystemClipboard(svg.outerHTML);- } else if (opts.type === "png") {- await copyBlobToClipboardAsPng(exportToBlob(opts));- } else if (opts.type === "json") {- await copyToClipboard(- getNonDeletedElements(restoreElements(opts.elements, null)),- opts.files,- );- } else {- throw new Error("Invalid export type");- }-};diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.tsindex 28c2db28c7..a3fd873ce0 100644--- a/packages/utils/src/index.ts+++ b/packages/utils/src/index.ts@@ -1,3 +1,15 @@-export * from "./export";+// Re-export from @excalidraw/excalidraw for backwards compatibility+export {+ exportScene,+ exportToClipboard,+ MIME_TYPES,+} from "@excalidraw/excalidraw/scene/export";++export type {+ ExportSceneData,+ ExportSceneConfig,+ ExportSceneOptions,+} from "@excalidraw/excalidraw/scene/export";+export { elementsOverlappingBBox } from "@excalidraw/element";export { getCommonBounds } from "@excalidraw/element";diff --git a/packages/utils/tests/__snapshots__/export.test.ts.snap b/packages/utils/tests/__snapshots__/export.test.ts.snapdeleted file mode 100644index 618ac57a04..0000000000--- a/packages/utils/tests/__snapshots__/export.test.ts.snap+++ /dev/null@@ -1,129 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`exportToSvg > with default arguments 1`] = `-{- "activeEmbeddable": null,- "activeLockedId": null,- "activeTool": {- "customType": null,- "fromSelection": false,- "lastActiveTool": null,- "locked": false,- "type": "selection",- },- "bindMode": "orbit",- "bindingPreference": "enabled",- "boxSelectionMode": "contain",- "collaborators": Map {},- "colorTopPicks": {- "bucketFill": null,- "elementBackground": null,- "elementStroke": null,- "stickyNoteBackground": null,- "stickyNoteStroke": null,- },- "contextMenu": null,- "croppingElementId": null,- "currentHoveredFontFamily": null,- "currentItemArrowType": "round",- "currentItemBackgroundColor": "transparent",- "currentItemEndArrowhead": "arrow",- "currentItemFillStyle": "solid",- "currentItemFontFamily": 5,- "currentItemFontSize": 20,- "currentItemOpacity": 100,- "currentItemRoughness": 1,- "currentItemRoundness": "sharp",- "currentItemStartArrowhead": null,- "currentItemStickynoteBackgroundColor": "#ffdf6b",- "currentItemStickynoteStrokeColor": "#1e1e1e",- "currentItemStrokeColor": "#1e1e1e",- "currentItemStrokeStyle": "solid",- "currentItemStrokeVariability": "constant",- "currentItemStrokeWidthKey": "medium",- "currentItemTextAlign": "left",- "cursorButton": "up",- "defaultSidebarDockedPreference": false,- "editingFrame": null,- "editingGroupId": null,- "editingTextElement": null,- "elementsToHighlight": null,- "errorMessage": null,- "exportBackground": true,- "exportEmbedScene": false,- "exportPadding": undefined,- "exportScale": 1,- "exportWithDarkMode": false,- "fileHandle": null,- "fontTopPicks": null,- "frameRendering": {- "clip": true,- "enabled": true,- "name": true,- "outline": true,- },- "frameToHighlight": null,- "gridModeEnabled": false,- "gridSize": 20,- "gridStep": 5,- "hoveredElementIds": {},- "inputDevice": "auto",- "isBindingEnabled": true,- "isCropping": false,- "isLoading": false,- "isMidpointSnappingEnabled": true,- "isResizing": false,- "isRotating": false,- "lastPointerDownWith": "mouse",- "lockedMultiSelections": {},- "multiElement": null,- "name": "name",- "newElement": null,- "objectsSnapModeEnabled": false,- "openDialog": null,- "openMenu": null,- "openPopup": null,- "openSidebar": null,- "originSnapOffset": {- "x": 0,- "y": 0,- },- "penDetected": false,- "penMode": false,- "preferredSelectionTool": {- "initialized": false,- "type": "selection",- },- "previousSelectedElementIds": {},- "resizingElement": null,- "scrollConstraints": null,- "scrollX": 0,- "scrollY": 0,- "scrolledOutside": false,- "searchMatches": null,- "selectedElementIds": {},- "selectedElementsAreBeingDragged": false,- "selectedGroupIds": {},- "selectedLinearElement": null,- "selectionElement": null,- "shouldCacheIgnoreZoom": false,- "showHints": true,- "showHyperlinkPopup": false,- "showWelcomeScreen": false,- "snapLines": [],- "stats": {- "open": false,- "panels": 3,- },- "suggestedBinding": null,- "textToolHover": null,- "theme": "light",- "toast": null,- "viewBackgroundColor": "#ffffff",- "viewModeEnabled": false,- "zenModeEnabled": false,- "zoom": {- "value": 1,- },-}-`;diff --git a/packages/utils/tests/export.test.ts b/packages/utils/tests/export.test.tsindex 6bf5418bea..ef41b2f92a 100644--- a/packages/utils/tests/export.test.ts+++ b/packages/utils/tests/export.test.ts@@ -2,20 +2,37 @@ import { MIME_TYPES } from "@excalidraw/common";import * as clipboardModule from "@excalidraw/excalidraw/clipboard";import * as imageModule from "@excalidraw/excalidraw/data/image";import * as jsonModule from "@excalidraw/excalidraw/data/json";-import * as mockedSceneExportUtils from "@excalidraw/excalidraw/scene/export";+import * as staticSceneModule from "@excalidraw/excalidraw/renderer/staticScene";+import * as staticSvgSceneModule from "@excalidraw/excalidraw/renderer/staticSvgScene";import { diagramFactory } from "@excalidraw/excalidraw/tests/fixtures/diagramFixture";+import { API } from "@excalidraw/excalidraw/tests/helpers/api";+import { pointFrom } from "@excalidraw/math";import { vi } from "vitest";import * as utils from "../src";-const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg");+import type { ExportSceneConfig } from "../src";-describe("exportToCanvas", async () => {+describe("exportScene: canvas", async () => {const EXPORT_PADDING = 10;- it("with default arguments", async () => {- const canvas = await utils.exportToCanvas({- ...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),+ it("with default arguments (padding 10)", async () => {+ const canvas = await utils.exportScene({+ type: "canvas",+ data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),+ });++ expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);+ expect(canvas.height).toBe(100 + 2 * EXPORT_PADDING);+ });++ it("with padding", async () => {+ const canvas = await utils.exportScene({+ type: "canvas",+ data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),+ config: {+ padding: EXPORT_PADDING,+ },});expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);@@ -23,116 +40,222 @@ describe("exportToCanvas", async () => {});it("when custom width and height", async () => {- const canvas = await utils.exportToCanvas({- ...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),- getDimensions: () => ({ width: 200, height: 200, scale: 1 }),+ const canvas = await utils.exportScene({+ type: "canvas",+ data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),+ config: { width: 200, height: 200 },});expect(canvas.width).toBe(200);expect(canvas.height).toBe(200);});-});-describe("exportToBlob", async () => {- describe("mime type", () => {- it("should change image/jpg to image/jpeg", async () => {- const blob = await utils.exportToBlob({- ...diagramFactory(),- getDimensions: (width, height) => ({ width, height, scale: 1 }),- // testing typo in MIME type (jpg → jpeg)- mimeType: "image/jpg",- appState: {- exportBackground: true,+ it("derives a missing width/height from the aspect ratio", async () => {+ const elements = [+ API.createElement({ type: "rectangle", width: 200, height: 100 }),+ ];++ const fromHeight = await utils.exportScene({+ type: "canvas",+ data: { elements, files: null },+ config: { padding: EXPORT_PADDING, height: 50 },+ });+ // 30px of content height → 60px of content width, plus padding+ expect([fromHeight.width, fromHeight.height]).toEqual([80, 50]);++ const fromWidth = await utils.exportScene({+ type: "canvas",+ data: { elements, files: null },+ config: { padding: EXPORT_PADDING, width: 100 },+ });+ expect([fromWidth.width, fromWidth.height]).toEqual([100, 60]);+ });++ it("crops (doesn't scale) an x/y region by default", async () => {+ const canvas = await utils.exportScene({+ type: "canvas",+ data: {+ elements: [+ API.createElement({ type: "rectangle", width: 200, height: 100 }),+ ],+ files: null,+ },+ config: { padding: EXPORT_PADDING, x: 50, y: 0, width: 100, height: 100 },+ });++ // `fit: "none"` adds the padding around the region+ expect([canvas.width, canvas.height]).toEqual([120, 120]);+ });++ it("pads an x/y region on all sides", async () => {+ const renderSpy = vi.spyOn(staticSceneModule, "renderStaticScene");+ const canvas = await utils.exportScene({+ type: "canvas",+ data: {+ elements: [+ API.createElement({ type: "rectangle", width: 200, height: 100 }),+ ],+ files: null,+ },+ config: { padding: EXPORT_PADDING, x: 0, y: 0, width: 100, height: 100 },+ });++ // the canvas covers the scene from -10 to 110 on both axes+ expect([canvas.width, canvas.height]).toEqual([120, 120]);+ const { scrollX, scrollY } = renderSpy.mock.calls[0][0].appState;+ expect([scrollX, scrollY]).toEqual([EXPORT_PADDING, EXPORT_PADDING]);+ renderSpy.mockRestore();+ });++ it("ignores x/y when the content is scaled to fit", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const renderSpy = vi.spyOn(staticSceneModule, "renderStaticScene");+ const exportWith = (config: ExportSceneConfig) =>+ utils.exportScene({+ type: "canvas",+ data: {+ elements: [+ API.createElement({ type: "rectangle", width: 200, height: 100 }),+ ],+ files: null,},+ config: { padding: EXPORT_PADDING, ...config },});- expect(blob?.type).toBe(MIME_TYPES.jpg);+ const renderedScroll = (call: number) => {+ const { scrollX, scrollY } = renderSpy.mock.calls[call][0].appState;+ return [scrollX, scrollY];+ };++ await exportWith({ width: 100, height: 100, fit: "contain" });+ await exportWith({ width: 100, height: 100, fit: "contain", x: 30, y: 20 });+ await exportWith({ maxWidthOrHeight: 100 });+ // the types forbid x/y with maxWidthOrHeight, JS callers still can+ // @ts-expect-error+ await exportWith({ maxWidthOrHeight: 100, x: 30, y: 20 });++ expect(renderedScroll(1)).toEqual(renderedScroll(0));+ expect(renderedScroll(3)).toEqual(renderedScroll(2));+ expect(warn).toHaveBeenCalledTimes(2);+ warn.mockRestore();+ renderSpy.mockRestore();+ });++ it("keeps the padding of flat content", async () => {+ const line = API.createElement({+ type: "line",+ width: 200,+ height: 0,+ points: [pointFrom(0, 0), pointFrom(200, 0)],});- it("should default to image/png", async () => {- const blob = await utils.exportToBlob({- ...diagramFactory(),- });- expect(blob?.type).toBe(MIME_TYPES.png);+ const exportLine = (config: ExportSceneConfig) =>+ utils.exportScene({ type: "canvas", data: { elements: [line] }, config });++ // the padding used to be clamped against the content's (zero) height+ const fitted = await exportLine({ padding: 10, maxWidthOrHeight: 400 });+ expect([fitted.width, fitted.height]).toEqual([220, 20]);++ // never a zero-sized canvas, which can't be encoded+ const unpadded = await exportLine({ padding: 0 });+ expect([unpadded.width, unpadded.height]).toEqual([200, 1]);+ });++ it("derives a missing width/height after clamping the padding", async () => {+ const canvas = await utils.exportScene({+ type: "canvas",+ data: {+ elements: [+ API.createElement({ type: "rectangle", width: 200, height: 100 }),+ ],+ },+ // a 10px height leaves no room for the padding, so it's dropped+ config: { height: 10, padding: 10 },});- it("should warn when using quality with image/png", async () => {- const consoleSpy = vi- .spyOn(console, "warn")- .mockImplementationOnce(() => void 0);- await utils.exportToBlob({- ...diagramFactory(),- mimeType: MIME_TYPES.png,- quality: 1,- });- expect(consoleSpy).toHaveBeenCalledWith(- `"quality" will be ignored for "${MIME_TYPES.png}" mimeType`,- );+ expect([canvas.width, canvas.height]).toEqual([20, 10]);+ });++ it("with a scale function", async () => {+ const scale = vi.fn((width: number, height: number) => 60 / width);+ const canvas = await utils.exportScene({+ type: "canvas",+ data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),+ config: { padding: EXPORT_PADDING, scale },+ });++ // receives the export dimensions at scale 1, padding included+ expect(scale).toHaveBeenCalledWith(120, 120);+ expect(canvas.width).toBe(60);+ expect(canvas.height).toBe(60);+ });++ it("rounds the canvas dimensions", async () => {+ const size = 29 / 1.1;+ const canvas = await utils.exportScene({+ type: "canvas",+ data: {+ elements: [+ API.createElement({ type: "rectangle", width: size, height: size }),+ ],+ files: null,+ },+ // size * 1.1 === 28.999999999999996+ config: { scale: 1.1, padding: 0 },});++ expect(canvas.width).toBe(29);+ expect(canvas.height).toBe(29);});});-describe("exportToSvg", () => {- const passedElements = () => exportToSvgSpy.mock.calls[0][0];- const passedOptions = () => exportToSvgSpy.mock.calls[0][1];+describe("exportScene: png & jpeg", () => {+ it("exports the requested image type", async () => {+ const png = await utils.exportScene({+ type: "png",+ data: diagramFactory(),+ });+ expect(png.type).toBe(MIME_TYPES.png);- afterEach(() => {- vi.clearAllMocks();+ const jpeg = await utils.exportScene({+ type: "jpeg",+ data: diagramFactory(),+ });+ expect(jpeg.type).toBe(MIME_TYPES.jpg);});+});+describe("exportScene: svg", () => {it("with default arguments", async () => {- await utils.exportToSvg({- ...diagramFactory({- overrides: { appState: void 0 },- }),+ const svg = await utils.exportScene({+ type: "svg",+ data: diagramFactory({ overrides: { appState: void 0 } }),});- const passedOptionsWhenDefault = {- ...passedOptions(),- // To avoid varying snapshots- name: "name",- };- expect(passedElements().length).toBe(3);- expect(passedOptionsWhenDefault).toMatchSnapshot();+ expect(svg.querySelectorAll("[data-id]")).toHaveLength(3);});- // Regression test: when all elements are deleted, exportToSvg should pass- // zero elements to the lower-level export (line 184-188 of export.ts calls- // getNonDeletedElements which filters them out).+ // Regression test (#11470): deleted elements must be filtered out at+ // runtime (inside `configExportDimension`), since the type contract alone+ // doesn't protect JS consumers passing raw scene data.it("with deleted elements", async () => {- await utils.exportToSvg({- ...diagramFactory({+ const svg = await utils.exportScene({+ type: "svg",+ data: diagramFactory({overrides: { appState: void 0 },elementOverrides: { isDeleted: true },}),});- expect(passedElements().length).toBe(0);- });-- it("with exportPadding", async () => {- await utils.exportToSvg({- ...diagramFactory({- overrides: { appState: { name: "diagram name" } },- }),- exportPadding: 0,- });-- expect(passedElements().length).toBe(3);- expect(passedOptions()).toEqual(- expect.objectContaining({ exportPadding: 0 }),- );+ expect(svg.querySelectorAll("[data-id]")).toHaveLength(0);});- it("with exportEmbedScene", async () => {- await utils.exportToSvg({- ...diagramFactory({- overrides: {- appState: { name: "diagram name", exportEmbedScene: true },- },- }),+ it("with embedScene", async () => {+ const svg = await utils.exportScene({+ type: "svg",+ data: diagramFactory({ overrides: { appState: void 0 } }),+ config: { embedScene: true },});- expect(passedElements().length).toBe(3);- expect(passedOptions().exportEmbedScene).toBe(true);+ expect(svg.querySelector("metadata")?.innerHTML).toContain("payload-start");});});@@ -159,43 +282,55 @@ describe("elements lacking creation metadata", () => {vi.restoreAllMocks();});- it("exportToSvg and exportToCanvas restore the elements", async () => {- const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg");+ it("svg and canvas exports render the restored elements", async () => {+ const renderSvgSpy = vi.spyOn(staticSvgSceneModule, "renderSceneToSvg");const diagram = legacyDiagram();- await utils.exportToSvg(diagram);+ await utils.exportScene({ type: "svg", data: diagram });- expect(createdOf(exportToSvgSpy.mock.calls[0][0])).toEqual([+ expect(createdOf(renderSvgSpy.mock.calls[0][0])).toEqual([null,null,null,]);expect(diagram.elements[0]).not.toHaveProperty("created");- const exportToCanvasSpy = vi.spyOn(- mockedSceneExportUtils,- "exportToCanvas",+ const renderCanvasSpy = vi.spyOn(staticSceneModule, "renderStaticScene");+ const canvas = await utils.exportScene({ type: "canvas", data: diagram });++ expect(createdOf(renderCanvasSpy.mock.calls[0][0].visibleElements)).toEqual(+ [null, null, null],);- const canvas = await utils.exportToCanvas(diagram);+ expect(canvas.width).toBeGreaterThan(0);+ });++ it("svg export embeds the restored scene", async () => {+ const serializeSpy = vi.spyOn(jsonModule, "serializeAsJSON");++ await utils.exportScene({+ type: "svg",+ data: legacyDiagram(),+ config: { embedScene: true },+ });- expect(createdOf(exportToCanvasSpy.mock.calls[0][0])).toEqual([+ expect(serializeSpy).toHaveBeenCalledTimes(1);+ expect(createdOf(serializeSpy.mock.calls[0][0])).toEqual([null,null,null,]);- expect(canvas.width).toBeGreaterThan(0);});- it("exportToBlob embeds the restored scene into png metadata", async () => {+ it("png export embeds the restored scene into its metadata", async () => {const serializeSpy = vi.spyOn(jsonModule, "serializeAsJSON");vi.spyOn(imageModule, "encodePngMetadata").mockImplementation(async ({ blob }) => blob,);- await utils.exportToBlob({- ...legacyDiagram(),- mimeType: MIME_TYPES.png,- appState: { exportEmbedScene: true },+ await utils.exportScene({+ type: "png",+ data: legacyDiagram(),+ config: { embedScene: true },});expect(serializeSpy).toHaveBeenCalledTimes(1);@@ -211,7 +346,7 @@ describe("elements lacking creation metadata", () => {.spyOn(clipboardModule, "copyToClipboard").mockResolvedValue(undefined);- await utils.exportToClipboard({ ...legacyDiagram(), type: "json" });+ await utils.exportToClipboard({ type: "json", data: legacyDiagram() });expect(copySpy).toHaveBeenCalledTimes(1);expect(createdOf(copySpy.mock.calls[0][0])).toEqual([null, null, null]);diff --git a/packages/utils/tests/utils.unmocked.test.ts b/packages/utils/tests/utils.unmocked.test.tsindex b77bc37d1c..9c7798c938 100644--- a/packages/utils/tests/utils.unmocked.test.ts+++ b/packages/utils/tests/utils.unmocked.test.ts@@ -11,21 +11,24 @@ import * as utils from "../src";// mocked and unmocked API in the same file.describe("embedding scene data", () => {- describe("exportToSvg", () => {+ describe("svg", () => {it("embedding scene data shouldn't modify them", async () => {const rectangle = API.createElement({ type: "rectangle" });const ellipse = API.createElement({ type: "ellipse" });const sourceElements = [rectangle, ellipse];- const svgNode = await utils.exportToSvg({- elements: sourceElements,- appState: {- viewBackgroundColor: "#ffffff",- gridModeEnabled: false,- exportEmbedScene: true,+ const svgNode = await utils.exportScene({+ type: "svg",+ data: {+ elements: sourceElements,+ appState: {+ viewBackgroundColor: "#ffffff",+ gridModeEnabled: false,+ },+ files: null,},- files: null,+ config: { embedScene: true },});const svg = svgNode.outerHTML;@@ -41,22 +44,24 @@ describe("embedding scene data", () => {// skipped because we can't test png encoding right now// (canvas.toBlob not supported in jsdom)- describe.skip("exportToBlob", () => {+ describe.skip("png", () => {it("embedding scene data shouldn't modify them", async () => {const rectangle = API.createElement({ type: "rectangle" });const ellipse = API.createElement({ type: "ellipse" });const sourceElements = [rectangle, ellipse];- const blob = await utils.exportToBlob({- mimeType: "image/png",- elements: sourceElements,- appState: {- viewBackgroundColor: "#ffffff",- gridModeEnabled: false,- exportEmbedScene: true,+ const blob = await utils.exportScene({+ type: "png",+ data: {+ elements: sourceElements,+ appState: {+ viewBackgroundColor: "#ffffff",+ gridModeEnabled: false,+ },+ files: null,},- files: null,+ config: { embedScene: true },});const parsedString = await decodePngMetadata(blob);