Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1625edeb07 |
@@ -25,15 +25,19 @@ export const AIComponents = ({
|
|||||||
const appState = excalidrawAPI.getAppState();
|
const appState = excalidrawAPI.getAppState();
|
||||||
|
|
||||||
const blob = await exportToBlob({
|
const blob = await exportToBlob({
|
||||||
elements: children,
|
data: {
|
||||||
appState: {
|
elements: children,
|
||||||
...appState,
|
appState: {
|
||||||
exportBackground: true,
|
...appState,
|
||||||
viewBackgroundColor: appState.viewBackgroundColor,
|
exportBackground: true,
|
||||||
|
viewBackgroundColor: appState.viewBackgroundColor,
|
||||||
|
},
|
||||||
|
files: excalidrawAPI.getFiles(),
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
exportingFrame: frame,
|
||||||
|
mimeType: MIME_TYPES.jpg,
|
||||||
},
|
},
|
||||||
exportingFrame: frame,
|
|
||||||
files: excalidrawAPI.getFiles(),
|
|
||||||
mimeType: MIME_TYPES.jpg,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const dataURL = await getDataURL(blob);
|
const dataURL = await getDataURL(blob);
|
||||||
|
|||||||
@@ -330,22 +330,30 @@ describe("Cropping and other features", async () => {
|
|||||||
const widthToHeightRatio = image.width / image.height;
|
const widthToHeightRatio = image.width / image.height;
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
elements: [image],
|
data: {
|
||||||
// @ts-ignore
|
elements: [image],
|
||||||
appState: h.state,
|
// @ts-ignore
|
||||||
files: h.app.files,
|
appState: h.state,
|
||||||
exportPadding: 0,
|
files: h.app.files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const exportedCanvasRatio = canvas.width / canvas.height;
|
const exportedCanvasRatio = canvas.width / canvas.height;
|
||||||
|
|
||||||
expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);
|
expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: [image],
|
data: {
|
||||||
// @ts-ignore
|
elements: [image],
|
||||||
appState: h.state,
|
// @ts-ignore
|
||||||
files: h.app.files,
|
appState: h.state,
|
||||||
exportPadding: 0,
|
files: h.app.files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const svgWidth = svg.getAttribute("width");
|
const svgWidth = svg.getAttribute("width");
|
||||||
const svgHeight = svg.getAttribute("height");
|
const svgHeight = svg.getAttribute("height");
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { exportToCanvas } from "@excalidraw/utils/export";
|
|
||||||
import React, { useEffect, useRef, useState } from "react";
|
import React, { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -6,6 +5,7 @@ import {
|
|||||||
EXPORT_IMAGE_TYPES,
|
EXPORT_IMAGE_TYPES,
|
||||||
isFirefox,
|
isFirefox,
|
||||||
EXPORT_SCALES,
|
EXPORT_SCALES,
|
||||||
|
THEME,
|
||||||
cloneJSON,
|
cloneJSON,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
@@ -26,6 +26,7 @@ import { useCopyStatus } from "../hooks/useCopiedIndicator";
|
|||||||
|
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { isSomeElementSelected } from "../scene";
|
import { isSomeElementSelected } from "../scene";
|
||||||
|
import { exportToCanvas } from "../scene/export";
|
||||||
|
|
||||||
import { copyIcon, downloadIcon, helpIcon } from "./icons";
|
import { copyIcon, downloadIcon, helpIcon } from "./icons";
|
||||||
import { Dialog } from "./Dialog";
|
import { Dialog } from "./Dialog";
|
||||||
@@ -128,19 +129,26 @@ const ImageExportModal = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
exportToCanvas({
|
exportToCanvas({
|
||||||
elements: exportedElements,
|
data: {
|
||||||
appState: {
|
elements: exportedElements,
|
||||||
...appStateSnapshot,
|
appState: {
|
||||||
name: projectName,
|
...appStateSnapshot,
|
||||||
exportBackground: exportWithBackground,
|
name: projectName,
|
||||||
exportWithDarkMode,
|
exportBackground: exportWithBackground,
|
||||||
exportScale,
|
exportScale,
|
||||||
exportEmbedScene: embedScene,
|
exportEmbedScene: embedScene,
|
||||||
|
},
|
||||||
|
files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: DEFAULT_EXPORT_PADDING,
|
||||||
|
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
|
||||||
|
exportingFrame,
|
||||||
|
theme: exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
|
||||||
|
canvasBackgroundColor: exportWithBackground
|
||||||
|
? appStateSnapshot.viewBackgroundColor
|
||||||
|
: false,
|
||||||
},
|
},
|
||||||
files,
|
|
||||||
exportPadding: DEFAULT_EXPORT_PADDING,
|
|
||||||
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
|
|
||||||
exportingFrame,
|
|
||||||
})
|
})
|
||||||
.then(async (canvas) => {
|
.then(async (canvas) => {
|
||||||
if (isStaleRequest()) {
|
if (isStaleRequest()) {
|
||||||
|
|||||||
@@ -72,18 +72,20 @@ const ChartPreviewBtn = (props: {
|
|||||||
const previewNode = previewRef.current!;
|
const previewNode = previewRef.current!;
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
svg = await exportToSvg(
|
svg = await exportToSvg({
|
||||||
elements,
|
data: {
|
||||||
{
|
elements,
|
||||||
exportBackground: false,
|
appState: {
|
||||||
viewBackgroundColor: "#fff",
|
exportBackground: false,
|
||||||
exportWithDarkMode: theme === "dark",
|
viewBackgroundColor: "#fff",
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
},
|
},
|
||||||
null, // files
|
config: {
|
||||||
{
|
|
||||||
skipInliningFonts: true,
|
skipInliningFonts: true,
|
||||||
|
theme,
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
svg.querySelector(".style-fonts")?.remove();
|
svg.querySelector(".style-fonts")?.remove();
|
||||||
previewNode.replaceChildren();
|
previewNode.replaceChildren();
|
||||||
previewNode.appendChild(svg);
|
previewNode.appendChild(svg);
|
||||||
@@ -134,18 +136,20 @@ const PlainTextPreviewBtn = (props: {
|
|||||||
const previewNode = previewRef.current!;
|
const previewNode = previewRef.current!;
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
const svg = await exportToSvg(
|
const svg = await exportToSvg({
|
||||||
[textElement],
|
data: {
|
||||||
{
|
elements: [textElement],
|
||||||
exportBackground: false,
|
appState: {
|
||||||
viewBackgroundColor: "#fff",
|
exportBackground: false,
|
||||||
exportWithDarkMode: theme === "dark",
|
viewBackgroundColor: "#fff",
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
},
|
},
|
||||||
null,
|
config: {
|
||||||
{
|
|
||||||
skipInliningFonts: true,
|
skipInliningFonts: true,
|
||||||
|
theme,
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
svg.querySelector(".style-fonts")?.remove();
|
svg.querySelector(".style-fonts")?.remove();
|
||||||
previewNode.replaceChildren();
|
previewNode.replaceChildren();
|
||||||
previewNode.appendChild(svg);
|
previewNode.appendChild(svg);
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { exportToCanvas, exportToSvg } from "@excalidraw/utils/export";
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -13,6 +12,7 @@ import {
|
|||||||
import { EditorLocalStorage } from "../data/EditorLocalStorage";
|
import { EditorLocalStorage } from "../data/EditorLocalStorage";
|
||||||
import { canvasToBlob, resizeImageFile } from "../data/blob";
|
import { canvasToBlob, resizeImageFile } from "../data/blob";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
|
import { exportToCanvas, exportToSvg } from "../scene/export";
|
||||||
|
|
||||||
import { Dialog } from "./Dialog";
|
import { Dialog } from "./Dialog";
|
||||||
import DialogActionButton from "./DialogActionButton";
|
import DialogActionButton from "./DialogActionButton";
|
||||||
@@ -63,9 +63,14 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
for (const [index, item] of libraryItems.entries()) {
|
for (const [index, item] of libraryItems.entries()) {
|
||||||
const itemCanvas = await exportToCanvas({
|
const itemCanvas = await exportToCanvas({
|
||||||
elements: item.elements,
|
data: {
|
||||||
files: null,
|
elements: item.elements,
|
||||||
maxWidthOrHeight: BOX_SIZE,
|
files: null,
|
||||||
|
appState: {},
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
maxWidthOrHeight: BOX_SIZE,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { width, height } = itemCanvas;
|
const { width, height } = itemCanvas;
|
||||||
@@ -127,14 +132,18 @@ const SingleLibraryItem = ({
|
|||||||
}
|
}
|
||||||
(async () => {
|
(async () => {
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: libItem.elements,
|
data: {
|
||||||
appState: {
|
elements: libItem.elements,
|
||||||
...appState,
|
appState: {
|
||||||
viewBackgroundColor: "#fff",
|
...appState,
|
||||||
exportBackground: true,
|
viewBackgroundColor: "#fff",
|
||||||
|
exportBackground: true,
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
skipInliningFonts: true,
|
||||||
},
|
},
|
||||||
files: null,
|
|
||||||
skipInliningFonts: true,
|
|
||||||
});
|
});
|
||||||
node.innerHTML = svg.outerHTML;
|
node.innerHTML = svg.outerHTML;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import { DEFAULT_EXPORT_PADDING, EDITOR_LS_KEYS } from "@excalidraw/common";
|
||||||
DEFAULT_EXPORT_PADDING,
|
|
||||||
EDITOR_LS_KEYS,
|
|
||||||
THEME,
|
|
||||||
} from "@excalidraw/common";
|
|
||||||
|
|
||||||
import { convertToExcalidrawElements } from "@excalidraw/element";
|
import { convertToExcalidrawElements } from "@excalidraw/element";
|
||||||
|
|
||||||
@@ -105,14 +101,16 @@ export const convertMermaidToExcalidraw = async ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
elements: data.current.elements,
|
data: {
|
||||||
files: data.current.files,
|
elements: data.current.elements,
|
||||||
exportPadding: DEFAULT_EXPORT_PADDING,
|
files: data.current.files,
|
||||||
maxWidthOrHeight:
|
},
|
||||||
Math.max(parent.offsetWidth, parent.offsetHeight) *
|
config: {
|
||||||
window.devicePixelRatio,
|
padding: DEFAULT_EXPORT_PADDING,
|
||||||
appState: {
|
maxWidthOrHeight:
|
||||||
exportWithDarkMode: theme === THEME.DARK,
|
Math.max(parent.offsetWidth, parent.offsetHeight) *
|
||||||
|
window.devicePixelRatio,
|
||||||
|
theme,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
IMAGE_MIME_TYPES,
|
IMAGE_MIME_TYPES,
|
||||||
isFirefox,
|
isFirefox,
|
||||||
MIME_TYPES,
|
MIME_TYPES,
|
||||||
|
THEME,
|
||||||
cloneJSON,
|
cloneJSON,
|
||||||
SVG_DOCUMENT_PREAMBLE,
|
SVG_DOCUMENT_PREAMBLE,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
@@ -115,20 +116,29 @@ export const exportCanvas = async (
|
|||||||
if (elements.length === 0) {
|
if (elements.length === 0) {
|
||||||
throw new Error(t("alerts.cannotExportEmptyCanvas"));
|
throw new Error(t("alerts.cannotExportEmptyCanvas"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const theme = appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT;
|
||||||
|
|
||||||
if (type === "svg" || type === "clipboard-svg") {
|
if (type === "svg" || type === "clipboard-svg") {
|
||||||
const svgPromise = exportToSvg(
|
const svgPromise = exportToSvg({
|
||||||
elements,
|
data: {
|
||||||
{
|
elements,
|
||||||
exportBackground,
|
appState: {
|
||||||
exportWithDarkMode: appState.exportWithDarkMode,
|
...appState,
|
||||||
viewBackgroundColor,
|
exportBackground,
|
||||||
exportPadding,
|
exportEmbedScene: appState.exportEmbedScene && type === "svg",
|
||||||
exportScale: appState.exportScale,
|
},
|
||||||
exportEmbedScene: appState.exportEmbedScene && type === "svg",
|
files,
|
||||||
},
|
},
|
||||||
files,
|
config: {
|
||||||
{ exportingFrame },
|
padding: exportPadding,
|
||||||
);
|
exportingFrame,
|
||||||
|
theme,
|
||||||
|
canvasBackgroundColor: exportBackground
|
||||||
|
? viewBackgroundColor
|
||||||
|
: "transparent",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
if (type === "svg") {
|
if (type === "svg") {
|
||||||
return fileSave(
|
return fileSave(
|
||||||
@@ -158,11 +168,19 @@ export const exportCanvas = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tempCanvas = exportToCanvas(elements, appState, files, {
|
const tempCanvas = exportToCanvas({
|
||||||
exportBackground,
|
data: {
|
||||||
viewBackgroundColor,
|
elements,
|
||||||
exportPadding,
|
appState,
|
||||||
exportingFrame,
|
files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
canvasBackgroundColor: exportBackground ? viewBackgroundColor : false,
|
||||||
|
padding: exportPadding,
|
||||||
|
theme,
|
||||||
|
scale: appState.exportScale,
|
||||||
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (type === "png") {
|
if (type === "png") {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { exportToSvg } from "@excalidraw/utils/export";
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
import { COLOR_PALETTE } from "@excalidraw/common";
|
import { COLOR_PALETTE } from "@excalidraw/common";
|
||||||
|
|
||||||
|
import { exportToSvg } from "../scene/export";
|
||||||
|
|
||||||
import { atom, useAtom } from "../editor-jotai";
|
import { atom, useAtom } from "../editor-jotai";
|
||||||
|
|
||||||
import type { LibraryItem } from "../types";
|
import type { LibraryItem } from "../types";
|
||||||
@@ -12,17 +13,18 @@ export type SvgCache = Map<LibraryItem["id"], SVGSVGElement>;
|
|||||||
export const libraryItemSvgsCache = atom<SvgCache>(new Map());
|
export const libraryItemSvgsCache = atom<SvgCache>(new Map());
|
||||||
|
|
||||||
const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => {
|
const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => {
|
||||||
// TODO should pass theme (appState.exportWithDark) - we're still using
|
|
||||||
// CSS filter here
|
|
||||||
return await exportToSvg({
|
return await exportToSvg({
|
||||||
elements,
|
data: {
|
||||||
appState: {
|
elements,
|
||||||
exportBackground: false,
|
appState: {
|
||||||
viewBackgroundColor: COLOR_PALETTE.white,
|
exportBackground: false,
|
||||||
|
viewBackgroundColor: COLOR_PALETTE.white,
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
skipInliningFonts: true,
|
||||||
},
|
},
|
||||||
files: null,
|
|
||||||
renderEmbeddables: false,
|
|
||||||
skipInliningFonts: true,
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { getDefaultAppState } from "./appState";
|
|
||||||
import { exportToCanvas } from "./scene/export";
|
import { exportToCanvas } from "./scene/export";
|
||||||
|
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
@@ -59,26 +58,23 @@ const elements = [
|
|||||||
registerFont("./public/Virgil.woff2", { family: "Virgil" });
|
registerFont("./public/Virgil.woff2", { family: "Virgil" });
|
||||||
registerFont("./public/Cascadia.woff2", { family: "Cascadia" });
|
registerFont("./public/Cascadia.woff2", { family: "Cascadia" });
|
||||||
|
|
||||||
const canvas = exportToCanvas(
|
(async () => {
|
||||||
elements as any,
|
const canvas = await exportToCanvas({
|
||||||
{
|
data: {
|
||||||
...getDefaultAppState(),
|
elements: elements as any,
|
||||||
offsetTop: 0,
|
appState: {},
|
||||||
offsetLeft: 0,
|
files: {},
|
||||||
width: 0,
|
},
|
||||||
height: 0,
|
config: {
|
||||||
},
|
canvasBackgroundColor: "#ffffff",
|
||||||
{}, // files
|
createCanvas,
|
||||||
{
|
},
|
||||||
exportBackground: true,
|
});
|
||||||
viewBackgroundColor: "#ffffff",
|
|
||||||
},
|
|
||||||
createCanvas,
|
|
||||||
);
|
|
||||||
|
|
||||||
const out = fs.createWriteStream("test.png");
|
const out = fs.createWriteStream("test.png");
|
||||||
const stream = (canvas as any).createPNGStream();
|
const stream = (canvas as any).createPNGStream();
|
||||||
stream.pipe(out);
|
stream.pipe(out);
|
||||||
out.on("finish", () => {
|
out.on("finish", () => {
|
||||||
console.info("test.png was created.");
|
console.info("test.png was created.");
|
||||||
});
|
});
|
||||||
|
})();
|
||||||
|
|||||||
@@ -304,7 +304,9 @@ export {
|
|||||||
exportToBlob,
|
exportToBlob,
|
||||||
exportToSvg,
|
exportToSvg,
|
||||||
exportToClipboard,
|
exportToClipboard,
|
||||||
} from "@excalidraw/utils/export";
|
} from "./scene/export";
|
||||||
|
|
||||||
|
export type { ExportSceneData, ExportSceneConfig } from "./scene/export";
|
||||||
|
|
||||||
export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";
|
export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";
|
||||||
export {
|
export {
|
||||||
|
|||||||
+672
-123
@@ -1,13 +1,13 @@
|
|||||||
import rough from "roughjs/bin/rough";
|
import rough from "roughjs/bin/rough";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
DEFAULT_EXPORT_PADDING,
|
|
||||||
FRAME_STYLE,
|
FRAME_STYLE,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
SVG_NS,
|
SVG_NS,
|
||||||
THEME,
|
THEME,
|
||||||
MIME_TYPES,
|
MIME_TYPES,
|
||||||
EXPORT_DATA_TYPES,
|
EXPORT_DATA_TYPES,
|
||||||
|
COLOR_WHITE,
|
||||||
arrayToMap,
|
arrayToMap,
|
||||||
distance,
|
distance,
|
||||||
getFontString,
|
getFontString,
|
||||||
@@ -47,20 +47,33 @@ import type {
|
|||||||
ExcalidrawTextElement,
|
ExcalidrawTextElement,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
NonDeletedSceneElementsMap,
|
NonDeletedSceneElementsMap,
|
||||||
|
Theme,
|
||||||
} from "@excalidraw/element/types";
|
} from "@excalidraw/element/types";
|
||||||
|
|
||||||
import { getDefaultAppState } from "../appState";
|
import { getDefaultAppState } from "../appState";
|
||||||
import { base64ToString, decode, encode, stringToBase64 } from "../data/encode";
|
import { base64ToString, decode, encode, stringToBase64 } from "../data/encode";
|
||||||
import { serializeAsJSON } from "../data/json";
|
import { serializeAsJSON } from "../data/json";
|
||||||
|
import { restoreAppState } from "../data/restore";
|
||||||
|
import { encodePngMetadata } from "../data/image";
|
||||||
|
|
||||||
import { Fonts } from "../fonts";
|
import { Fonts } from "../fonts";
|
||||||
|
|
||||||
import { renderStaticScene } from "../renderer/staticScene";
|
import { renderStaticScene } from "../renderer/staticScene";
|
||||||
import { renderSceneToSvg } from "../renderer/staticSvgScene";
|
import { renderSceneToSvg } from "../renderer/staticSvgScene";
|
||||||
|
|
||||||
|
import {
|
||||||
|
copyBlobToClipboardAsPng,
|
||||||
|
copyTextToSystemClipboard,
|
||||||
|
copyToClipboard,
|
||||||
|
} from "../clipboard";
|
||||||
|
|
||||||
import type { RenderableElementsMap } from "./types";
|
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;
|
||||||
|
const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;
|
||||||
|
|
||||||
const truncateText = (element: ExcalidrawTextElement, maxWidth: number) => {
|
const truncateText = (element: ExcalidrawTextElement, maxWidth: number) => {
|
||||||
if (element.width <= maxWidth) {
|
if (element.width <= maxWidth) {
|
||||||
@@ -169,36 +182,205 @@ const prepareElementsForRender = ({
|
|||||||
return nextElements;
|
return nextElements;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToCanvas = async (
|
// ---------------------------------------------------------------------------
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
// Types for the new API
|
||||||
appState: AppState,
|
// ---------------------------------------------------------------------------
|
||||||
files: BinaryFiles,
|
|
||||||
{
|
export type ExportSceneData = {
|
||||||
exportBackground,
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
appState?: Partial<
|
||||||
viewBackgroundColor,
|
Omit<AppState, "offsetTop" | "offsetLeft" | "exportWithDarkMode">
|
||||||
exportingFrame,
|
>;
|
||||||
}: {
|
files: BinaryFiles | null;
|
||||||
exportBackground: boolean;
|
};
|
||||||
exportPadding?: number;
|
|
||||||
viewBackgroundColor: string;
|
export type ExportSceneConfig = {
|
||||||
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
theme?: Theme;
|
||||||
},
|
/**
|
||||||
createCanvas: (
|
* Canvas background. Valid values are:
|
||||||
|
*
|
||||||
|
* - `undefined` - the background of "appState.viewBackgroundColor" is used.
|
||||||
|
* - `false` - no background is used (set to "transparent").
|
||||||
|
* - `string` - should be a valid CSS color.
|
||||||
|
*
|
||||||
|
* @default undefined
|
||||||
|
*/
|
||||||
|
canvasBackgroundColor?: string | false;
|
||||||
|
/**
|
||||||
|
* Canvas padding in pixels. Affected by `scale`.
|
||||||
|
*
|
||||||
|
* When `fit` is set to `none`, padding is added to the content bounding box
|
||||||
|
* (including if you set `width` or `height` or `maxWidthOrHeight` or
|
||||||
|
* `widthOrHeight`).
|
||||||
|
*
|
||||||
|
* When `fit` set to `contain`, padding is subtracted from the content
|
||||||
|
* bounding box (ensuring the size doesn't exceed the supplied values, with
|
||||||
|
* the exeception of using alongside `scale` as noted above), and the padding
|
||||||
|
* serves as a minimum distance between the content and the canvas edges, as
|
||||||
|
* it may exceed the supplied padding value from one side or the other in
|
||||||
|
* order to maintain the aspect ratio. It is recommended to set `position`
|
||||||
|
* to `center` when using `fit=contain`.
|
||||||
|
*
|
||||||
|
* When `fit` is set to `none` and either `width` or `height` or
|
||||||
|
* `maxWidthOrHeight` is set, padding is simply adding to the bounding box
|
||||||
|
* and the content may overflow the canvas, thus right or bottom padding
|
||||||
|
* may be ignored.
|
||||||
|
*
|
||||||
|
* @default 0
|
||||||
|
*/
|
||||||
|
padding?: number;
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* 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`.
|
||||||
|
*/
|
||||||
|
maxWidthOrHeight?: number;
|
||||||
|
/**
|
||||||
|
* Scale the canvas content to be excatly this many pixels wide/tall,
|
||||||
|
* maintaining the aspect ratio.
|
||||||
|
*
|
||||||
|
* Cannot be used in conjunction with `maxWidthOrHeight`.
|
||||||
|
*
|
||||||
|
* Final dimensions can get smaller/larger if used in conjunction with
|
||||||
|
* `scale`.
|
||||||
|
*/
|
||||||
|
widthOrHeight?: number;
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* Width of the frame. Supply `x` or `y` if you want to ofsset the canvas
|
||||||
|
* content.
|
||||||
|
*
|
||||||
|
* If `width` omitted but `height` supplied, `width` is calculated from the
|
||||||
|
* the content's bounding box to preserve the aspect ratio.
|
||||||
|
*
|
||||||
|
* Defaults to the content bounding box width when both `width` and `height`
|
||||||
|
* are omitted.
|
||||||
|
*/
|
||||||
|
width?: number;
|
||||||
|
/**
|
||||||
|
* Height of the frame.
|
||||||
|
*
|
||||||
|
* If `height` omitted but `width` supplied, `height` is calculated from the
|
||||||
|
* content's bounding box to preserve the aspect ratio.
|
||||||
|
*
|
||||||
|
* Defaults to the content bounding box height when both `width` and `height`
|
||||||
|
* are omitted.
|
||||||
|
*/
|
||||||
|
height?: number;
|
||||||
|
/**
|
||||||
|
* Left canvas offset. By default the coordinate is relative to the canvas.
|
||||||
|
* You can switch to content coordinates by setting `origin` to `content`.
|
||||||
|
*
|
||||||
|
* Defaults to the `x` postion of the content bounding box.
|
||||||
|
*/
|
||||||
|
x?: number;
|
||||||
|
/**
|
||||||
|
* Top canvas offset. By default the coordinate is relative to the canvas.
|
||||||
|
* You can switch to content coordinates by setting `origin` to `content`.
|
||||||
|
*
|
||||||
|
* Defaults to the `y` postion of the content bounding box.
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
*
|
||||||
|
* @default "canvas"
|
||||||
|
*/
|
||||||
|
origin?: "canvas" | "content";
|
||||||
|
/**
|
||||||
|
* If dimensions specified and `x` and `y` are not specified, this indicates
|
||||||
|
* how the canvas should be scaled.
|
||||||
|
*
|
||||||
|
* Behavior aligns with the `object-fit` CSS property.
|
||||||
|
*
|
||||||
|
* - `none` - no scaling.
|
||||||
|
* - `contain` - scale to fit the frame. Includes `padding`.
|
||||||
|
*
|
||||||
|
* If `maxWidthOrHeight` or `widthOrHeight` is set, `fit` is ignored.
|
||||||
|
*
|
||||||
|
* @default "contain" unless `width`, `height`, `maxWidthOrHeight`, or
|
||||||
|
* `widthOrHeight` is specified in which case `none` is the default (can be
|
||||||
|
* changed). If `x` or `y` are specified, `none` is forced.
|
||||||
|
*/
|
||||||
|
fit?: "none" | "contain";
|
||||||
|
/**
|
||||||
|
* When either `x` or `y` are not specified, indicates how the canvas should
|
||||||
|
* be aligned on the respective axis.
|
||||||
|
*
|
||||||
|
* - `none` - canvas aligned to top left.
|
||||||
|
* - `center` - canvas is centered on the axis which is not specified
|
||||||
|
* (or both).
|
||||||
|
*
|
||||||
|
* If `maxWidthOrHeight` or `widthOrHeight` is set, `position` is ignored.
|
||||||
|
*
|
||||||
|
* @default "center"
|
||||||
|
*/
|
||||||
|
position?: "center" | "topLeft";
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
* @default 1
|
||||||
|
*/
|
||||||
|
scale?: number;
|
||||||
|
/**
|
||||||
|
* If you need to suply your own canvas, e.g. in test environments or in
|
||||||
|
* Node.js.
|
||||||
|
*
|
||||||
|
* Do not set `canvas.width/height` or modify the canvas context as that's
|
||||||
|
* handled by Excalidraw.
|
||||||
|
*
|
||||||
|
* Defaults to `document.createElement("canvas")`.
|
||||||
|
*/
|
||||||
|
createCanvas?: () => HTMLCanvasElement;
|
||||||
|
/**
|
||||||
|
* If you want to supply `width`/`height` dynamically (or derive from the
|
||||||
|
* content bounding box), you can use this function.
|
||||||
|
*
|
||||||
|
* Ignored if `maxWidthOrHeight`, `width`, or `height` is set.
|
||||||
|
*/
|
||||||
|
getDimensions?: (
|
||||||
width: number,
|
width: number,
|
||||||
height: number,
|
height: number,
|
||||||
) => { canvas: HTMLCanvasElement; scale: number } = (width, height) => {
|
) => { width: number; height: number; scale?: number };
|
||||||
const canvas = document.createElement("canvas");
|
|
||||||
canvas.width = width * appState.exportScale;
|
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
||||||
canvas.height = height * appState.exportScale;
|
|
||||||
return { canvas, scale: appState.exportScale };
|
loadFonts?: () => Promise<void>;
|
||||||
},
|
};
|
||||||
loadFonts: () => Promise<void> = async () => {
|
|
||||||
await Fonts.loadElementsFonts(elements);
|
// ---------------------------------------------------------------------------
|
||||||
},
|
// Internal helper to configure export dimensions
|
||||||
) => {
|
// ---------------------------------------------------------------------------
|
||||||
// load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)
|
|
||||||
await loadFonts();
|
const configExportDimension = async ({
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
data: ExportSceneData;
|
||||||
|
config?: ExportSceneConfig;
|
||||||
|
}) => {
|
||||||
|
// clone
|
||||||
|
const cfg = Object.assign({}, config);
|
||||||
|
|
||||||
|
const { exportingFrame } = cfg;
|
||||||
|
|
||||||
|
const elements = data.elements;
|
||||||
|
|
||||||
|
// initialize defaults
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const appState = restoreAppState(data.appState, null);
|
||||||
|
|
||||||
const frameRendering = getFrameRenderingConfig(
|
const frameRendering = getFrameRenderingConfig(
|
||||||
exportingFrame ?? null,
|
exportingFrame ?? null,
|
||||||
@@ -218,26 +400,255 @@ export const exportToCanvas = async (
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (exportingFrame) {
|
if (exportingFrame) {
|
||||||
exportPadding = 0;
|
cfg.padding = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const [minX, minY, width, height] = getCanvasSize(
|
cfg.fit =
|
||||||
|
cfg.fit ??
|
||||||
|
(cfg.width != null ||
|
||||||
|
cfg.height != null ||
|
||||||
|
cfg.maxWidthOrHeight != null ||
|
||||||
|
cfg.widthOrHeight != null
|
||||||
|
? "contain"
|
||||||
|
: "none");
|
||||||
|
|
||||||
|
cfg.padding = cfg.padding ?? 0;
|
||||||
|
cfg.scale = cfg.scale ?? 1;
|
||||||
|
|
||||||
|
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.maxWidthOrHeight != null || cfg.width != null || cfg.height != null) &&
|
||||||
|
cfg.getDimensions
|
||||||
|
) {
|
||||||
|
if (!import.meta.env.PROD) {
|
||||||
|
console.warn(
|
||||||
|
"`getDimensions` is ignored when `width`, `height`, or `maxWidthOrHeight` is set",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
cfg.getDimensions = undefined;
|
||||||
|
}
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)
|
||||||
|
if (cfg.loadFonts) {
|
||||||
|
await cfg.loadFonts();
|
||||||
|
} else {
|
||||||
|
await Fonts.loadElementsFonts(elements);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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),
|
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;
|
||||||
|
|
||||||
const defaultAppState = getDefaultAppState();
|
x = cfg.x ?? x;
|
||||||
|
y = cfg.y ?? y;
|
||||||
|
width = cfg.width ?? width;
|
||||||
|
height = cfg.height ?? height;
|
||||||
|
|
||||||
|
if (cfg.fit === "contain" || cfg.widthOrHeight || cfg.maxWidthOrHeight) {
|
||||||
|
cfg.padding =
|
||||||
|
cfg.padding && cfg.padding > 0
|
||||||
|
? Math.min(
|
||||||
|
cfg.padding,
|
||||||
|
(width - DEFAULT_SMALLEST_EXPORT_SIZE) / 2,
|
||||||
|
(height - DEFAULT_SMALLEST_EXPORT_SIZE) / 2,
|
||||||
|
)
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
if (cfg.getDimensions != null) {
|
||||||
|
const ret = cfg.getDimensions(width, height);
|
||||||
|
|
||||||
|
width = ret.width;
|
||||||
|
height = ret.height;
|
||||||
|
|
||||||
|
cfg.padding = Math.min(
|
||||||
|
cfg.padding,
|
||||||
|
(width - DEFAULT_SMALLEST_EXPORT_SIZE) / 2,
|
||||||
|
(height - DEFAULT_SMALLEST_EXPORT_SIZE) / 2,
|
||||||
|
);
|
||||||
|
} else if (cfg.widthOrHeight != null) {
|
||||||
|
cfg.padding = Math.min(
|
||||||
|
cfg.padding,
|
||||||
|
(cfg.widthOrHeight - DEFAULT_SMALLEST_EXPORT_SIZE) / 2,
|
||||||
|
);
|
||||||
|
} else if (cfg.maxWidthOrHeight != null) {
|
||||||
|
cfg.padding = Math.min(
|
||||||
|
cfg.padding,
|
||||||
|
(cfg.maxWidthOrHeight - DEFAULT_SMALLEST_EXPORT_SIZE) / 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.getDimensions) {
|
||||||
|
const ret = cfg.getDimensions(width, height);
|
||||||
|
|
||||||
|
width = ret.width;
|
||||||
|
height = ret.height;
|
||||||
|
cfg.scale = ret.scale ?? cfg.scale;
|
||||||
|
} else if (cfg.fit === "contain") {
|
||||||
|
width -= cfg.padding * 2;
|
||||||
|
height -= cfg.padding * 2;
|
||||||
|
|
||||||
|
const wRatio = width / origWidth;
|
||||||
|
const hRatio = height / origHeight;
|
||||||
|
// scale the orig canvas to fit in the target region
|
||||||
|
exportScale = Math.min(wRatio, hRatio);
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
if (cfg.position === "center") {
|
||||||
|
x -=
|
||||||
|
width / exportScale / 2 -
|
||||||
|
(cfg.x == null ? origWidth : width + cfg.padding * 2) / 2;
|
||||||
|
y -=
|
||||||
|
height / exportScale / 2 -
|
||||||
|
(cfg.y == null ? origHeight : height + cfg.padding * 2) / 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;
|
||||||
|
|
||||||
|
// scale the whole frame by cfg.scale (on top of whatever canvasScale we
|
||||||
|
// calculated above)
|
||||||
|
exportScale *= cfg.scale;
|
||||||
|
|
||||||
|
width *= cfg.scale;
|
||||||
|
height *= cfg.scale;
|
||||||
|
|
||||||
|
const exportWidth = width + cfg.padding * 2 * cfg.scale;
|
||||||
|
const exportHeight = height + cfg.padding * 2 * cfg.scale;
|
||||||
|
|
||||||
|
return {
|
||||||
|
config: cfg,
|
||||||
|
normalizedPadding,
|
||||||
|
contentWidth: width,
|
||||||
|
contentHeight: height,
|
||||||
|
exportWidth,
|
||||||
|
exportHeight,
|
||||||
|
exportScale,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
elementsForRender,
|
||||||
|
appState,
|
||||||
|
frameRendering,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// exportToCanvas
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This API is usually used as a precursor to searializing to Blob or PNG,
|
||||||
|
* but can also be used to create a canvas for other purposes.
|
||||||
|
*/
|
||||||
|
export const exportToCanvas = async ({
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
data: ExportSceneData;
|
||||||
|
config?: ExportSceneConfig;
|
||||||
|
}) => {
|
||||||
|
const {
|
||||||
|
config: cfg,
|
||||||
|
normalizedPadding,
|
||||||
|
contentWidth: width,
|
||||||
|
contentHeight: height,
|
||||||
|
exportWidth,
|
||||||
|
exportHeight,
|
||||||
|
exportScale,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
elementsForRender,
|
||||||
|
appState,
|
||||||
|
frameRendering,
|
||||||
|
} = await configExportDimension({ data, config });
|
||||||
|
|
||||||
|
const canvas = cfg.createCanvas
|
||||||
|
? cfg.createCanvas()
|
||||||
|
: document.createElement("canvas");
|
||||||
|
|
||||||
|
canvas.width = exportWidth;
|
||||||
|
canvas.height = exportHeight;
|
||||||
|
|
||||||
const { imageCache } = await updateImageCache({
|
const { imageCache } = await updateImageCache({
|
||||||
imageCache: new Map(),
|
imageCache: new Map(),
|
||||||
fileIds: getInitializedImageElements(elementsForRender).map(
|
fileIds: getInitializedImageElements(elementsForRender).map(
|
||||||
(element) => element.fileId,
|
(element) => element.fileId,
|
||||||
),
|
),
|
||||||
files,
|
files: data.files || {},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const theme =
|
||||||
|
cfg.theme ?? (appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT);
|
||||||
|
|
||||||
|
// Determine the background color for the canvas
|
||||||
|
const viewBackgroundColor =
|
||||||
|
cfg.canvasBackgroundColor === false
|
||||||
|
? // "transparent" triggers clearRect in bootstrapCanvas
|
||||||
|
"transparent"
|
||||||
|
: cfg.canvasBackgroundColor ||
|
||||||
|
appState.viewBackgroundColor ||
|
||||||
|
COLOR_WHITE;
|
||||||
|
|
||||||
renderStaticScene({
|
renderStaticScene({
|
||||||
canvas,
|
canvas,
|
||||||
rc: rough.canvas(canvas),
|
rc: rough.canvas(canvas),
|
||||||
@@ -245,19 +656,23 @@ export const exportToCanvas = async (
|
|||||||
arrayToMap(elementsForRender),
|
arrayToMap(elementsForRender),
|
||||||
),
|
),
|
||||||
allElementsMap: toBrandedType<NonDeletedSceneElementsMap>(
|
allElementsMap: toBrandedType<NonDeletedSceneElementsMap>(
|
||||||
arrayToMap(syncInvalidIndices(elements)),
|
arrayToMap(syncInvalidIndices(data.elements)),
|
||||||
),
|
),
|
||||||
visibleElements: elementsForRender,
|
visibleElements: elementsForRender,
|
||||||
scale,
|
scale: exportScale,
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
frameRendering,
|
frameRendering,
|
||||||
viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
|
width,
|
||||||
scrollX: -minX + exportPadding,
|
height,
|
||||||
scrollY: -minY + exportPadding,
|
offsetLeft: 0,
|
||||||
zoom: defaultAppState.zoom,
|
offsetTop: 0,
|
||||||
|
scrollX: -x + normalizedPadding,
|
||||||
|
scrollY: -y + normalizedPadding,
|
||||||
|
zoom: { value: DEFAULT_ZOOM_VALUE },
|
||||||
shouldCacheIgnoreZoom: false,
|
shouldCacheIgnoreZoom: false,
|
||||||
theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
|
theme,
|
||||||
|
viewBackgroundColor,
|
||||||
},
|
},
|
||||||
renderConfig: {
|
renderConfig: {
|
||||||
canvasBackgroundColor: viewBackgroundColor,
|
canvasBackgroundColor: viewBackgroundColor,
|
||||||
@@ -268,13 +683,44 @@ export const exportToCanvas = async (
|
|||||||
embedsValidationStatus: new Map(),
|
embedsValidationStatus: new Map(),
|
||||||
elementsPendingErasure: new Set(),
|
elementsPendingErasure: new Set(),
|
||||||
pendingFlowchartNodes: null,
|
pendingFlowchartNodes: null,
|
||||||
theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
|
theme,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return canvas;
|
return canvas;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// exportToSvg
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
type ExportToSvgConfig = Pick<
|
||||||
|
ExportSceneConfig,
|
||||||
|
| "canvasBackgroundColor"
|
||||||
|
| "padding"
|
||||||
|
| "theme"
|
||||||
|
| "exportingFrame"
|
||||||
|
| "scale"
|
||||||
|
| "width"
|
||||||
|
| "height"
|
||||||
|
| "x"
|
||||||
|
| "y"
|
||||||
|
| "origin"
|
||||||
|
| "fit"
|
||||||
|
| "position"
|
||||||
|
| "maxWidthOrHeight"
|
||||||
|
| "widthOrHeight"
|
||||||
|
| "getDimensions"
|
||||||
|
| "loadFonts"
|
||||||
|
> & {
|
||||||
|
/**
|
||||||
|
* if true, all embeddables passed in will be rendered when possible.
|
||||||
|
*/
|
||||||
|
renderEmbeddables?: boolean;
|
||||||
|
skipInliningFonts?: true;
|
||||||
|
reuseImages?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
const createHTMLComment = (text: string) => {
|
const createHTMLComment = (text: string) => {
|
||||||
// surrounding with spaces to maintain prettified consistency with previous
|
// surrounding with spaces to maintain prettified consistency with previous
|
||||||
// iterations
|
// iterations
|
||||||
@@ -282,61 +728,34 @@ const createHTMLComment = (text: string) => {
|
|||||||
return document.createComment(` ${text} `);
|
return document.createComment(` ${text} `);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToSvg = async (
|
export const exportToSvg = async ({
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
data,
|
||||||
appState: {
|
config,
|
||||||
exportBackground: boolean;
|
}: {
|
||||||
exportPadding?: number;
|
data: ExportSceneData;
|
||||||
exportScale?: number;
|
config?: ExportToSvgConfig;
|
||||||
viewBackgroundColor: string;
|
}) => {
|
||||||
exportWithDarkMode?: boolean;
|
const {
|
||||||
exportEmbedScene?: boolean;
|
config: cfg,
|
||||||
frameRendering?: AppState["frameRendering"];
|
normalizedPadding,
|
||||||
},
|
exportWidth,
|
||||||
files: BinaryFiles | null,
|
exportHeight,
|
||||||
opts?: {
|
exportScale,
|
||||||
/**
|
x,
|
||||||
* if true, all embeddables passed in will be rendered when possible.
|
y,
|
||||||
*/
|
elementsForRender,
|
||||||
renderEmbeddables?: boolean;
|
appState,
|
||||||
exportingFrame?: 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;
|
|
||||||
|
|
||||||
const { exportingFrame = null } = opts || {};
|
|
||||||
|
|
||||||
const elementsForRender = prepareElementsForRender({
|
|
||||||
elements,
|
|
||||||
exportingFrame,
|
|
||||||
exportWithDarkMode,
|
|
||||||
frameRendering,
|
frameRendering,
|
||||||
});
|
} = await configExportDimension({ data, config });
|
||||||
|
|
||||||
if (exportingFrame) {
|
const offsetX = -(x - normalizedPadding);
|
||||||
exportPadding = 0;
|
const offsetY = -(y - normalizedPadding);
|
||||||
}
|
|
||||||
|
|
||||||
const [minX, minY, width, height] = getCanvasSize(
|
const { elements } = data;
|
||||||
exportingFrame ? [exportingFrame] : getRootElements(elementsForRender),
|
|
||||||
exportPadding,
|
|
||||||
);
|
|
||||||
|
|
||||||
const offsetX = -minX + exportPadding;
|
const theme =
|
||||||
const offsetY = -minY + exportPadding;
|
cfg.theme ?? (appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT);
|
||||||
|
const exportWithDarkMode = theme === THEME.DARK;
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// initialize SVG root element
|
// initialize SVG root element
|
||||||
@@ -346,9 +765,12 @@ export const exportToSvg = async (
|
|||||||
|
|
||||||
svgRoot.setAttribute("version", "1.1");
|
svgRoot.setAttribute("version", "1.1");
|
||||||
svgRoot.setAttribute("xmlns", SVG_NS);
|
svgRoot.setAttribute("xmlns", SVG_NS);
|
||||||
svgRoot.setAttribute("viewBox", `0 0 ${width} ${height}`);
|
svgRoot.setAttribute(
|
||||||
svgRoot.setAttribute("width", `${width * exportScale}`);
|
"viewBox",
|
||||||
svgRoot.setAttribute("height", `${height * exportScale}`);
|
`0 0 ${exportWidth / exportScale} ${exportHeight / exportScale}`,
|
||||||
|
);
|
||||||
|
svgRoot.setAttribute("width", `${exportWidth}`);
|
||||||
|
svgRoot.setAttribute("height", `${exportHeight}`);
|
||||||
|
|
||||||
const defsElement = svgRoot.ownerDocument.createElementNS(SVG_NS, "defs");
|
const defsElement = svgRoot.ownerDocument.createElementNS(SVG_NS, "defs");
|
||||||
|
|
||||||
@@ -367,7 +789,7 @@ export const exportToSvg = async (
|
|||||||
|
|
||||||
// we need to serialize the "original" elements before we put them through
|
// we need to serialize the "original" elements before we put them through
|
||||||
// the tempScene hack which duplicates and regenerates ids
|
// the tempScene hack which duplicates and regenerates ids
|
||||||
if (exportEmbedScene) {
|
if (appState.exportEmbedScene) {
|
||||||
try {
|
try {
|
||||||
encodeSvgBase64Payload({
|
encodeSvgBase64Payload({
|
||||||
metadataElement,
|
metadataElement,
|
||||||
@@ -375,7 +797,7 @@ export const exportToSvg = async (
|
|||||||
// elements which don't contain the temp frame labels.
|
// elements which don't contain the temp frame labels.
|
||||||
// But it also requires that the exportToSvg is being supplied with
|
// But it also requires that the exportToSvg is being supplied with
|
||||||
// only the elements that we're exporting, and no extra.
|
// only the elements that we're exporting, and no extra.
|
||||||
payload: serializeAsJSON(elements, appState, files || {}, "local"),
|
payload: serializeAsJSON(elements, appState, data.files || {}, "local"),
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@@ -413,7 +835,7 @@ export const exportToSvg = async (
|
|||||||
rect.setAttribute("width", `${frame.width}`);
|
rect.setAttribute("width", `${frame.width}`);
|
||||||
rect.setAttribute("height", `${frame.height}`);
|
rect.setAttribute("height", `${frame.height}`);
|
||||||
|
|
||||||
if (!exportingFrame) {
|
if (!cfg.exportingFrame) {
|
||||||
rect.setAttribute("rx", `${FRAME_STYLE.radius}`);
|
rect.setAttribute("rx", `${FRAME_STYLE.radius}`);
|
||||||
rect.setAttribute("ry", `${FRAME_STYLE.radius}`);
|
rect.setAttribute("ry", `${FRAME_STYLE.radius}`);
|
||||||
}
|
}
|
||||||
@@ -428,9 +850,10 @@ export const exportToSvg = async (
|
|||||||
// inline font faces
|
// inline font faces
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
const fontFaces = !opts?.skipInliningFonts
|
const fontFaces =
|
||||||
? await Fonts.generateFontFaceDeclarations(elements)
|
config?.skipInliningFonts !== true
|
||||||
: [];
|
? await Fonts.generateFontFaceDeclarations(elements)
|
||||||
|
: [];
|
||||||
|
|
||||||
const delimiter = "\n "; // 6 spaces
|
const delimiter = "\n "; // 6 spaces
|
||||||
|
|
||||||
@@ -447,17 +870,16 @@ export const exportToSvg = async (
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// render background rect
|
// render background rect
|
||||||
if (appState.exportBackground && viewBackgroundColor) {
|
if (appState.exportBackground && appState.viewBackgroundColor) {
|
||||||
|
const bgColor = cfg.canvasBackgroundColor || appState.viewBackgroundColor;
|
||||||
const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");
|
const rect = svgRoot.ownerDocument.createElementNS(SVG_NS, "rect");
|
||||||
rect.setAttribute("x", "0");
|
rect.setAttribute("x", "0");
|
||||||
rect.setAttribute("y", "0");
|
rect.setAttribute("y", "0");
|
||||||
rect.setAttribute("width", `${width}`);
|
rect.setAttribute("width", `${exportWidth / exportScale}`);
|
||||||
rect.setAttribute("height", `${height}`);
|
rect.setAttribute("height", `${exportHeight / exportScale}`);
|
||||||
rect.setAttribute(
|
rect.setAttribute(
|
||||||
"fill",
|
"fill",
|
||||||
exportWithDarkMode
|
exportWithDarkMode ? applyDarkModeFilter(bgColor) : bgColor,
|
||||||
? applyDarkModeFilter(viewBackgroundColor)
|
|
||||||
: viewBackgroundColor,
|
|
||||||
);
|
);
|
||||||
svgRoot.appendChild(rect);
|
svgRoot.appendChild(rect);
|
||||||
}
|
}
|
||||||
@@ -468,14 +890,14 @@ export const exportToSvg = async (
|
|||||||
|
|
||||||
const rsvg = rough.svg(svgRoot);
|
const rsvg = rough.svg(svgRoot);
|
||||||
|
|
||||||
const renderEmbeddables = opts?.renderEmbeddables ?? false;
|
const renderEmbeddables = config?.renderEmbeddables ?? false;
|
||||||
|
|
||||||
renderSceneToSvg(
|
renderSceneToSvg(
|
||||||
elementsForRender,
|
elementsForRender,
|
||||||
toBrandedType<RenderableElementsMap>(arrayToMap(elementsForRender)),
|
toBrandedType<RenderableElementsMap>(arrayToMap(elementsForRender)),
|
||||||
rsvg,
|
rsvg,
|
||||||
svgRoot,
|
svgRoot,
|
||||||
files || {},
|
data.files || {},
|
||||||
{
|
{
|
||||||
offsetX,
|
offsetX,
|
||||||
offsetY,
|
offsetY,
|
||||||
@@ -483,7 +905,7 @@ export const exportToSvg = async (
|
|||||||
exportWithDarkMode,
|
exportWithDarkMode,
|
||||||
renderEmbeddables,
|
renderEmbeddables,
|
||||||
frameRendering,
|
frameRendering,
|
||||||
canvasBackgroundColor: viewBackgroundColor,
|
canvasBackgroundColor: appState.viewBackgroundColor,
|
||||||
embedsValidationStatus: renderEmbeddables
|
embedsValidationStatus: renderEmbeddables
|
||||||
? new Map(
|
? new Map(
|
||||||
elementsForRender
|
elementsForRender
|
||||||
@@ -491,8 +913,8 @@ export const exportToSvg = async (
|
|||||||
.map((element) => [element.id, true]),
|
.map((element) => [element.id, true]),
|
||||||
)
|
)
|
||||||
: new Map(),
|
: new Map(),
|
||||||
reuseImages: opts?.reuseImages ?? true,
|
reuseImages: config?.reuseImages ?? true,
|
||||||
theme: exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
|
theme,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -501,6 +923,10 @@ export const exportToSvg = async (
|
|||||||
return svgRoot;
|
return svgRoot;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// SVG payload encoding/decoding
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export const encodeSvgBase64Payload = ({
|
export const encodeSvgBase64Payload = ({
|
||||||
payload,
|
payload,
|
||||||
metadataElement,
|
metadataElement,
|
||||||
@@ -556,26 +982,149 @@ export const decodeSvgBase64Payload = ({ svg }: { svg: string }) => {
|
|||||||
throw new Error("INVALID");
|
throw new Error("INVALID");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// getCanvasSize
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
// calculate smallest area to fit the contents in
|
// calculate smallest area to fit the contents in
|
||||||
const getCanvasSize = (
|
export const getCanvasSize = (
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
exportPadding: number,
|
|
||||||
): Bounds => {
|
): Bounds => {
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
||||||
const width = distance(minX, maxX) + exportPadding * 2;
|
const width = distance(minX, maxX);
|
||||||
const height = distance(minY, maxY) + exportPadding * 2;
|
const height = distance(minY, maxY);
|
||||||
|
|
||||||
return [minX, minY, width, height];
|
return [minX, minY, width, height];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the export dimensions for a set of elements.
|
||||||
|
*
|
||||||
|
* @param elements - Elements to calculate size for
|
||||||
|
* @param exportPadding - Padding to add around the elements
|
||||||
|
* @param scale - Scale factor
|
||||||
|
* @returns [width, height] tuple
|
||||||
|
*/
|
||||||
export const getExportSize = (
|
export const getExportSize = (
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
exportPadding: number,
|
exportPadding: number,
|
||||||
scale: number,
|
scale: number,
|
||||||
): [number, number] => {
|
): [number, number] => {
|
||||||
const [, , width, height] = getCanvasSize(elements, exportPadding).map(
|
const [, , width, height] = getCanvasSize(elements);
|
||||||
(dimension) => Math.trunc(dimension * scale),
|
|
||||||
);
|
|
||||||
|
|
||||||
return [width, height];
|
return [
|
||||||
|
Math.trunc((width + exportPadding * 2) * scale),
|
||||||
|
Math.trunc((height + exportPadding * 2) * scale),
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// exportToBlob
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export { MIME_TYPES };
|
||||||
|
|
||||||
|
type ExportToBlobConfig = ExportSceneConfig & {
|
||||||
|
mimeType?: string;
|
||||||
|
quality?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const exportToBlob = async ({
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
data: ExportSceneData;
|
||||||
|
config?: ExportToBlobConfig;
|
||||||
|
}): Promise<Blob> => {
|
||||||
|
let { mimeType = MIME_TYPES.png, quality } = config || {};
|
||||||
|
|
||||||
|
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 && config?.canvasBackgroundColor !== false) {
|
||||||
|
if (config?.canvasBackgroundColor === undefined) {
|
||||||
|
console.warn(
|
||||||
|
`Defaulting "canvasBackgroundColor" for "${MIME_TYPES.jpg}" mimeType`,
|
||||||
|
);
|
||||||
|
config = {
|
||||||
|
...config,
|
||||||
|
canvasBackgroundColor:
|
||||||
|
data.appState?.viewBackgroundColor || COLOR_WHITE,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvas = await exportToCanvas({ data, config });
|
||||||
|
|
||||||
|
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 &&
|
||||||
|
data.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
|
||||||
|
data.elements,
|
||||||
|
data.appState,
|
||||||
|
data.files || {},
|
||||||
|
"local",
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
resolve(blob);
|
||||||
|
},
|
||||||
|
mimeType,
|
||||||
|
quality,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// exportToClipboard
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const exportToClipboard = async ({
|
||||||
|
type,
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
data: ExportSceneData;
|
||||||
|
} & (
|
||||||
|
| { type: "png"; config?: ExportToBlobConfig }
|
||||||
|
| { type: "svg"; config?: ExportToSvgConfig }
|
||||||
|
| { type: "json"; config?: never }
|
||||||
|
)) => {
|
||||||
|
if (type === "svg") {
|
||||||
|
const svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
|
...data,
|
||||||
|
appState: restoreAppState(data.appState, null),
|
||||||
|
},
|
||||||
|
config,
|
||||||
|
});
|
||||||
|
await copyTextToSystemClipboard(svg.outerHTML);
|
||||||
|
} else if (type === "png") {
|
||||||
|
await copyBlobToClipboardAsPng(exportToBlob({ data, config }));
|
||||||
|
} else if (type === "json") {
|
||||||
|
await copyToClipboard(data.elements, data.files);
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid export type");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -83,11 +83,13 @@ describe("export", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("export svg-embedded scene", async () => {
|
it("export svg-embedded scene", async () => {
|
||||||
const svg = await exportToSvg(
|
const svg = await exportToSvg({
|
||||||
testElements,
|
data: {
|
||||||
{ ...getDefaultAppState(), exportEmbedScene: true },
|
elements: testElements,
|
||||||
{},
|
appState: { ...getDefaultAppState(), exportEmbedScene: true },
|
||||||
);
|
files: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
const svgText = svg.outerHTML;
|
const svgText = svg.outerHTML;
|
||||||
|
|
||||||
expect(svgText).toMatchSnapshot(`svg-embdedded scene export output`);
|
expect(svgText).toMatchSnapshot(`svg-embdedded scene export output`);
|
||||||
@@ -205,7 +207,13 @@ describe("export", () => {
|
|||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const svg = await exportToSvg(elements, appState, files);
|
const svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
|
elements,
|
||||||
|
appState,
|
||||||
|
files,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const svgText = svg.outerHTML;
|
const svgText = svg.outerHTML;
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,9 +1,10 @@
|
|||||||
import { exportToCanvas, exportToSvg } from "@excalidraw/utils";
|
import { exportToCanvas, exportToSvg } from "../../scene/export";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
applyDarkModeFilter,
|
applyDarkModeFilter,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
FRAME_STYLE,
|
FRAME_STYLE,
|
||||||
|
THEME,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -53,39 +54,42 @@ describe("exportToSvg", () => {
|
|||||||
},
|
},
|
||||||
] as NonDeletedExcalidrawElement[];
|
] as NonDeletedExcalidrawElement[];
|
||||||
|
|
||||||
const DEFAULT_OPTIONS = {
|
const DEFAULT_APP_STATE = {
|
||||||
exportBackground: false,
|
exportBackground: false,
|
||||||
viewBackgroundColor: "#ffffff",
|
viewBackgroundColor: "#ffffff",
|
||||||
files: {},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
DEFAULT_OPTIONS,
|
elements: ELEMENTS,
|
||||||
null,
|
appState: DEFAULT_APP_STATE,
|
||||||
);
|
files: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toMatchSnapshot();
|
expect(svgElement).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with a CJK font", async () => {
|
it("with a CJK font", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
[
|
data: {
|
||||||
...ELEMENTS,
|
elements: [
|
||||||
{
|
...ELEMENTS,
|
||||||
...textFixture,
|
{
|
||||||
height: ELEMENT_HEIGHT,
|
...textFixture,
|
||||||
width: ELEMENT_WIDTH,
|
height: ELEMENT_HEIGHT,
|
||||||
text: "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",
|
width: ELEMENT_WIDTH,
|
||||||
originalText:
|
text: "中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",
|
||||||
"中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",
|
originalText:
|
||||||
index: "a4" as FractionalIndex,
|
"中国你好!这是一个测试。中国你好!日本こんにちは!これはテストです。한국 안녕하세요! 이것은 테스트입니다.",
|
||||||
} as ExcalidrawTextElement,
|
index: "a4" as FractionalIndex,
|
||||||
],
|
} as ExcalidrawTextElement,
|
||||||
DEFAULT_OPTIONS,
|
],
|
||||||
null,
|
appState: DEFAULT_APP_STATE,
|
||||||
);
|
files: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toMatchSnapshot();
|
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)
|
// extend the timeout, as it needs to first load the fonts from disk and then perform whole woff2 decode, subset and encode (without workers)
|
||||||
@@ -94,15 +98,17 @@ describe("exportToSvg", () => {
|
|||||||
it("with background color", async () => {
|
it("with background color", async () => {
|
||||||
const BACKGROUND_COLOR = "#abcdef";
|
const BACKGROUND_COLOR = "#abcdef";
|
||||||
|
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
...DEFAULT_OPTIONS,
|
appState: {
|
||||||
exportBackground: true,
|
...DEFAULT_APP_STATE,
|
||||||
viewBackgroundColor: BACKGROUND_COLOR,
|
exportBackground: true,
|
||||||
|
viewBackgroundColor: BACKGROUND_COLOR,
|
||||||
|
},
|
||||||
|
files: {},
|
||||||
},
|
},
|
||||||
null,
|
});
|
||||||
);
|
|
||||||
|
|
||||||
expect(svgElement.querySelector("rect")).toHaveAttribute(
|
expect(svgElement.querySelector("rect")).toHaveAttribute(
|
||||||
"fill",
|
"fill",
|
||||||
@@ -111,14 +117,18 @@ describe("exportToSvg", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("with dark mode", async () => {
|
it("with dark mode", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
...DEFAULT_OPTIONS,
|
appState: {
|
||||||
exportWithDarkMode: true,
|
...DEFAULT_APP_STATE,
|
||||||
|
},
|
||||||
|
files: {},
|
||||||
},
|
},
|
||||||
null,
|
config: {
|
||||||
);
|
theme: THEME.DARK,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const textElements = svgElement.querySelectorAll("text");
|
const textElements = svgElement.querySelectorAll("text");
|
||||||
expect(textElements.length).toBeGreaterThan(0);
|
expect(textElements.length).toBeGreaterThan(0);
|
||||||
@@ -132,14 +142,16 @@ describe("exportToSvg", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("with exportPadding", async () => {
|
it("with exportPadding", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
...DEFAULT_OPTIONS,
|
appState: DEFAULT_APP_STATE,
|
||||||
exportPadding: 0,
|
files: {},
|
||||||
},
|
},
|
||||||
null,
|
config: {
|
||||||
);
|
padding: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toHaveAttribute("height", ELEMENT_HEIGHT.toString());
|
expect(svgElement).toHaveAttribute("height", ELEMENT_HEIGHT.toString());
|
||||||
expect(svgElement).toHaveAttribute("width", ELEMENT_WIDTH.toString());
|
expect(svgElement).toHaveAttribute("width", ELEMENT_WIDTH.toString());
|
||||||
@@ -152,15 +164,17 @@ describe("exportToSvg", () => {
|
|||||||
it("with scale", async () => {
|
it("with scale", async () => {
|
||||||
const SCALE = 2;
|
const SCALE = 2;
|
||||||
|
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
...DEFAULT_OPTIONS,
|
appState: DEFAULT_APP_STATE,
|
||||||
exportPadding: 0,
|
files: {},
|
||||||
exportScale: SCALE,
|
|
||||||
},
|
},
|
||||||
null,
|
config: {
|
||||||
);
|
padding: 0,
|
||||||
|
scale: SCALE,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toHaveAttribute(
|
expect(svgElement).toHaveAttribute(
|
||||||
"height",
|
"height",
|
||||||
@@ -173,23 +187,27 @@ describe("exportToSvg", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("with exportEmbedScene", async () => {
|
it("with exportEmbedScene", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
...DEFAULT_OPTIONS,
|
appState: {
|
||||||
exportEmbedScene: true,
|
...DEFAULT_APP_STATE,
|
||||||
|
exportEmbedScene: true,
|
||||||
|
},
|
||||||
|
files: {},
|
||||||
},
|
},
|
||||||
null,
|
});
|
||||||
);
|
|
||||||
expect(svgElement.innerHTML).toMatchSnapshot();
|
expect(svgElement.innerHTML).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with elements that have a link", async () => {
|
it("with elements that have a link", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
[rectangleWithLinkFixture],
|
data: {
|
||||||
DEFAULT_OPTIONS,
|
elements: [rectangleWithLinkFixture],
|
||||||
null,
|
appState: DEFAULT_APP_STATE,
|
||||||
);
|
files: {},
|
||||||
|
},
|
||||||
|
});
|
||||||
expect(svgElement.innerHTML).toMatchSnapshot();
|
expect(svgElement.innerHTML).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -229,9 +247,14 @@ describe("exporting frames", () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
elements,
|
data: {
|
||||||
files: null,
|
elements,
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toEqual(200);
|
expect(canvas.width).toEqual(200);
|
||||||
@@ -258,10 +281,15 @@ describe("exporting frames", () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
elements,
|
data: {
|
||||||
files: null,
|
elements,
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame: frame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toEqual(frame.width);
|
expect(canvas.width).toEqual(frame.width);
|
||||||
@@ -297,10 +325,15 @@ describe("exporting frames", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: [rectOverlapping, frame, frameChild],
|
data: {
|
||||||
files: null,
|
elements: [rectOverlapping, frame, frameChild],
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame: frame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@@ -341,10 +374,15 @@ describe("exporting frames", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: [frameChild, frame, elementOutside],
|
data: {
|
||||||
files: null,
|
elements: [frameChild, frame, elementOutside],
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame: frame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@@ -409,10 +447,15 @@ describe("exporting frames", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: exportedElements,
|
data: {
|
||||||
files: null,
|
elements: exportedElements,
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frames themselves should be exported when multiple frames selected
|
// frames themselves should be exported when multiple frames selected
|
||||||
@@ -454,10 +497,15 @@ describe("exporting frames", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: exportedElements,
|
data: {
|
||||||
files: null,
|
elements: exportedElements,
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@@ -513,10 +561,15 @@ describe("exporting frames", () => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: exportedElements,
|
data: {
|
||||||
files: null,
|
elements: exportedElements,
|
||||||
exportPadding: 0,
|
appState: {},
|
||||||
exportingFrame,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame shouldn't be exported
|
// frame shouldn't be exported
|
||||||
|
|||||||
@@ -1,216 +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 { 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 {
|
|
||||||
ExcalidrawElement,
|
|
||||||
ExcalidrawFrameLikeElement,
|
|
||||||
NonDeleted,
|
|
||||||
} from "@excalidraw/element/types";
|
|
||||||
import type { AppState, BinaryFiles } from "@excalidraw/excalidraw/types";
|
|
||||||
|
|
||||||
export { MIME_TYPES };
|
|
||||||
|
|
||||||
type ExportOpts = {
|
|
||||||
elements: readonly NonDeleted<ExcalidrawElement>[];
|
|
||||||
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
|
|
||||||
files: BinaryFiles | null;
|
|
||||||
maxWidthOrHeight?: number;
|
|
||||||
exportingFrame?: 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 = 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
|
|
||||||
opts.elements,
|
|
||||||
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 = 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(opts.elements, opts.files);
|
|
||||||
} else {
|
|
||||||
throw new Error("Invalid export type");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,4 +1,17 @@
|
|||||||
export * from "./export";
|
// Re-export from @excalidraw/excalidraw for backwards compatibility
|
||||||
|
export {
|
||||||
|
exportToCanvas,
|
||||||
|
exportToBlob,
|
||||||
|
exportToSvg,
|
||||||
|
exportToClipboard,
|
||||||
|
MIME_TYPES,
|
||||||
|
} from "@excalidraw/excalidraw/scene/export";
|
||||||
|
|
||||||
|
export type {
|
||||||
|
ExportSceneData,
|
||||||
|
ExportSceneConfig,
|
||||||
|
} from "@excalidraw/excalidraw/scene/export";
|
||||||
|
|
||||||
export * from "./withinBounds";
|
export * from "./withinBounds";
|
||||||
export * from "./bbox";
|
export * from "./bbox";
|
||||||
export { getCommonBounds } from "@excalidraw/element";
|
export { getCommonBounds } from "@excalidraw/element";
|
||||||
|
|||||||
@@ -10,9 +10,22 @@ const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg");
|
|||||||
describe("exportToCanvas", async () => {
|
describe("exportToCanvas", async () => {
|
||||||
const EXPORT_PADDING = 10;
|
const EXPORT_PADDING = 10;
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments (no padding)", async () => {
|
||||||
const canvas = await utils.exportToCanvas({
|
const canvas = await utils.exportToCanvas({
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// New API has no default padding - call sites must explicitly set it
|
||||||
|
expect(canvas.width).toBe(100);
|
||||||
|
expect(canvas.height).toBe(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("with padding", async () => {
|
||||||
|
const canvas = await utils.exportToCanvas({
|
||||||
|
data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||||
|
config: {
|
||||||
|
padding: EXPORT_PADDING,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
||||||
@@ -21,8 +34,10 @@ describe("exportToCanvas", async () => {
|
|||||||
|
|
||||||
it("when custom width and height", async () => {
|
it("when custom width and height", async () => {
|
||||||
const canvas = await utils.exportToCanvas({
|
const canvas = await utils.exportToCanvas({
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||||
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
config: {
|
||||||
|
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toBe(200);
|
expect(canvas.width).toBe(200);
|
||||||
@@ -33,20 +48,27 @@ describe("exportToCanvas", async () => {
|
|||||||
describe("exportToBlob", async () => {
|
describe("exportToBlob", async () => {
|
||||||
describe("mime type", () => {
|
describe("mime type", () => {
|
||||||
it("should change image/jpg to image/jpeg", async () => {
|
it("should change image/jpg to image/jpeg", async () => {
|
||||||
|
const diagramData = diagramFactory();
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: {
|
||||||
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
elements: diagramData.elements,
|
||||||
// testing typo in MIME type (jpg → jpeg)
|
appState: {
|
||||||
mimeType: "image/jpg",
|
...diagramData.appState,
|
||||||
appState: {
|
exportBackground: true,
|
||||||
exportBackground: true,
|
},
|
||||||
|
files: diagramData.files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
||||||
|
// testing typo in MIME type (jpg → jpeg)
|
||||||
|
mimeType: "image/jpg",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
||||||
});
|
});
|
||||||
it("should default to image/png", async () => {
|
it("should default to image/png", async () => {
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: diagramFactory(),
|
||||||
});
|
});
|
||||||
expect(blob?.type).toBe(MIME_TYPES.png);
|
expect(blob?.type).toBe(MIME_TYPES.png);
|
||||||
});
|
});
|
||||||
@@ -56,9 +78,11 @@ describe("exportToBlob", async () => {
|
|||||||
.spyOn(console, "warn")
|
.spyOn(console, "warn")
|
||||||
.mockImplementationOnce(() => void 0);
|
.mockImplementationOnce(() => void 0);
|
||||||
await utils.exportToBlob({
|
await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: diagramFactory(),
|
||||||
mimeType: MIME_TYPES.png,
|
config: {
|
||||||
quality: 1,
|
mimeType: MIME_TYPES.png,
|
||||||
|
quality: 1,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
expect(consoleSpy).toHaveBeenCalledWith(
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`,
|
`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`,
|
||||||
@@ -68,8 +92,9 @@ describe("exportToBlob", async () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("exportToSvg", () => {
|
describe("exportToSvg", () => {
|
||||||
const passedElements = () => exportToSvgSpy.mock.calls[0][0];
|
const getPassedArg = () => exportToSvgSpy.mock.calls[0][0];
|
||||||
const passedOptions = () => exportToSvgSpy.mock.calls[0][1];
|
const passedData = () => getPassedArg().data;
|
||||||
|
const passedConfig = () => getPassedArg().config;
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
@@ -77,18 +102,14 @@ describe("exportToSvg", () => {
|
|||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: { appState: void 0 },
|
overrides: { appState: void 0 },
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const passedOptionsWhenDefault = {
|
const data = passedData();
|
||||||
...passedOptions(),
|
expect(data.elements.length).toBe(3);
|
||||||
// To avoid varying snapshots
|
expect(passedConfig()).toMatchSnapshot();
|
||||||
name: "name",
|
|
||||||
};
|
|
||||||
expect(passedElements().length).toBe(3);
|
|
||||||
expect(passedOptionsWhenDefault).toMatchSnapshot();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// FIXME the utils.exportToSvg no longer filters out deleted elements.
|
// FIXME the utils.exportToSvg no longer filters out deleted elements.
|
||||||
@@ -96,37 +117,39 @@ describe("exportToSvg", () => {
|
|||||||
// type-checking for it correctly.
|
// type-checking for it correctly.
|
||||||
it.skip("with deleted elements", async () => {
|
it.skip("with deleted elements", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: { appState: void 0 },
|
overrides: { appState: void 0 },
|
||||||
elementOverrides: { isDeleted: true },
|
elementOverrides: { isDeleted: true },
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(passedElements().length).toBe(0);
|
expect(passedData().elements.length).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with exportPadding", async () => {
|
it("with padding", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
|
data: diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
|
||||||
exportPadding: 0,
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(passedElements().length).toBe(3);
|
expect(passedData().elements.length).toBe(3);
|
||||||
expect(passedOptions()).toEqual(
|
expect(passedConfig()).toEqual(
|
||||||
expect.objectContaining({ exportPadding: 0 }),
|
expect.objectContaining({ padding: 0 }),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with exportEmbedScene", async () => {
|
it("with exportEmbedScene", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: {
|
overrides: {
|
||||||
appState: { name: "diagram name", exportEmbedScene: true },
|
appState: { name: "diagram name", exportEmbedScene: true },
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(passedElements().length).toBe(3);
|
expect(passedData().elements.length).toBe(3);
|
||||||
expect(passedOptions().exportEmbedScene).toBe(true);
|
expect(passedData().appState?.exportEmbedScene).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -19,13 +19,15 @@ describe("embedding scene data", () => {
|
|||||||
const sourceElements = [rectangle, ellipse];
|
const sourceElements = [rectangle, ellipse];
|
||||||
|
|
||||||
const svgNode = await utils.exportToSvg({
|
const svgNode = await utils.exportToSvg({
|
||||||
elements: sourceElements,
|
data: {
|
||||||
appState: {
|
elements: sourceElements,
|
||||||
viewBackgroundColor: "#ffffff",
|
appState: {
|
||||||
gridModeEnabled: false,
|
viewBackgroundColor: "#ffffff",
|
||||||
exportEmbedScene: true,
|
gridModeEnabled: false,
|
||||||
|
exportEmbedScene: true,
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
},
|
},
|
||||||
files: null,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const svg = svgNode.outerHTML;
|
const svg = svgNode.outerHTML;
|
||||||
@@ -49,14 +51,18 @@ describe("embedding scene data", () => {
|
|||||||
const sourceElements = [rectangle, ellipse];
|
const sourceElements = [rectangle, ellipse];
|
||||||
|
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await utils.exportToBlob({
|
||||||
mimeType: "image/png",
|
data: {
|
||||||
elements: sourceElements,
|
elements: sourceElements,
|
||||||
appState: {
|
appState: {
|
||||||
viewBackgroundColor: "#ffffff",
|
viewBackgroundColor: "#ffffff",
|
||||||
gridModeEnabled: false,
|
gridModeEnabled: false,
|
||||||
exportEmbedScene: true,
|
exportEmbedScene: true,
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
mimeType: "image/png",
|
||||||
},
|
},
|
||||||
files: null,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const parsedString = await decodePngMetadata(blob);
|
const parsedString = await decodePngMetadata(blob);
|
||||||
|
|||||||
@@ -1531,10 +1531,10 @@
|
|||||||
resolved "https://registry.yarnpkg.com/@excalidraw/markdown-to-text/-/markdown-to-text-0.1.2.tgz#1703705e7da608cf478f17bfe96fb295f55a23eb"
|
resolved "https://registry.yarnpkg.com/@excalidraw/markdown-to-text/-/markdown-to-text-0.1.2.tgz#1703705e7da608cf478f17bfe96fb295f55a23eb"
|
||||||
integrity sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==
|
integrity sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==
|
||||||
|
|
||||||
"@excalidraw/mermaid-to-excalidraw@2.1.0":
|
"@excalidraw/mermaid-to-excalidraw@2.1.1":
|
||||||
version "2.1.0"
|
version "2.1.1"
|
||||||
resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-2.1.0.tgz#a5b9cf87c3185558cda7f9687d87b9937f452358"
|
resolved "https://registry.yarnpkg.com/@excalidraw/mermaid-to-excalidraw/-/mermaid-to-excalidraw-2.1.1.tgz#659c934a607dd2cf57f2a69282588ee2b0722959"
|
||||||
integrity sha512-RMd+c2b7WzzUjhERMpKwp8PhF2/XlHDjr/zK+Gxfp8K9sVlafPYJ5OEa/GkN6edi2rBUXRfW+41WdO6L56b6Kw==
|
integrity sha512-jU+frqcxazsY+t5yOBf2mgrQy+WUrbrzA36if3SQB/Vwaf2qOJjnWxucNafgZZk/3+9xGmRotUeOviSOJG+wYA==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@excalidraw/markdown-to-text" "0.1.2"
|
"@excalidraw/markdown-to-text" "0.1.2"
|
||||||
"@mermaid-js/parser" "^0.6.3"
|
"@mermaid-js/parser" "^0.6.3"
|
||||||
|
|||||||
Reference in New Issue
Block a user