Compare commits

...

6 Commits

Author SHA1 Message Date
dwelle
16a2431fd8 progress 2023-05-08 00:14:22 +02:00
dwelle
b71bf2072e Merge branch 'master' into dwelle/fix-export
# Conflicts:
#	src/components/LayerUI.tsx
#	src/packages/excalidraw/index.tsx
#	src/packages/utils.ts
2023-05-06 17:33:07 +02:00
dwelle
f1923acf05 Merge branch 'master' into dwelle/fix-export
# Conflicts:
#	src/appState.ts
#	src/components/ImageExportDialog.tsx
#	src/components/PublishLibrary.tsx
#	src/components/SingleLibraryItem.tsx
#	src/constants.ts
#	src/packages/utils.ts
2023-04-18 23:43:23 +02:00
dwelle
d81e0afa19 refactor exportToCanvas, improve tsdoc, add comments 2023-02-20 10:43:43 +01:00
dwelle
41de1fa951 rewrite exportToCanvas and start deduplicating export utils 2023-02-20 10:43:43 +01:00
dwelle
33ab88926f factor out default appState color constants 2023-02-20 10:43:43 +01:00
20 changed files with 699 additions and 310 deletions

View File

@ -8,7 +8,7 @@ import {
} from "../clipboard"; } from "../clipboard";
import { actionDeleteSelected } from "./actionDeleteSelected"; import { actionDeleteSelected } from "./actionDeleteSelected";
import { getSelectedElements } from "../scene/selection"; import { getSelectedElements } from "../scene/selection";
import { exportCanvas } from "../data/index"; import { exportAsImage } from "../data/index";
import { getNonDeletedElements, isTextElement } from "../element"; import { getNonDeletedElements, isTextElement } from "../element";
import { t } from "../i18n"; import { t } from "../i18n";
@ -78,7 +78,7 @@ export const actionCopyAsSvg = register({
true, true,
); );
try { try {
await exportCanvas( await exportAsImage(
"clipboard-svg", "clipboard-svg",
selectedElements.length selectedElements.length
? selectedElements ? selectedElements
@ -122,7 +122,7 @@ export const actionCopyAsPng = register({
true, true,
); );
try { try {
await exportCanvas( await exportAsImage(
"clipboard", "clipboard",
selectedElements.length selectedElements.length
? selectedElements ? selectedElements

View File

@ -10,13 +10,13 @@ import { useDevice } from "../components/App";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { register } from "./register"; import { register } from "./register";
import { CheckboxItem } from "../components/CheckboxItem"; import { CheckboxItem } from "../components/CheckboxItem";
import { getExportSize } from "../scene/export"; import { getCanvasSize } from "../scene/export";
import { DEFAULT_EXPORT_PADDING, EXPORT_SCALES, THEME } from "../constants"; import { DEFAULT_EXPORT_PADDING, EXPORT_SCALES, THEME } from "../constants";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
import { isImageFileHandle } from "../data/blob"; import { isImageFileHandle } from "../data/blob";
import { nativeFileSystemSupported } from "../data/filesystem"; import { nativeFileSystemSupported } from "../data/filesystem";
import { Theme } from "../element/types"; import { NonDeletedExcalidrawElement, Theme } from "../element/types";
import "../components/ToolIcon.scss"; import "../components/ToolIcon.scss";
@ -54,6 +54,18 @@ export const actionChangeExportScale = register({
? getSelectedElements(elements, appState) ? getSelectedElements(elements, appState)
: elements; : elements;
const getExportSize = (
elements: readonly NonDeletedExcalidrawElement[],
padding: number,
scale: number,
): [number, number] => {
const [, , width, height] = getCanvasSize(elements).map((dimension) =>
Math.trunc(dimension * scale),
);
return [width + padding * 2, height + padding * 2];
};
return ( return (
<> <>
{EXPORT_SCALES.map((s) => { {EXPORT_SCALES.map((s) => {

View File

@ -1,14 +1,15 @@
import oc from "open-color";
import { import {
DEFAULT_BACKGROUND_COLOR,
DEFAULT_ELEMENT_PROPS, DEFAULT_ELEMENT_PROPS,
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
DEFAULT_ZOOM_VALUE,
EXPORT_SCALES, EXPORT_SCALES,
THEME, THEME,
} from "./constants"; } from "./constants";
import { t } from "./i18n"; import { t } from "./i18n";
import { AppState, NormalizedZoomValue } from "./types"; import { AppState } from "./types";
import { getDateTime } from "./utils"; import { getDateTime } from "./utils";
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio) const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
@ -84,10 +85,10 @@ export const getDefaultAppState = (): Omit<
startBoundElement: null, startBoundElement: null,
suggestedBindings: [], suggestedBindings: [],
toast: null, toast: null,
viewBackgroundColor: oc.white, viewBackgroundColor: DEFAULT_BACKGROUND_COLOR,
zenModeEnabled: false, zenModeEnabled: false,
zoom: { zoom: {
value: 1 as NormalizedZoomValue, value: DEFAULT_ZOOM_VALUE,
}, },
viewModeEnabled: false, viewModeEnabled: false,
pendingImageElementId: null, pendingImageElementId: null,

View File

@ -1375,14 +1375,14 @@ class App extends React.Component<AppProps, AppState> {
{ {
elements: renderingElements, elements: renderingElements,
appState: this.state, appState: this.state,
scale: window.devicePixelRatio,
rc: this.rc!, rc: this.rc!,
canvas: this.canvas!, canvas: this.canvas!,
renderConfig: { renderConfig: {
canvasScale: window.devicePixelRatio,
selectionColor, selectionColor,
scrollX: this.state.scrollX, scrollX: this.state.scrollX,
scrollY: this.state.scrollY, scrollY: this.state.scrollY,
viewBackgroundColor: this.state.viewBackgroundColor, canvasBackgroundColor: this.state.viewBackgroundColor,
zoom: this.state.zoom, zoom: this.state.zoom,
remotePointerViewportCoords: pointerViewportCoords, remotePointerViewportCoords: pointerViewportCoords,
remotePointerButton: cursorButton, remotePointerButton: cursorButton,

View File

@ -103,11 +103,20 @@ const ImageExportModal = ({
return; return;
} }
exportToCanvas({ exportToCanvas({
data: {
elements: exportedElements, elements: exportedElements,
appState, appState,
files, files,
exportPadding, },
config: {
canvasBackgroundColor: !appState.exportBackground
? false
: appState.viewBackgroundColor,
padding: exportPadding,
theme: appState.exportWithDarkMode ? "dark" : "light",
scale: appState.exportScale,
maxWidthOrHeight: maxWidth, maxWidthOrHeight: maxWidth,
},
}) })
.then((canvas) => { .then((canvas) => {
setRenderError(null); setRenderError(null);

View File

@ -2,7 +2,7 @@ import clsx from "clsx";
import React from "react"; import React from "react";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
import { CLASSES, DEFAULT_SIDEBAR, LIBRARY_SIDEBAR_WIDTH } from "../constants"; import { CLASSES, DEFAULT_SIDEBAR, LIBRARY_SIDEBAR_WIDTH } from "../constants";
import { exportCanvas } from "../data"; import { exportAsImage } from "../data";
import { isTextElement, showSelectedShapeActions } from "../element"; import { isTextElement, showSelectedShapeActions } from "../element";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { Language, t } from "../i18n"; import { Language, t } from "../i18n";
@ -141,7 +141,7 @@ const LayerUI = ({
(type: ExportType): ExportCB => (type: ExportType): ExportCB =>
async (exportedElements) => { async (exportedElements) => {
trackEvent("export", type, "ui"); trackEvent("export", type, "ui");
const fileHandle = await exportCanvas( const fileHandle = await exportAsImage(
type, type,
exportedElements, exportedElements,
appState, appState,

View File

@ -37,12 +37,14 @@ export const LibraryUnit = ({
return; return;
} }
const svg = await exportToSvg({ const svg = await exportToSvg({
data: {
elements, elements,
appState: { appState: {
exportBackground: false, exportBackground: false,
viewBackgroundColor: oc.white, viewBackgroundColor: oc.white,
}, },
files: null, files: null,
},
}); });
svg.querySelector(".style-fonts")?.remove(); svg.querySelector(".style-fonts")?.remove();
node.innerHTML = svg.outerHTML; node.innerHTML = svg.outerHTML;

View File

@ -86,9 +86,13 @@ 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({
data: {
elements: item.elements, elements: item.elements,
files: null, files: null,
},
config: {
maxWidthOrHeight: BOX_SIZE, maxWidthOrHeight: BOX_SIZE,
},
}); });
const { width, height } = itemCanvas; const { width, height } = itemCanvas;
@ -150,6 +154,7 @@ const SingleLibraryItem = ({
} }
(async () => { (async () => {
const svg = await exportToSvg({ const svg = await exportToSvg({
data: {
elements: libItem.elements, elements: libItem.elements,
appState: { appState: {
...appState, ...appState,
@ -157,6 +162,7 @@ const SingleLibraryItem = ({
exportBackground: true, exportBackground: true,
}, },
files: null, files: null,
},
}); });
node.innerHTML = svg.outerHTML; node.innerHTML = svg.outerHTML;
})(); })();

View File

@ -1,5 +1,5 @@
import cssVariables from "./css/variables.module.scss"; import cssVariables from "./css/variables.module.scss";
import { AppProps } from "./types"; import { AppProps, NormalizedZoomValue } from "./types";
import { ExcalidrawElement, FontFamilyValues } from "./element/types"; import { ExcalidrawElement, FontFamilyValues } from "./element/types";
import oc from "open-color"; import oc from "open-color";
@ -75,6 +75,7 @@ export enum EVENT {
export const ENV = { export const ENV = {
TEST: "test", TEST: "test",
DEVELOPMENT: "development", DEVELOPMENT: "development",
PRODUCTION: "production",
}; };
export const CLASSES = { export const CLASSES = {
@ -100,6 +101,9 @@ export const DEFAULT_FONT_FAMILY: FontFamilyValues = FONT_FAMILY.Virgil;
export const DEFAULT_TEXT_ALIGN = "left"; export const DEFAULT_TEXT_ALIGN = "left";
export const DEFAULT_VERTICAL_ALIGN = "top"; export const DEFAULT_VERTICAL_ALIGN = "top";
export const DEFAULT_VERSION = "{version}"; export const DEFAULT_VERSION = "{version}";
export const DEFAULT_BACKGROUND_COLOR = "#ffffff";
export const DEFAULT_STROKE_COLOR = "#000000";
export const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;
export const CANVAS_ONLY_ACTIONS = ["selectAll"]; export const CANVAS_ONLY_ACTIONS = ["selectAll"];

View File

@ -15,7 +15,7 @@ import { serializeAsJSON } from "./json";
export { loadFromBlob } from "./blob"; export { loadFromBlob } from "./blob";
export { loadFromJSON, saveAsJSON } from "./json"; export { loadFromJSON, saveAsJSON } from "./json";
export const exportCanvas = async ( export const exportAsImage = async (
type: Omit<ExportType, "backend">, type: Omit<ExportType, "backend">,
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
appState: AppState, appState: AppState,
@ -66,10 +66,19 @@ export const exportCanvas = async (
} }
} }
const tempCanvas = await exportToCanvas(elements, appState, files, { const tempCanvas = await exportToCanvas({
exportBackground, data: {
viewBackgroundColor, elements,
exportPadding, appState,
files,
},
config: {
canvasBackgroundColor: !exportBackground ? false : viewBackgroundColor,
padding: exportPadding,
theme: appState.exportWithDarkMode ? "dark" : "light",
scale: appState.exportScale,
fit: "none",
},
}); });
tempCanvas.style.display = "none"; tempCanvas.style.display = "none";
document.body.appendChild(tempCanvas); document.body.appendChild(tempCanvas);

View File

@ -1,6 +1,6 @@
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { exportCanvas } from "."; import { exportAsImage } from ".";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
import { getFileHandleType, isImageFileHandleType } from "./blob"; import { getFileHandleType, isImageFileHandleType } from "./blob";
@ -23,7 +23,7 @@ export const resaveAsImageWithScene = async (
exportEmbedScene: true, exportEmbedScene: true,
}; };
await exportCanvas( await exportAsImage(
fileHandleType, fileHandleType,
getNonDeletedElements(elements), getNonDeletedElements(elements),
appState, appState,

View File

@ -57,22 +57,21 @@ 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( const canvas = exportToCanvas({
elements as any, data: {
{ elements: elements as any,
appState: {
...getDefaultAppState(), ...getDefaultAppState(),
offsetTop: 0,
offsetLeft: 0,
width: 0, width: 0,
height: 0, height: 0,
}, },
{}, // files files: {}, // files
{
exportBackground: true,
viewBackgroundColor: "#ffffff",
}, },
config: {
canvasBackgroundColor: "#ffffff",
createCanvas, createCanvas,
); },
});
const fs = require("fs"); const fs = require("fs");
const out = fs.createWriteStream("test.png"); const out = fs.createWriteStream("test.png");

View File

@ -252,10 +252,12 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
return false; return false;
} }
await exportToClipboard({ await exportToClipboard({
data: {
elements: excalidrawAPI.getSceneElements(), elements: excalidrawAPI.getSceneElements(),
appState: excalidrawAPI.getAppState(), appState: excalidrawAPI.getAppState(),
files: excalidrawAPI.getFiles(), files: excalidrawAPI.getFiles(),
type, },
type: "json",
}); });
window.alert(`Copied to clipboard as ${type} successfully`); window.alert(`Copied to clipboard as ${type} successfully`);
}; };
@ -740,6 +742,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
return; return;
} }
const svg = await exportToSvg({ const svg = await exportToSvg({
data: {
elements: excalidrawAPI?.getSceneElements(), elements: excalidrawAPI?.getSceneElements(),
appState: { appState: {
...initialData.appState, ...initialData.appState,
@ -749,6 +752,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
height: 100, height: 100,
}, },
files: excalidrawAPI?.getFiles(), files: excalidrawAPI?.getFiles(),
},
}); });
appRef.current.querySelector(".export-svg").innerHTML = appRef.current.querySelector(".export-svg").innerHTML =
svg.outerHTML; svg.outerHTML;
@ -764,14 +768,18 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
return; return;
} }
const blob = await exportToBlob({ const blob = await exportToBlob({
data: {
elements: excalidrawAPI?.getSceneElements(), elements: excalidrawAPI?.getSceneElements(),
mimeType: "image/png",
appState: { appState: {
...initialData.appState, ...initialData.appState,
exportEmbedScene, exportEmbedScene,
exportWithDarkMode, exportWithDarkMode,
}, },
files: excalidrawAPI?.getFiles(), files: excalidrawAPI?.getFiles(),
},
config: {
mimeType: "image/png",
},
}); });
setBlobUrl(window.URL.createObjectURL(blob)); setBlobUrl(window.URL.createObjectURL(blob));
}} }}
@ -788,12 +796,14 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
return; return;
} }
const canvas = await exportToCanvas({ const canvas = await exportToCanvas({
data: {
elements: excalidrawAPI.getSceneElements(), elements: excalidrawAPI.getSceneElements(),
appState: { appState: {
...initialData.appState, ...initialData.appState,
exportWithDarkMode, exportWithDarkMode,
}, },
files: excalidrawAPI.getFiles(), files: excalidrawAPI.getFiles(),
},
}); });
const ctx = canvas.getContext("2d")!; const ctx = canvas.getContext("2d")!;
ctx.font = "30px Virgil"; ctx.font = "30px Virgil";

View File

@ -206,7 +206,6 @@ export {
restoreLibraryItems, restoreLibraryItems,
} from "../../data/restore"; } from "../../data/restore";
export { export {
exportToCanvas,
exportToBlob, exportToBlob,
exportToSvg, exportToSvg,
serializeAsJSON, serializeAsJSON,
@ -245,5 +244,6 @@ export { MainMenu };
export { useDevice } from "../../components/App"; export { useDevice } from "../../components/App";
export { WelcomeScreen }; export { WelcomeScreen };
export { LiveCollaborationTrigger }; export { LiveCollaborationTrigger };
export { DefaultSidebar } from "../../components/DefaultSidebar"; export { DefaultSidebar } from "../../components/DefaultSidebar";
export { exportToCanvas } from "../../scene/export";

View File

@ -1,12 +1,13 @@
import { import {
exportToCanvas as _exportToCanvas, exportToCanvas as _exportToCanvas,
ExportToCanvasConfig,
ExportToCanvasData,
exportToSvg as _exportToSvg, exportToSvg as _exportToSvg,
} from "../scene/export"; } from "../scene/export";
import { getDefaultAppState } from "../appState"; import { getNonDeletedElements } from "../element";
import { AppState, BinaryFiles } from "../types"; import { ExcalidrawElement } from "../element/types";
import { ExcalidrawElement, NonDeleted } from "../element/types";
import { restore } from "../data/restore"; import { restore } from "../data/restore";
import { MIME_TYPES } from "../constants"; import { DEFAULT_BACKGROUND_COLOR, MIME_TYPES } from "../constants";
import { encodePngMetadata } from "../data/image"; import { encodePngMetadata } from "../data/image";
import { serializeAsJSON } from "../data/json"; import { serializeAsJSON } from "../data/json";
import { import {
@ -35,86 +36,24 @@ const passElementsSafely = (elements: readonly ExcalidrawElement[]) => {
export { MIME_TYPES }; export { MIME_TYPES };
type ExportOpts = { type ExportToBlobConfig = ExportToCanvasConfig & {
elements: readonly NonDeleted<ExcalidrawElement>[];
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
files: BinaryFiles | null;
maxWidthOrHeight?: number;
getDimensions?: (
width: number,
height: number,
) => { width: number; height: number; scale?: number };
};
export const exportToCanvas = ({
elements,
appState,
files,
maxWidthOrHeight,
getDimensions,
exportPadding,
}: ExportOpts & {
exportPadding?: number;
}) => {
const { elements: restoredElements, appState: restoredAppState } = restore(
{ elements, appState },
null,
null,
);
const { exportBackground, viewBackgroundColor } = restoredAppState;
return _exportToCanvas(
passElementsSafely(restoredElements),
{ ...restoredAppState, offsetTop: 0, offsetLeft: 0, width: 0, height: 0 },
files || {},
{ exportBackground, exportPadding, viewBackgroundColor },
(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; mimeType?: string;
quality?: number; quality?: number;
exportPadding?: number; };
},
): Promise<Blob> => { type ExportToSvgConfig = Pick<
let { mimeType = MIME_TYPES.png, quality } = opts; ExportToCanvasConfig,
"canvasBackgroundColor" | "padding" | "theme"
>;
export const exportToBlob = async ({
data,
config,
}: {
data: ExportToCanvasData;
config?: ExportToBlobConfig;
}): Promise<Blob> => {
let { mimeType = MIME_TYPES.png, quality } = config || {};
if (mimeType === MIME_TYPES.png && typeof quality === "number") { if (mimeType === MIME_TYPES.png && typeof quality === "number") {
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`); console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
@ -125,19 +64,23 @@ export const exportToBlob = async (
mimeType = MIME_TYPES.jpg; mimeType = MIME_TYPES.jpg;
} }
if (mimeType === MIME_TYPES.jpg && !opts.appState?.exportBackground) { if (mimeType === MIME_TYPES.jpg && !config?.canvasBackgroundColor === false) {
console.warn( console.warn(
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`, `Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
); );
opts = { config = {
...opts, ...config,
appState: { ...opts.appState, exportBackground: true }, canvasBackgroundColor:
data.appState?.viewBackgroundColor || DEFAULT_BACKGROUND_COLOR,
}; };
} }
const canvas = await exportToCanvas({ const canvas = await _exportToCanvas({
...opts, data: {
elements: passElementsSafely(opts.elements), ...data,
elements: passElementsSafely(data.elements),
},
config,
}); });
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8; quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
@ -150,7 +93,7 @@ export const exportToBlob = async (
if ( if (
blob && blob &&
mimeType === MIME_TYPES.png && mimeType === MIME_TYPES.png &&
opts.appState?.exportEmbedScene data.appState?.exportEmbedScene
) { ) {
blob = await encodePngMetadata({ blob = await encodePngMetadata({
blob, blob,
@ -158,9 +101,9 @@ export const exportToBlob = async (
// NOTE as long as we're using the Scene hack, we need to ensure // NOTE as long as we're using the Scene hack, we need to ensure
// we pass the original, uncloned elements when serializing // we pass the original, uncloned elements when serializing
// so that we keep ids stable // so that we keep ids stable
opts.elements, data.elements,
opts.appState, data.appState,
opts.files || {}, data.files || {},
"local", "local",
), ),
}); });
@ -174,53 +117,62 @@ export const exportToBlob = async (
}; };
export const exportToSvg = async ({ export const exportToSvg = async ({
elements, data,
appState = getDefaultAppState(), config,
files = {}, }: {
exportPadding, data: ExportToCanvasData;
}: Omit<ExportOpts, "getDimensions"> & { config?: ExportToSvgConfig;
exportPadding?: number;
}): Promise<SVGSVGElement> => { }): Promise<SVGSVGElement> => {
const { elements: restoredElements, appState: restoredAppState } = restore( const { elements: restoredElements, appState: restoredAppState } = restore(
{ elements, appState }, { ...data, files: data.files || {} },
null, null,
null, null,
); );
const exportAppState = { const appState = { ...restoredAppState, exportPadding: config?.padding };
...restoredAppState, const elements = getNonDeletedElements(restoredElements);
exportPadding, const files = data.files || {};
};
return _exportToSvg( return _exportToSvg(passElementsSafely(elements), appState, files, {
passElementsSafely(restoredElements),
exportAppState,
files,
{
// NOTE as long as we're using the Scene hack, we need to ensure // NOTE as long as we're using the Scene hack, we need to ensure
// we pass the original, uncloned elements when serializing // we pass the original, uncloned elements when serializing
// so that we keep ids stable. Hence adding the serializeAsJSON helper // so that we keep ids stable. Hence adding the serializeAsJSON helper
// support into the downstream exportToSvg function. // support into the downstream exportToSvg function.
serializeAsJSON: () => serializeAsJSON: () => serializeAsJSON(elements, appState, files, "local"),
serializeAsJSON(restoredElements, exportAppState, files || {}, "local"), });
},
);
}; };
export const exportToClipboard = async ( export const exportToCanvas = async ({
opts: ExportOpts & { data,
mimeType?: string; config,
quality?: number; }: {
type: "png" | "svg" | "json"; data: ExportToCanvasData;
}, config?: ExportToCanvasConfig;
) => { }) => {
if (opts.type === "svg") { return _exportToCanvas({
const svg = await exportToSvg(opts); data: { ...data, elements: passElementsSafely(data.elements) },
config,
});
};
export const exportToClipboard = async ({
type,
data,
config,
}: {
data: ExportToCanvasData;
} & (
| { type: "png"; config?: ExportToBlobConfig }
| { type: "svg"; config?: ExportToSvgConfig }
| { type: "json"; config?: never }
)) => {
if (type === "svg") {
const svg = await exportToSvg({ data, config });
await copyTextToSystemClipboard(svg.outerHTML); await copyTextToSystemClipboard(svg.outerHTML);
} else if (opts.type === "png") { } else if (type === "png") {
await copyBlobToClipboardAsPng(exportToBlob(opts)); await copyBlobToClipboardAsPng(exportToBlob({ data, config }));
} else if (opts.type === "json") { } else if (type === "json") {
await copyToClipboard(opts.elements, opts.files); await copyToClipboard(data.elements, data.files);
} else { } else {
throw new Error("Invalid export type"); throw new Error("Invalid export type");
} }

View File

@ -317,14 +317,12 @@ const renderLinearElementPointHighlight = (
export const _renderScene = ({ export const _renderScene = ({
elements, elements,
appState, appState,
scale,
rc, rc,
canvas, canvas,
renderConfig, renderConfig,
}: { }: {
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
appState: AppState; appState: AppState;
scale: number;
rc: RoughCanvas; rc: RoughCanvas;
canvas: HTMLCanvasElement; canvas: HTMLCanvasElement;
renderConfig: RenderConfig; renderConfig: RenderConfig;
@ -347,27 +345,27 @@ export const _renderScene = ({
context.setTransform(1, 0, 0, 1, 0, 0); context.setTransform(1, 0, 0, 1, 0, 0);
context.save(); context.save();
context.scale(scale, scale); context.scale(renderConfig.canvasScale, renderConfig.canvasScale);
// When doing calculations based on canvas width we should used normalized one // When doing calculations based on canvas width we should used normalized one
const normalizedCanvasWidth = canvas.width / scale; const normalizedCanvasWidth = canvas.width / renderConfig.canvasScale;
const normalizedCanvasHeight = canvas.height / scale; const normalizedCanvasHeight = canvas.height / renderConfig.canvasScale;
if (isExporting && renderConfig.theme === "dark") { if (isExporting && renderConfig.theme === "dark") {
context.filter = THEME_FILTER; context.filter = THEME_FILTER;
} }
// Paint background // Paint background
if (typeof renderConfig.viewBackgroundColor === "string") { if (typeof renderConfig.canvasBackgroundColor === "string") {
const hasTransparence = const hasTransparence =
renderConfig.viewBackgroundColor === "transparent" || renderConfig.canvasBackgroundColor === "transparent" ||
renderConfig.viewBackgroundColor.length === 5 || // #RGBA renderConfig.canvasBackgroundColor.length === 5 || // #RGBA
renderConfig.viewBackgroundColor.length === 9 || // #RRGGBBA renderConfig.canvasBackgroundColor.length === 9 || // #RRGGBBA
/(hsla|rgba)\(/.test(renderConfig.viewBackgroundColor); /(hsla|rgba)\(/.test(renderConfig.canvasBackgroundColor);
if (hasTransparence) { if (hasTransparence) {
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight); context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
} }
context.save(); context.save();
context.fillStyle = renderConfig.viewBackgroundColor; context.fillStyle = renderConfig.canvasBackgroundColor;
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight); context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
context.restore(); context.restore();
} else { } else {
@ -796,7 +794,6 @@ const renderSceneThrottled = throttleRAF(
(config: { (config: {
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
appState: AppState; appState: AppState;
scale: number;
rc: RoughCanvas; rc: RoughCanvas;
canvas: HTMLCanvasElement; canvas: HTMLCanvasElement;
renderConfig: RenderConfig; renderConfig: RenderConfig;
@ -813,7 +810,6 @@ export const renderScene = <T extends boolean = false>(
config: { config: {
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
appState: AppState; appState: AppState;
scale: number;
rc: RoughCanvas; rc: RoughCanvas;
canvas: HTMLCanvasElement; canvas: HTMLCanvasElement;
renderConfig: RenderConfig; renderConfig: RenderConfig;

View File

@ -1,73 +1,447 @@
import rough from "roughjs/bin/rough"; import rough from "roughjs/bin/rough";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement, Theme } from "../element/types";
import { getCommonBounds } from "../element/bounds"; import { getCommonBounds } from "../element/bounds";
import { renderScene, renderSceneToSvg } from "../renderer/renderScene"; import { renderScene, renderSceneToSvg } from "../renderer/renderScene";
import { distance } from "../utils"; import { distance } from "../utils";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { DEFAULT_EXPORT_PADDING, SVG_NS, THEME_FILTER } from "../constants"; import {
import { getDefaultAppState } from "../appState"; DEFAULT_BACKGROUND_COLOR,
DEFAULT_EXPORT_PADDING,
DEFAULT_ZOOM_VALUE,
ENV,
SVG_NS,
THEME,
THEME_FILTER,
} from "../constants";
import { serializeAsJSON } from "../data/json"; import { serializeAsJSON } from "../data/json";
import { import {
getInitializedImageElements, getInitializedImageElements,
updateImageCache, updateImageCache,
} from "../element/image"; } from "../element/image";
import { restoreAppState } from "../data/restore";
export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`; export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
export const exportToCanvas = async ( export type ExportToCanvasData = {
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[];
appState: AppState, appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
files: BinaryFiles, files: BinaryFiles | null;
{ };
exportBackground,
exportPadding = DEFAULT_EXPORT_PADDING, export type ExportToCanvasConfig = {
viewBackgroundColor, theme?: Theme;
}: { /**
exportBackground: boolean; * Canvas background. Valid values are:
exportPadding?: number; *
viewBackgroundColor: string; * - `undefined` - the background of "appState.viewBackgroundColor" is used.
}, * - `false` - no background is used (set to "transparent").
createCanvas: ( * - `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 `cover`, padding is disabled (set to 0).
*
* 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`.
* - `cover` - scale to fill the frame while maintaining aspect ratio. If
* content overflows, it will be cropped.
*
* 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" | "cover";
/**
* 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;
canvas.height = height * appState.exportScale;
return { canvas, scale: appState.exportScale };
},
) => {
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding);
const { canvas, scale = 1 } = createCanvas(width, height); /**
* 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: ExportToCanvasData;
config?: ExportToCanvasConfig;
}) => {
// initialize defaults
// ---------------------------------------------------------------------------
const { elements, files } = data;
const defaultAppState = getDefaultAppState(); const appState = restoreAppState(data.appState, null);
// clone
const cfg = Object.assign({}, config);
cfg.fit =
cfg.fit ??
(cfg.width != null ||
cfg.height != null ||
cfg.maxWidthOrHeight != null ||
cfg.widthOrHeight != null
? "contain"
: "none");
const containPadding = cfg.fit === "contain";
if (cfg.x != null || cfg.x != null) {
cfg.fit = "none";
}
if (cfg.fit === "cover") {
if (cfg.padding && process.env.NODE_ENV !== ENV.PRODUCTION) {
console.warn("`padding` is ignored when `fit` is set to `cover`");
}
cfg.padding = 0;
}
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 (process.env.NODE_ENV !== ENV.PRODUCTION) {
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 (process.env.NODE_ENV !== ENV.PRODUCTION) {
console.warn(
"`getDimensions` is ignored when `width`, `height`, or `maxWidthOrHeight` is set",
);
}
cfg.getDimensions = undefined;
}
// ---------------------------------------------------------------------------
// 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 canvasScale = 1;
const origCanvasSize = getCanvasSize(elements);
// cfg.x = undefined;
// cfg.y = undefined;
// variables for original content bounding box
const [origX, origY, origWidth, origHeight] = origCanvasSize;
// variables for target bounding box
let [x, y, width, height] = origCanvasSize;
if (cfg.width != null) {
width = cfg.width;
if (cfg.padding && containPadding) {
width -= cfg.padding * 2;
}
if (cfg.height) {
height = cfg.height;
if (cfg.padding && containPadding) {
height -= cfg.padding * 2;
}
} else {
// if height not specified, scale the original height to match the new
// width while maintaining aspect ratio
height *= width / origWidth;
}
} else if (cfg.height != null) {
height = cfg.height;
if (cfg.padding && containPadding) {
height -= cfg.padding * 2;
}
// width not specified, so scale the original width to match the new
// height while maintaining aspect ratio
width *= height / origHeight;
}
if (cfg.maxWidthOrHeight != null || cfg.widthOrHeight != null) {
if (containPadding && 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)
canvasScale = cfg.widthOrHeight / max;
} else if (cfg.maxWidthOrHeight != null) {
canvasScale = cfg.maxWidthOrHeight < max ? cfg.maxWidthOrHeight / max : 1;
}
width *= canvasScale;
height *= canvasScale;
} else if (cfg.getDimensions) {
const ret = cfg.getDimensions(width, height);
width = ret.width;
height = ret.height;
cfg.scale = ret.scale ?? cfg.scale;
} else if (
containPadding &&
cfg.padding &&
cfg.width == null &&
cfg.height == null
) {
const whRatio = width / height;
width -= cfg.padding * 2;
height -= (cfg.padding * 2) / whRatio;
}
if (
(cfg.fit === "contain" && !cfg.maxWidthOrHeight) ||
(containPadding && cfg.padding)
) {
if (cfg.fit === "contain") {
const wRatio = width / origWidth;
const hRatio = height / origHeight;
// scale the orig canvas to fit in the target frame
canvasScale = Math.min(wRatio, hRatio);
} else {
const wRatio = (width - cfg.padding * 2) / width;
const hRatio = (height - cfg.padding * 2) / height;
canvasScale = Math.min(wRatio, hRatio);
}
} else if (cfg.fit === "cover") {
const wRatio = width / origWidth;
const hRatio = height / origHeight;
// scale the orig canvas to fill the the target frame
// (opposite of "contain")
canvasScale = Math.max(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 / canvasScale / 2 -
(cfg.x == null ? origWidth : width + cfg.padding * 2) / 2;
y -=
height / canvasScale / 2 -
(cfg.y == null ? origHeight : height + cfg.padding * 2) / 2;
}
const canvas = cfg.createCanvas
? cfg.createCanvas()
: document.createElement("canvas");
// 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 / canvasScale;
// scale the whole frame by cfg.scale (on top of whatever canvasScale we
// calculated above)
canvasScale *= cfg.scale;
width *= cfg.scale;
height *= cfg.scale;
canvas.width = width + cfg.padding * 2 * cfg.scale;
canvas.height = height + cfg.padding * 2 * cfg.scale;
const { imageCache } = await updateImageCache({ const { imageCache } = await updateImageCache({
imageCache: new Map(), imageCache: new Map(),
fileIds: getInitializedImageElements(elements).map( fileIds: getInitializedImageElements(elements).map(
(element) => element.fileId, (element) => element.fileId,
), ),
files, files: files || {},
}); });
// console.log(elements, width, height, cfg, canvasScale);
renderScene({ renderScene({
elements, elements,
appState, appState: { ...appState, width, height, offsetLeft: 0, offsetTop: 0 },
scale,
rc: rough.canvas(canvas), rc: rough.canvas(canvas),
canvas, canvas,
renderConfig: { renderConfig: {
viewBackgroundColor: exportBackground ? viewBackgroundColor : null, canvasBackgroundColor:
scrollX: -minX + exportPadding, cfg.canvasBackgroundColor === false
scrollY: -minY + exportPadding, ? // null indicates transparent background
zoom: defaultAppState.zoom, null
: cfg.canvasBackgroundColor ||
appState.viewBackgroundColor ||
DEFAULT_BACKGROUND_COLOR,
scrollX: -x + normalizedPadding,
scrollY: -y + normalizedPadding,
canvasScale,
zoom: { value: DEFAULT_ZOOM_VALUE },
remotePointerViewportCoords: {}, remotePointerViewportCoords: {},
remoteSelectedElementIds: {}, remoteSelectedElementIds: {},
shouldCacheIgnoreZoom: false, shouldCacheIgnoreZoom: false,
remotePointerUsernames: {}, remotePointerUsernames: {},
remotePointerUserStates: {}, remotePointerUserStates: {},
theme: appState.exportWithDarkMode ? "dark" : "light", theme: cfg.theme || THEME.LIGHT,
imageCache, imageCache,
renderScrollbars: false, renderScrollbars: false,
renderSelection: false, renderSelection: false,
@ -114,7 +488,7 @@ export const exportToSvg = async (
console.error(error); console.error(error);
} }
} }
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding); const [minX, minY, width, height] = getCanvasSize(elements);
// initialize SVG root // initialize SVG root
const svgRoot = document.createElementNS(SVG_NS, "svg"); const svgRoot = document.createElementNS(SVG_NS, "svg");
@ -178,25 +552,12 @@ export const exportToSvg = async (
}; };
// 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, ): [minX: number, minY: number, width: number, height: number] => {
): [number, number, number, number] => {
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 + exportPadding; const height = distance(minY, maxY);
return [minX, minY, width, height]; 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),
);
return [width, height];
};

View File

@ -2,15 +2,23 @@ import { ExcalidrawTextElement } from "../element/types";
import { AppClassProperties, AppState } from "../types"; import { AppClassProperties, AppState } from "../types";
export type RenderConfig = { export type RenderConfig = {
// AppState values // canvas related (AppState)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
scrollX: AppState["scrollX"]; scrollX: AppState["scrollX"];
scrollY: AppState["scrollY"]; scrollY: AppState["scrollY"];
/** null indicates transparent bg */ /** null indicates transparent bg */
viewBackgroundColor: AppState["viewBackgroundColor"] | null; canvasBackgroundColor: AppState["viewBackgroundColor"] | null;
zoom: AppState["zoom"]; zoom: AppState["zoom"];
shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"]; shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"];
theme: AppState["theme"]; theme: AppState["theme"];
/**
* canvas scale factor. Not related to zoom. In browsers, it's the
* devicePixelRatio. For export, it's the `appState.exportScale`
* (user setting) or whatever scale you want to use when exporting elsewhere.
*
* Bigger the scale, the more pixels (=quality).
*/
canvasScale: number;
// collab-related state // collab-related state
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
remotePointerViewportCoords: { [id: string]: { x: number; y: number } }; remotePointerViewportCoords: { [id: string]: { x: number; y: number } };

View File

@ -3,6 +3,7 @@ import { diagramFactory } from "../fixtures/diagramFixture";
import * as mockedSceneExportUtils from "../../scene/export"; import * as mockedSceneExportUtils from "../../scene/export";
import { MIME_TYPES } from "../../constants"; import { MIME_TYPES } from "../../constants";
import { exportToCanvas } from "../../scene/export";
jest.mock("../../scene/export", () => ({ jest.mock("../../scene/export", () => ({
__esmodule: true, __esmodule: true,
...jest.requireActual("../../scene/export"), ...jest.requireActual("../../scene/export"),
@ -13,8 +14,8 @@ describe("exportToCanvas", () => {
const EXPORT_PADDING = 10; const EXPORT_PADDING = 10;
it("with default arguments", async () => { it("with default arguments", async () => {
const canvas = await utils.exportToCanvas({ const canvas = await exportToCanvas({
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }), data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
}); });
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING); expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
@ -22,9 +23,13 @@ describe("exportToCanvas", () => {
}); });
it("when custom width and height", async () => { it("when custom width and height", async () => {
const canvas = await utils.exportToCanvas({ const canvas = await exportToCanvas({
data: {
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }), ...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
},
config: {
getDimensions: () => ({ width: 200, height: 200, scale: 1 }), getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
},
}); });
expect(canvas.width).toBe(200); expect(canvas.width).toBe(200);
@ -38,12 +43,17 @@ describe("exportToBlob", () => {
it("should change image/jpg to image/jpeg", async () => { it("should change image/jpg to image/jpeg", async () => {
const blob = await utils.exportToBlob({ const blob = await utils.exportToBlob({
data: {
...diagramFactory(), ...diagramFactory(),
appState: {
exportBackground: true,
},
},
config: {
getDimensions: (width, height) => ({ width, height, scale: 1 }), getDimensions: (width, height) => ({ width, height, scale: 1 }),
// testing typo in MIME type (jpg → jpeg) // testing typo in MIME type (jpg → jpeg)
mimeType: "image/jpg", mimeType: "image/jpg",
appState: {
exportBackground: true,
}, },
}); });
expect(blob?.type).toBe(MIME_TYPES.jpg); expect(blob?.type).toBe(MIME_TYPES.jpg);
@ -51,7 +61,7 @@ describe("exportToBlob", () => {
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);
}); });
@ -62,9 +72,11 @@ describe("exportToBlob", () => {
.mockImplementationOnce(() => void 0); .mockImplementationOnce(() => void 0);
await utils.exportToBlob({ await utils.exportToBlob({
...diagramFactory(), data: diagramFactory(),
config: {
mimeType: MIME_TYPES.png, mimeType: MIME_TYPES.png,
quality: 1, quality: 1,
},
}); });
expect(consoleSpy).toHaveBeenCalledWith( expect(consoleSpy).toHaveBeenCalledWith(
@ -82,7 +94,7 @@ 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 },
}), }),
}); });
@ -98,7 +110,7 @@ describe("exportToSvg", () => {
it("with deleted elements", async () => { it("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 },
}), }),
@ -109,8 +121,10 @@ describe("exportToSvg", () => {
it("with exportPadding", async () => { it("with exportPadding", async () => {
await utils.exportToSvg({ await utils.exportToSvg({
...diagramFactory({ overrides: { appState: { name: "diagram name" } } }), data: diagramFactory({
exportPadding: 0, overrides: { appState: { name: "diagram name" } },
}),
config: { padding: 0 },
}); });
expect(passedElements().length).toBe(3); expect(passedElements().length).toBe(3);
@ -121,7 +135,7 @@ describe("exportToSvg", () => {
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 },
}, },

View File

@ -16,6 +16,7 @@ describe("embedding scene data", () => {
const sourceElements = [rectangle, ellipse]; const sourceElements = [rectangle, ellipse];
const svgNode = await utils.exportToSvg({ const svgNode = await utils.exportToSvg({
data: {
elements: sourceElements, elements: sourceElements,
appState: { appState: {
viewBackgroundColor: "#ffffff", viewBackgroundColor: "#ffffff",
@ -23,6 +24,7 @@ describe("embedding scene data", () => {
exportEmbedScene: true, exportEmbedScene: true,
}, },
files: null, files: null,
},
}); });
const svg = svgNode.outerHTML; const svg = svgNode.outerHTML;
@ -46,7 +48,7 @@ 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",
@ -54,6 +56,10 @@ describe("embedding scene data", () => {
exportEmbedScene: true, exportEmbedScene: true,
}, },
files: null, files: null,
},
config: {
mimeType: "image/png",
},
}); });
const parsedString = await decodePngMetadata(blob); const parsedString = await decodePngMetadata(blob);