This commit is contained in:
dwelle 2024-03-07 20:00:03 +01:00
parent 480572f893
commit 1fd8f283cb
33 changed files with 1034 additions and 549 deletions

View File

@ -369,10 +369,12 @@ export default function App({
return false; return false;
} }
await exportToClipboard({ await exportToClipboard({
elements: excalidrawAPI.getSceneElements(), data: {
appState: excalidrawAPI.getAppState(), elements: excalidrawAPI.getSceneElements(),
files: excalidrawAPI.getFiles(), appState: excalidrawAPI.getAppState(),
type, files: excalidrawAPI.getFiles(),
},
type: "json",
}); });
window.alert(`Copied to clipboard as ${type} successfully`); window.alert(`Copied to clipboard as ${type} successfully`);
}; };
@ -817,15 +819,17 @@ export default function App({
return; return;
} }
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: excalidrawAPI?.getSceneElements(), data: {
appState: { elements: excalidrawAPI?.getSceneElements(),
...initialData.appState, appState: {
exportWithDarkMode, ...initialData.appState,
exportEmbedScene, exportWithDarkMode,
width: 300, exportEmbedScene,
height: 100, width: 300,
height: 100,
},
files: excalidrawAPI?.getFiles(),
}, },
files: excalidrawAPI?.getFiles(),
}); });
appRef.current.querySelector(".export-svg").innerHTML = appRef.current.querySelector(".export-svg").innerHTML =
svg.outerHTML; svg.outerHTML;
@ -841,14 +845,18 @@ export default function App({
return; return;
} }
const blob = await exportToBlob({ const blob = await exportToBlob({
elements: excalidrawAPI?.getSceneElements(), data: {
mimeType: "image/png", elements: excalidrawAPI?.getSceneElements(),
appState: { appState: {
...initialData.appState, ...initialData.appState,
exportEmbedScene, exportEmbedScene,
exportWithDarkMode, exportWithDarkMode,
},
files: excalidrawAPI?.getFiles(),
},
config: {
mimeType: "image/png",
}, },
files: excalidrawAPI?.getFiles(),
}); });
setBlobUrl(window.URL.createObjectURL(blob)); setBlobUrl(window.URL.createObjectURL(blob));
}} }}
@ -864,12 +872,14 @@ export default function App({
return; return;
} }
const canvas = await exportToCanvas({ const canvas = await exportToCanvas({
elements: excalidrawAPI.getSceneElements(), data: {
appState: { elements: excalidrawAPI.getSceneElements(),
...initialData.appState, appState: {
exportWithDarkMode, ...initialData.appState,
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";
@ -885,12 +895,14 @@ export default function App({
return; return;
} }
const canvas = await exportToCanvas({ const canvas = await exportToCanvas({
elements: excalidrawAPI.getSceneElements(), data: {
appState: { elements: excalidrawAPI.getSceneElements(),
...initialData.appState, appState: {
exportWithDarkMode, ...initialData.appState,
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

@ -9,8 +9,9 @@ import {
readSystemClipboard, readSystemClipboard,
} from "../clipboard"; } from "../clipboard";
import { actionDeleteSelected } from "./actionDeleteSelected"; import { actionDeleteSelected } from "./actionDeleteSelected";
import { exportCanvas, prepareElementsForExport } from "../data/index"; import { exportAsImage } from "../data/index";
import { isTextElement } from "../element"; import { isTextElement } from "../element";
import { prepareElementsForExport } from "../data/index";
import { t } from "../i18n"; import { t } from "../i18n";
import { isFirefox } from "../constants"; import { isFirefox } from "../constants";
@ -130,17 +131,15 @@ export const actionCopyAsSvg = register({
); );
try { try {
await exportCanvas( await exportAsImage({
"clipboard-svg", type: "clipboard-svg",
exportedElements, data: { elements: exportedElements, appState, files: app.files },
appState, config: {
app.files,
{
...appState, ...appState,
exportingFrame, exportingFrame,
name: app.getName(), name: app.getName(),
}, },
); });
return { return {
commitToHistory: false, commitToHistory: false,
}; };
@ -182,11 +181,16 @@ export const actionCopyAsPng = register({
true, true,
); );
try { try {
await exportCanvas("clipboard", exportedElements, appState, app.files, { await exportAsImage({
...appState, type: "clipboard",
exportingFrame, data: { elements: exportedElements, appState, files: app.files },
name: app.getName(), config: {
...appState,
exportingFrame,
name: appState.name || app.getName(),
},
}); });
return { return {
appState: { appState: {
...appState, ...appState,

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";
@ -52,6 +52,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,13 +1,14 @@
import { COLOR_PALETTE } from "./colors";
import { import {
COLOR_WHITE,
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 { AppState, NormalizedZoomValue } from "./types"; import { AppState } from "./types";
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio) const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
? devicePixelRatio ? devicePixelRatio
@ -88,10 +89,10 @@ export const getDefaultAppState = (): Omit<
editingFrame: null, editingFrame: null,
elementsToHighlight: null, elementsToHighlight: null,
toast: null, toast: null,
viewBackgroundColor: COLOR_PALETTE.white, viewBackgroundColor: COLOR_WHITE,
zenModeEnabled: false, zenModeEnabled: false,
zoom: { zoom: {
value: 1 as NormalizedZoomValue, value: DEFAULT_ZOOM_VALUE,
}, },
viewModeEnabled: false, viewModeEnabled: false,
pendingImageElementId: null, pendingImageElementId: null,

View File

@ -1,9 +1,6 @@
import { DEFAULT_CHART_COLOR_INDEX, getAllColorsSpecificShade } from "./colors";
import { import {
COLOR_PALETTE, COLOR_CHARCOAL_BLACK,
DEFAULT_CHART_COLOR_INDEX,
getAllColorsSpecificShade,
} from "./colors";
import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
VERTICAL_ALIGN, VERTICAL_ALIGN,
@ -171,7 +168,7 @@ const commonProps = {
fontSize: DEFAULT_FONT_SIZE, fontSize: DEFAULT_FONT_SIZE,
opacity: 100, opacity: 100,
roughness: 1, roughness: 1,
strokeColor: COLOR_PALETTE.black, strokeColor: COLOR_CHARCOAL_BLACK,
roundness: null, roundness: null,
strokeStyle: "solid", strokeStyle: "solid",
strokeWidth: 1, strokeWidth: 1,
@ -337,7 +334,7 @@ const chartBaseElements = (
y: y - chartHeight, y: y - chartHeight,
width: chartWidth, width: chartWidth,
height: chartHeight, height: chartHeight,
strokeColor: COLOR_PALETTE.black, strokeColor: COLOR_CHARCOAL_BLACK,
fillStyle: "solid", fillStyle: "solid",
opacity: 6, opacity: 6,
}) })

View File

@ -1,27 +1,25 @@
import oc from "open-color"; import oc from "open-color";
import {
COLOR_WHITE,
COLOR_CHARCOAL_BLACK,
COLOR_TRANSPARENT,
} from "./constants";
import { Merge } from "./utility-types"; import { Merge } from "./utility-types";
import { pick } from "./utils";
// FIXME can't put to utils.ts rn because of circular dependency
const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
source: R,
keys: K,
) => {
return keys.reduce((acc, key: K[number]) => {
if (key in source) {
acc[key] = source[key];
}
return acc;
}, {} as Pick<R, K[number]>) as Pick<R, K[number]>;
};
export type ColorPickerColor = export type ColorPickerColor =
| Exclude<keyof oc, "indigo" | "lime"> | Exclude<keyof oc, "indigo" | "lime" | "black">
| "transparent" | "transparent"
| "charcoal"
| "bronze"; | "bronze";
export type ColorTuple = readonly [string, string, string, string, string]; export type ColorTuple = readonly [string, string, string, string, string];
export type ColorPalette = Merge< export type ColorPalette = Merge<
Record<ColorPickerColor, ColorTuple>, Record<ColorPickerColor, ColorTuple>,
{ black: "#1e1e1e"; white: "#ffffff"; transparent: "transparent" } {
charcoal: typeof COLOR_CHARCOAL_BLACK;
white: typeof COLOR_WHITE;
transparent: typeof COLOR_TRANSPARENT;
}
>; >;
// used general type instead of specific type (ColorPalette) to support custom colors // used general type instead of specific type (ColorPalette) to support custom colors
@ -41,7 +39,7 @@ export const CANVAS_PALETTE_SHADE_INDEXES = [0, 1, 2, 3, 4] as const;
export const getSpecificColorShades = ( export const getSpecificColorShades = (
color: Exclude< color: Exclude<
ColorPickerColor, ColorPickerColor,
"transparent" | "white" | "black" | "bronze" "transparent" | "charcoal" | "black" | "white" | "bronze"
>, >,
indexArr: Readonly<ColorShadesIndexes>, indexArr: Readonly<ColorShadesIndexes>,
) => { ) => {
@ -49,9 +47,9 @@ export const getSpecificColorShades = (
}; };
export const COLOR_PALETTE = { export const COLOR_PALETTE = {
transparent: "transparent", transparent: COLOR_TRANSPARENT,
black: "#1e1e1e", charcoal: COLOR_CHARCOAL_BLACK,
white: "#ffffff", white: COLOR_WHITE,
// open-colors // open-colors
gray: getSpecificColorShades("gray", ELEMENTS_PALETTE_SHADE_INDEXES), gray: getSpecificColorShades("gray", ELEMENTS_PALETTE_SHADE_INDEXES),
red: getSpecificColorShades("red", ELEMENTS_PALETTE_SHADE_INDEXES), red: getSpecificColorShades("red", ELEMENTS_PALETTE_SHADE_INDEXES),
@ -87,7 +85,7 @@ const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
// ORDER matters for positioning in quick picker // ORDER matters for positioning in quick picker
export const DEFAULT_ELEMENT_STROKE_PICKS = [ export const DEFAULT_ELEMENT_STROKE_PICKS = [
COLOR_PALETTE.black, COLOR_PALETTE.charcoal,
COLOR_PALETTE.red[DEFAULT_ELEMENT_STROKE_COLOR_INDEX], COLOR_PALETTE.red[DEFAULT_ELEMENT_STROKE_COLOR_INDEX],
COLOR_PALETTE.green[DEFAULT_ELEMENT_STROKE_COLOR_INDEX], COLOR_PALETTE.green[DEFAULT_ELEMENT_STROKE_COLOR_INDEX],
COLOR_PALETTE.blue[DEFAULT_ELEMENT_STROKE_COLOR_INDEX], COLOR_PALETTE.blue[DEFAULT_ELEMENT_STROKE_COLOR_INDEX],
@ -125,7 +123,7 @@ export const DEFAULT_ELEMENT_STROKE_COLOR_PALETTE = {
transparent: COLOR_PALETTE.transparent, transparent: COLOR_PALETTE.transparent,
white: COLOR_PALETTE.white, white: COLOR_PALETTE.white,
gray: COLOR_PALETTE.gray, gray: COLOR_PALETTE.gray,
black: COLOR_PALETTE.black, charcoal: COLOR_PALETTE.charcoal,
bronze: COLOR_PALETTE.bronze, bronze: COLOR_PALETTE.bronze,
// rest // rest
...COMMON_ELEMENT_SHADES, ...COMMON_ELEMENT_SHADES,
@ -136,7 +134,7 @@ export const DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE = {
transparent: COLOR_PALETTE.transparent, transparent: COLOR_PALETTE.transparent,
white: COLOR_PALETTE.white, white: COLOR_PALETTE.white,
gray: COLOR_PALETTE.gray, gray: COLOR_PALETTE.gray,
black: COLOR_PALETTE.black, charcoal: COLOR_PALETTE.charcoal,
bronze: COLOR_PALETTE.bronze, bronze: COLOR_PALETTE.bronze,
...COMMON_ELEMENT_SHADES, ...COMMON_ELEMENT_SHADES,

View File

@ -90,7 +90,7 @@ import {
EDITOR_LS_KEYS, EDITOR_LS_KEYS,
isIOS, isIOS,
} from "../constants"; } from "../constants";
import { ExportedElements, exportCanvas, loadFromBlob } from "../data"; import { exportAsImage, ExportedElements, loadFromBlob } from "../data";
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library"; import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
import { restore, restoreElements } from "../data/restore"; import { restore, restoreElements } from "../data/restore";
import { import {
@ -1736,18 +1736,20 @@ class App extends React.Component<AppProps, AppState> {
opts: { exportingFrame: ExcalidrawFrameLikeElement | null }, opts: { exportingFrame: ExcalidrawFrameLikeElement | null },
) => { ) => {
trackEvent("export", type, "ui"); trackEvent("export", type, "ui");
const fileHandle = await exportCanvas( const fileHandle = await exportAsImage({
type, type,
elements, data: {
this.state, elements,
this.files, appState: this.state,
{ files: this.files,
},
config: {
exportBackground: this.state.exportBackground, exportBackground: this.state.exportBackground,
name: this.getName(), name: this.getName(),
viewBackgroundColor: this.state.viewBackgroundColor, viewBackgroundColor: this.state.viewBackgroundColor,
exportingFrame: opts.exportingFrame, exportingFrame: opts.exportingFrame,
}, },
) })
.catch(muteFSAbortError) .catch(muteFSAbortError)
.catch((error) => { .catch((error) => {
console.error(error); console.error(error);
@ -1860,14 +1862,18 @@ class App extends React.Component<AppProps, AppState> {
}); });
const blob = await exportToBlob({ const blob = await exportToBlob({
elements: this.scene.getNonDeletedElements(), data: {
appState: { elements: this.scene.getNonDeletedElements(),
...this.state, appState: {
exportBackground: true, ...this.state,
viewBackgroundColor: this.state.viewBackgroundColor, exportBackground: true,
viewBackgroundColor: this.state.viewBackgroundColor,
},
files: this.files,
},
config: {
exportingFrame: magicFrame,
}, },
exportingFrame: magicFrame,
files: this.files,
}); });
const dataURL = await getDataURL(blob); const dataURL = await getDataURL(blob);

View File

@ -205,7 +205,7 @@ export const colorPickerKeyNavHandler = ({
}); });
if (!baseColorName) { if (!baseColorName) {
onChange(COLOR_PALETTE.black); onChange(COLOR_PALETTE.charcoal);
} }
} }

View File

@ -106,19 +106,25 @@ const ImageExportModal = ({
return; return;
} }
exportToCanvas({ exportToCanvas({
elements: exportedElements, data: {
appState: { elements: exportedElements,
...appStateSnapshot, appState: {
name: projectName, ...appStateSnapshot,
exportBackground: exportWithBackground, name: projectName,
exportWithDarkMode: exportDarkMode, exportEmbedScene: embedScene,
exportScale, },
exportEmbedScene: embedScene, files,
},
config: {
canvasBackgroundColor: !exportWithBackground
? false
: appStateSnapshot.viewBackgroundColor,
padding: DEFAULT_EXPORT_PADDING,
theme: exportDarkMode ? "dark" : "light",
scale: exportScale,
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
exportingFrame,
}, },
files,
exportPadding: DEFAULT_EXPORT_PADDING,
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
exportingFrame,
}) })
.then((canvas) => { .then((canvas) => {
setRenderError(null); setRenderError(null);

View File

@ -1,7 +1,7 @@
import oc from "open-color";
import React, { useLayoutEffect, useRef, useState } from "react"; import React, { useLayoutEffect, useRef, useState } from "react";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { ChartElements, renderSpreadsheet, Spreadsheet } from "../charts"; import { ChartElements, renderSpreadsheet, Spreadsheet } from "../charts";
import { COLOR_WHITE } from "../constants";
import { ChartType } from "../element/types"; import { ChartType } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { exportToSvg } from "../scene/export"; import { exportToSvg } from "../scene/export";
@ -40,14 +40,16 @@ 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: oc.white, exportBackground: false,
viewBackgroundColor: COLOR_WHITE,
},
files: null,
}, },
null, // files });
);
svg.querySelector(".style-fonts")?.remove(); svg.querySelector(".style-fonts")?.remove();
previewNode.replaceChildren(); previewNode.replaceChildren();
previewNode.appendChild(svg); previewNode.appendChild(svg);

View File

@ -8,6 +8,7 @@ import Trans from "./Trans";
import { LibraryItems, LibraryItem, UIAppState } from "../types"; import { LibraryItems, LibraryItem, UIAppState } from "../types";
import { exportToCanvas, exportToSvg } from "../../utils/export"; import { exportToCanvas, exportToSvg } from "../../utils/export";
import { import {
COLOR_WHITE,
EDITOR_LS_KEYS, EDITOR_LS_KEYS,
EXPORT_DATA_TYPES, EXPORT_DATA_TYPES,
EXPORT_SOURCE, EXPORT_SOURCE,
@ -54,16 +55,20 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
const ctx = canvas.getContext("2d")!; const ctx = canvas.getContext("2d")!;
ctx.fillStyle = OpenColor.white; ctx.fillStyle = COLOR_WHITE;
ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillRect(0, 0, canvas.width, canvas.height);
// draw items // draw items
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
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,
},
config: {
maxWidthOrHeight: BOX_SIZE,
},
}); });
const { width, height } = itemCanvas; const { width, height } = itemCanvas;
@ -125,13 +130,15 @@ const SingleLibraryItem = ({
} }
(async () => { (async () => {
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: libItem.elements, data: {
appState: { elements: libItem.elements,
...appState, appState: {
viewBackgroundColor: OpenColor.white, ...appState,
exportBackground: true, viewBackgroundColor: COLOR_WHITE,
exportBackground: true,
},
files: null,
}, },
files: null,
}); });
node.innerHTML = svg.outerHTML; node.innerHTML = svg.outerHTML;
})(); })();

View File

@ -100,12 +100,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,
maxWidthOrHeight:
Math.max(parent.offsetWidth, parent.offsetHeight) *
window.devicePixelRatio,
},
}); });
// if converting to blob fails, there's some problem that will // if converting to blob fails, there's some problem that will
// likely prevent preview and export (e.g. canvas too big) // likely prevent preview and export (e.g. canvas too big)

View File

@ -97,7 +97,6 @@ const getRelevantAppStateProps = (
theme: appState.theme, theme: appState.theme,
pendingImageElementId: appState.pendingImageElementId, pendingImageElementId: appState.pendingImageElementId,
shouldCacheIgnoreZoom: appState.shouldCacheIgnoreZoom, shouldCacheIgnoreZoom: appState.shouldCacheIgnoreZoom,
viewBackgroundColor: appState.viewBackgroundColor,
exportScale: appState.exportScale, exportScale: appState.exportScale,
selectedElementsAreBeingDragged: appState.selectedElementsAreBeingDragged, selectedElementsAreBeingDragged: appState.selectedElementsAreBeingDragged,
gridSize: appState.gridSize, gridSize: appState.gridSize,

View File

@ -1,7 +1,7 @@
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 { COLOR_PALETTE } from "./colors";
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform); export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
export const isWindows = /^Win/.test(navigator.platform); export const isWindows = /^Win/.test(navigator.platform);
export const isAndroid = /\b(android)\b/i.test(navigator.userAgent); export const isAndroid = /\b(android)\b/i.test(navigator.userAgent);
@ -98,7 +98,6 @@ export const YOUTUBE_STATES = {
export const ENV = { export const ENV = {
TEST: "test", TEST: "test",
DEVELOPMENT: "development",
}; };
export const CLASSES = { export const CLASSES = {
@ -143,6 +142,14 @@ 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_TRANSFORM_HANDLE_SPACING = 2; export const DEFAULT_TRANSFORM_HANDLE_SPACING = 2;
export const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;
// -----------------------------------------------
// !!! these colors are tied to color picker !!!
export const COLOR_WHITE = "#ffffff";
export const COLOR_CHARCOAL_BLACK = "#1e1e1e";
export const COLOR_TRANSPARENT = "transparent";
// -----------------------------------------------
export const CANVAS_ONLY_ACTIONS = ["selectAll"]; export const CANVAS_ONLY_ACTIONS = ["selectAll"];
@ -333,8 +340,8 @@ export const DEFAULT_ELEMENT_PROPS: {
opacity: ExcalidrawElement["opacity"]; opacity: ExcalidrawElement["opacity"];
locked: ExcalidrawElement["locked"]; locked: ExcalidrawElement["locked"];
} = { } = {
strokeColor: COLOR_PALETTE.black, strokeColor: COLOR_CHARCOAL_BLACK,
backgroundColor: COLOR_PALETTE.transparent, backgroundColor: COLOR_TRANSPARENT,
fillStyle: "solid", fillStyle: "solid",
strokeWidth: 2, strokeWidth: 2,
strokeStyle: "solid", strokeStyle: "solid",

View File

@ -80,46 +80,54 @@ export const prepareElementsForExport = (
}; };
}; };
export const exportCanvas = async ( export const exportAsImage = async ({
type: Omit<ExportType, "backend">, type,
elements: ExportedElements, data,
appState: AppState, config,
files: BinaryFiles, }: {
{ type: Omit<ExportType, "backend">;
exportBackground, data: {
exportPadding = DEFAULT_EXPORT_PADDING, elements: ExportedElements;
viewBackgroundColor, appState: AppState;
name = appState.name || DEFAULT_FILENAME, files: BinaryFiles;
fileHandle = null, };
exportingFrame = null, config: {
}: {
exportBackground: boolean; exportBackground: boolean;
exportPadding?: number; padding?: number;
viewBackgroundColor: string; viewBackgroundColor: string;
/** filename, if applicable */ /** filename, if applicable */
name?: string; name?: string;
fileHandle?: FileSystemHandle | null; fileHandle?: FileSystemHandle | null;
exportingFrame: ExcalidrawFrameLikeElement | null; exportingFrame: ExcalidrawFrameLikeElement | null;
}, };
) => { }) => {
if (elements.length === 0) { // clone
const cfg = Object.assign({}, config);
cfg.padding = cfg.padding ?? DEFAULT_EXPORT_PADDING;
cfg.fileHandle = cfg.fileHandle ?? null;
cfg.exportingFrame = cfg.exportingFrame ?? null;
cfg.name = cfg.name || DEFAULT_FILENAME;
if (data.elements.length === 0) {
throw new Error(t("alerts.cannotExportEmptyCanvas")); throw new Error(t("alerts.cannotExportEmptyCanvas"));
} }
if (type === "svg" || type === "clipboard-svg") { if (type === "svg" || type === "clipboard-svg") {
const svgPromise = exportToSvg( const svgPromise = exportToSvg({
elements, data: {
{ elements: data.elements,
exportBackground, appState: {
exportWithDarkMode: appState.exportWithDarkMode, exportBackground: cfg.exportBackground,
viewBackgroundColor, exportWithDarkMode: data.appState.exportWithDarkMode,
exportPadding, viewBackgroundColor: data.appState.viewBackgroundColor,
exportScale: appState.exportScale, exportPadding: cfg.padding,
exportEmbedScene: appState.exportEmbedScene && type === "svg", exportScale: data.appState.exportScale,
exportEmbedScene: data.appState.exportEmbedScene && type === "svg",
},
files: data.files,
}, },
files, config: { exportingFrame: cfg.exportingFrame },
{ exportingFrame }, });
);
if (type === "svg") { if (type === "svg") {
return fileSave( return fileSave(
svgPromise.then((svg) => { svgPromise.then((svg) => {
@ -127,9 +135,9 @@ export const exportCanvas = async (
}), }),
{ {
description: "Export to SVG", description: "Export to SVG",
name, name: cfg.name,
extension: appState.exportEmbedScene ? "excalidraw.svg" : "svg", extension: data.appState.exportEmbedScene ? "excalidraw.svg" : "svg",
fileHandle, fileHandle: cfg.fileHandle,
}, },
); );
} else if (type === "clipboard-svg") { } else if (type === "clipboard-svg") {
@ -143,22 +151,33 @@ export const exportCanvas = async (
} }
} }
const tempCanvas = exportToCanvas(elements, appState, files, { const tempCanvas = exportToCanvas({
exportBackground, data,
viewBackgroundColor, config: {
exportPadding, canvasBackgroundColor: !cfg.exportBackground
exportingFrame, ? false
: cfg.viewBackgroundColor,
padding: cfg.padding,
theme: data.appState.exportWithDarkMode ? "dark" : "light",
scale: data.appState.exportScale,
fit: "none",
exportingFrame: cfg.exportingFrame,
},
}); });
if (type === "png") { if (type === "png") {
let blob = canvasToBlob(tempCanvas); const blob = canvasToBlob(tempCanvas);
if (data.appState.exportEmbedScene) {
if (appState.exportEmbedScene) { blob.then((blob) =>
blob = blob.then((blob) =>
import("./image").then(({ encodePngMetadata }) => import("./image").then(({ encodePngMetadata }) =>
encodePngMetadata({ encodePngMetadata({
blob, blob,
metadata: serializeAsJSON(elements, appState, files, "local"), metadata: serializeAsJSON(
data.elements,
data.appState,
data.files,
"local",
),
}), }),
), ),
); );
@ -166,11 +185,11 @@ export const exportCanvas = async (
return fileSave(blob, { return fileSave(blob, {
description: "Export to PNG", description: "Export to PNG",
name, name: cfg.name,
// FIXME reintroduce `excalidraw.png` when most people upgrade away // FIXME reintroduce `excalidraw.png` when most people upgrade away
// from 111.0.5563.64 (arm64), see #6349 // from 111.0.5563.64 (arm64), see #6349
extension: /* appState.exportEmbedScene ? "excalidraw.png" : */ "png", extension: /* appState.exportEmbedScene ? "excalidraw.png" : */ "png",
fileHandle, fileHandle: cfg.fileHandle,
}); });
} else if (type === "clipboard") { } else if (type === "clipboard") {
try { try {

View File

@ -1,6 +1,7 @@
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { exportCanvas, prepareElementsForExport } from "."; import { exportAsImage } from ".";
import { prepareElementsForExport } from ".";
import { getFileHandleType, isImageFileHandleType } from "./blob"; import { getFileHandleType, isImageFileHandleType } from "./blob";
export const resaveAsImageWithScene = async ( export const resaveAsImageWithScene = async (
@ -29,12 +30,16 @@ export const resaveAsImageWithScene = async (
false, false,
); );
await exportCanvas(fileHandleType, exportedElements, appState, files, { await exportAsImage({
exportBackground, type: fileHandleType,
viewBackgroundColor, data: { elements: exportedElements, appState, files },
name, config: {
fileHandle, exportBackground,
exportingFrame, viewBackgroundColor,
name,
fileHandle,
exportingFrame,
},
}); });
return { fileHandle }; return { fileHandle };

View File

@ -11,13 +11,17 @@ export const libraryItemSvgsCache = atom<SvgCache>(new Map());
const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => { const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => {
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: {
// renderEmbeddables: false,
}, },
files: null,
renderEmbeddables: false,
}); });
}; };

View File

@ -1,5 +1,6 @@
import { exportToCanvas } from "./scene/export"; import { exportToCanvas } from "./scene/export";
import { getDefaultAppState } from "./appState"; import { getDefaultAppState } from "./appState";
import { COLOR_WHITE } from "./constants";
const { registerFont, createCanvas } = require("canvas"); const { registerFont, createCanvas } = require("canvas");
@ -57,22 +58,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,
...getDefaultAppState(), appState: {
offsetTop: 0, ...getDefaultAppState(),
offsetLeft: 0, width: 0,
width: 0, height: 0,
height: 0, },
files: {}, // files
}, },
{}, // files config: {
{ canvasBackgroundColor: COLOR_WHITE,
exportBackground: true, createCanvas,
viewBackgroundColor: "#ffffff",
}, },
createCanvas, });
);
const fs = require("fs"); const fs = require("fs");
const out = fs.createWriteStream("test.png"); const out = fs.createWriteStream("test.png");

View File

@ -219,7 +219,6 @@ export {
} from "./data/restore"; } from "./data/restore";
export { export {
exportToCanvas,
exportToBlob, exportToBlob,
exportToSvg, exportToSvg,
exportToClipboard, exportToClipboard,
@ -258,6 +257,8 @@ export { useDevice } from "./components/App";
export { WelcomeScreen }; export { WelcomeScreen };
export { LiveCollaborationTrigger }; export { LiveCollaborationTrigger };
export { exportToCanvas } from "./scene/export";
export { DefaultSidebar } from "./components/DefaultSidebar"; export { DefaultSidebar } from "./components/DefaultSidebar";
export { TTDDialog } from "./components/TTDDialog/TTDDialog"; export { TTDDialog } from "./components/TTDDialog/TTDDialog";
export { TTDDialogTrigger } from "./components/TTDDialog/TTDDialogTrigger"; export { TTDDialogTrigger } from "./components/TTDDialog/TTDDialogTrigger";

View File

@ -34,15 +34,16 @@ export const bootstrapCanvas = ({
normalizedHeight, normalizedHeight,
theme, theme,
isExporting, isExporting,
viewBackgroundColor, canvasBackgroundColor,
}: { }: {
canvas: HTMLCanvasElement; canvas: HTMLCanvasElement;
scale: number; scale: number;
normalizedWidth: number; normalizedWidth: number;
normalizedHeight: number; normalizedHeight: number;
theme?: AppState["theme"]; theme?: AppState["theme"];
// static canvas only
isExporting?: StaticCanvasRenderConfig["isExporting"]; isExporting?: StaticCanvasRenderConfig["isExporting"];
viewBackgroundColor?: StaticCanvasAppState["viewBackgroundColor"]; canvasBackgroundColor?: string | null;
}): CanvasRenderingContext2D => { }): CanvasRenderingContext2D => {
const context = canvas.getContext("2d")!; const context = canvas.getContext("2d")!;
@ -54,17 +55,17 @@ export const bootstrapCanvas = ({
} }
// Paint background // Paint background
if (typeof viewBackgroundColor === "string") { if (typeof canvasBackgroundColor === "string") {
const hasTransparence = const hasTransparence =
viewBackgroundColor === "transparent" || canvasBackgroundColor === "transparent" ||
viewBackgroundColor.length === 5 || // #RGBA canvasBackgroundColor.length === 5 || // #RGBA
viewBackgroundColor.length === 9 || // #RRGGBBA canvasBackgroundColor.length === 9 || // #RRGGBBA
/(hsla|rgba)\(/.test(viewBackgroundColor); /(hsla|rgba)\(/.test(canvasBackgroundColor);
if (hasTransparence) { if (hasTransparence) {
context.clearRect(0, 0, normalizedWidth, normalizedHeight); context.clearRect(0, 0, normalizedWidth, normalizedHeight);
} }
context.save(); context.save();
context.fillStyle = viewBackgroundColor; context.fillStyle = canvasBackgroundColor;
context.fillRect(0, 0, normalizedWidth, normalizedHeight); context.fillRect(0, 0, normalizedWidth, normalizedHeight);
context.restore(); context.restore();
} else { } else {

View File

@ -190,7 +190,7 @@ const _renderStaticScene = ({
normalizedHeight, normalizedHeight,
theme: appState.theme, theme: appState.theme,
isExporting, isExporting,
viewBackgroundColor: appState.viewBackgroundColor, canvasBackgroundColor: renderConfig.canvasBackgroundColor,
}); });
// Apply zoom // Apply zoom

View File

@ -156,8 +156,10 @@ const getArrowheadShapes = (
arrowhead: Arrowhead, arrowhead: Arrowhead,
generator: RoughGenerator, generator: RoughGenerator,
options: Options, options: Options,
canvasBackgroundColor: string, canvasBackgroundColor: string | null,
) => { ) => {
canvasBackgroundColor = canvasBackgroundColor || "transparent";
const arrowheadPoints = getArrowheadPoints( const arrowheadPoints = getArrowheadPoints(
element, element,
shape, shape,
@ -285,7 +287,7 @@ export const _generateElementShape = (
embedsValidationStatus, embedsValidationStatus,
}: { }: {
isExporting: boolean; isExporting: boolean;
canvasBackgroundColor: string; canvasBackgroundColor: string | null;
embedsValidationStatus: EmbedsValidationStatus | null; embedsValidationStatus: EmbedsValidationStatus | null;
}, },
): Drawable | Drawable[] | null => { ): Drawable | Drawable[] | null => {

View File

@ -6,9 +6,9 @@ import {
} from "../element/types"; } from "../element/types";
import { elementWithCanvasCache } from "../renderer/renderElement"; import { elementWithCanvasCache } from "../renderer/renderElement";
import { _generateElementShape } from "./Shape"; import { _generateElementShape } from "./Shape";
import { ElementShape, ElementShapes } from "./types"; import { ElementShape, ElementShapes, StaticCanvasRenderConfig } from "./types";
import { COLOR_PALETTE } from "../colors"; import { COLOR_PALETTE } from "../colors";
import { AppState, EmbedsValidationStatus } from "../types"; import { EmbedsValidationStatus } from "../types";
export class ShapeCache { export class ShapeCache {
private static rg = new RoughGenerator(); private static rg = new RoughGenerator();
@ -50,7 +50,7 @@ export class ShapeCache {
element: T, element: T,
renderConfig: { renderConfig: {
isExporting: boolean; isExporting: boolean;
canvasBackgroundColor: AppState["viewBackgroundColor"]; canvasBackgroundColor: StaticCanvasRenderConfig["canvasBackgroundColor"];
embedsValidationStatus: EmbedsValidationStatus; embedsValidationStatus: EmbedsValidationStatus;
} | null, } | null,
) => { ) => {

View File

@ -5,6 +5,7 @@ import {
ExcalidrawTextElement, ExcalidrawTextElement,
NonDeletedExcalidrawElement, NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap, NonDeletedSceneElementsMap,
Theme,
} from "../element/types"; } from "../element/types";
import { import {
Bounds, Bounds,
@ -15,10 +16,13 @@ import { renderSceneToSvg } from "../renderer/staticSvgScene";
import { arrayToMap, distance, getFontString, toBrandedType } from "../utils"; import { arrayToMap, distance, getFontString, toBrandedType } from "../utils";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { import {
COLOR_WHITE,
DEFAULT_EXPORT_PADDING, DEFAULT_EXPORT_PADDING,
DEFAULT_ZOOM_VALUE,
FONT_FAMILY, FONT_FAMILY,
FRAME_STYLE, FRAME_STYLE,
SVG_NS, SVG_NS,
THEME,
THEME_FILTER, THEME_FILTER,
} from "../constants"; } from "../constants";
import { getDefaultAppState } from "../appState"; import { getDefaultAppState } from "../appState";
@ -27,6 +31,7 @@ import {
getInitializedImageElements, getInitializedImageElements,
updateImageCache, updateImageCache,
} from "../element/image"; } from "../element/image";
import { restoreAppState } from "../data/restore";
import { import {
getElementsOverlappingFrame, getElementsOverlappingFrame,
getFrameLikeElements, getFrameLikeElements,
@ -159,31 +164,203 @@ const prepareElementsForRender = ({
return nextElements; return nextElements;
}; };
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;
exportingFrame, /**
}: { * Canvas background. Valid values are:
exportBackground: boolean; *
exportPadding?: number; * - `undefined` - the background of "appState.viewBackgroundColor" is used.
viewBackgroundColor: string; * - `false` - no background is used (set to "transparent").
exportingFrame?: ExcalidrawFrameLikeElement | null; * - `string` - should be a valid CSS color.
}, *
createCanvas: ( * @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; exportingFrame?: ExcalidrawFrameLikeElement | null;
canvas.height = height * appState.exportScale; };
return { canvas, scale: appState.exportScale };
}, /**
) => { * 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;
}) => {
// clone
const cfg = Object.assign({}, config);
const { files } = data;
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,
appState.frameRendering ?? null, appState.frameRendering ?? null,
@ -197,24 +374,213 @@ 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");
const containPadding = cfg.fit === "contain";
if (cfg.x != null || cfg.x != null) {
cfg.fit = "none";
}
if (cfg.fit === "cover") {
if (cfg.padding && !import.meta.env.PROD) {
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 (!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;
}
// ---------------------------------------------------------------------------
// 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(
exportingFrame ? [exportingFrame] : getRootElements(elementsForRender), exportingFrame ? [exportingFrame] : getRootElements(elementsForRender),
exportPadding,
); );
const { canvas, scale = 1 } = createCanvas(width, height); // cfg.x = undefined;
// cfg.y = undefined;
const defaultAppState = getDefaultAppState(); // 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(elementsForRender).map( fileIds: getInitializedImageElements(elementsForRender).map(
(element) => element.fileId, (element) => element.fileId,
), ),
files, files: files || {},
}); });
renderStaticScene({ renderStaticScene({
@ -227,19 +593,29 @@ export const exportToCanvas = async (
arrayToMap(elements), arrayToMap(elements),
), ),
visibleElements: elementsForRender, visibleElements: elementsForRender,
scale,
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 ? "dark" : "light", theme: cfg.theme || THEME.LIGHT,
}, },
scale: canvasScale,
renderConfig: { renderConfig: {
canvasBackgroundColor: viewBackgroundColor, canvasBackgroundColor:
cfg.canvasBackgroundColor === false
? // null indicates transparent background
null
: cfg.canvasBackgroundColor ||
appState.viewBackgroundColor ||
COLOR_WHITE,
imageCache, imageCache,
renderGrid: false, renderGrid: false,
isExporting: true, isExporting: true,
@ -252,29 +628,41 @@ export const exportToCanvas = async (
return canvas; return canvas;
}; };
export const exportToSvg = async ( export const exportToSvg = async ({
elements: readonly NonDeletedExcalidrawElement[], data,
appState: { config,
exportBackground: boolean; }: {
exportPadding?: number; data: {
exportScale?: number; elements: readonly NonDeletedExcalidrawElement[];
viewBackgroundColor: string; appState: {
exportWithDarkMode?: boolean; exportBackground: boolean;
exportEmbedScene?: boolean; exportPadding?: number;
frameRendering?: AppState["frameRendering"]; exportScale?: number;
}, viewBackgroundColor: string;
files: BinaryFiles | null, exportWithDarkMode?: boolean;
opts?: { exportEmbedScene?: boolean;
frameRendering?: AppState["frameRendering"];
};
files: BinaryFiles | null;
};
config?: {
/** /**
* if true, all embeddables passed in will be rendered when possible. * if true, all embeddables passed in will be rendered when possible.
*/ */
renderEmbeddables?: boolean; renderEmbeddables?: boolean;
exportingFrame?: ExcalidrawFrameLikeElement | null; exportingFrame?: ExcalidrawFrameLikeElement | null;
}, };
): Promise<SVGSVGElement> => { }): Promise<SVGSVGElement> => {
// clone
const cfg = Object.assign({}, config);
cfg.exportingFrame = cfg.exportingFrame ?? null;
const elements = data.elements;
const frameRendering = getFrameRenderingConfig( const frameRendering = getFrameRenderingConfig(
opts?.exportingFrame ?? null, cfg?.exportingFrame ?? null,
appState.frameRendering ?? null, data.appState.frameRendering ?? null,
); );
let { let {
@ -283,18 +671,16 @@ export const exportToSvg = async (
viewBackgroundColor, viewBackgroundColor,
exportScale = 1, exportScale = 1,
exportEmbedScene, exportEmbedScene,
} = appState; } = data.appState;
const { exportingFrame = null } = opts || {};
const elementsForRender = prepareElementsForRender({ const elementsForRender = prepareElementsForRender({
elements, elements,
exportingFrame, exportingFrame: cfg.exportingFrame,
exportWithDarkMode, exportWithDarkMode,
frameRendering, frameRendering,
}); });
if (exportingFrame) { if (cfg.exportingFrame) {
exportPadding = 0; exportPadding = 0;
} }
@ -311,18 +697,27 @@ 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.
text: serializeAsJSON(elements, appState, files || {}, "local"), text: serializeAsJSON(
elements,
data.appState,
data.files || {},
"local",
),
}); });
} catch (error: any) { } catch (error: any) {
console.error(error); console.error(error);
} }
} }
const [minX, minY, width, height] = getCanvasSize( let [minX, minY, width, height] = getCanvasSize(
exportingFrame ? [exportingFrame] : getRootElements(elementsForRender), cfg.exportingFrame
exportPadding, ? [cfg.exportingFrame]
: getRootElements(elementsForRender),
); );
width += exportPadding * 2;
height += exportPadding * 2;
// initialize SVG root // initialize SVG root
const svgRoot = document.createElementNS(SVG_NS, "svg"); const svgRoot = document.createElementNS(SVG_NS, "svg");
svgRoot.setAttribute("version", "1.1"); svgRoot.setAttribute("version", "1.1");
@ -395,7 +790,7 @@ export const exportToSvg = async (
`; `;
// render background rect // render background rect
if (appState.exportBackground && viewBackgroundColor) { if (data.appState.exportBackground && 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");
@ -407,14 +802,14 @@ export const exportToSvg = async (
const rsvg = rough.svg(svgRoot); const rsvg = rough.svg(svgRoot);
const renderEmbeddables = opts?.renderEmbeddables ?? false; const renderEmbeddables = cfg.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,
@ -437,25 +832,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,
): 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];
}; };
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

@ -20,7 +20,6 @@ export type RenderableElementsMap = NonDeletedElementsMap &
MakeBrand<"RenderableElementsMap">; MakeBrand<"RenderableElementsMap">;
export type StaticCanvasRenderConfig = { export type StaticCanvasRenderConfig = {
canvasBackgroundColor: AppState["viewBackgroundColor"];
// extra options passed to the renderer // extra options passed to the renderer
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
imageCache: AppClassProperties["imageCache"]; imageCache: AppClassProperties["imageCache"];
@ -28,6 +27,8 @@ export type StaticCanvasRenderConfig = {
/** when exporting the behavior is slightly different (e.g. we can't use /** when exporting the behavior is slightly different (e.g. we can't use
CSS filters), and we disable render optimizations for best output */ CSS filters), and we disable render optimizations for best output */
isExporting: boolean; isExporting: boolean;
/** null indicates transparent bg */
canvasBackgroundColor: string | null;
embedsValidationStatus: EmbedsValidationStatus; embedsValidationStatus: EmbedsValidationStatus;
elementsPendingErasure: ElementsPendingErasure; elementsPendingErasure: ElementsPendingErasure;
}; };
@ -69,6 +70,13 @@ export type StaticSceneRenderConfig = {
elementsMap: RenderableElementsMap; elementsMap: RenderableElementsMap;
allElementsMap: NonDeletedSceneElementsMap; allElementsMap: NonDeletedSceneElementsMap;
visibleElements: readonly NonDeletedExcalidrawElement[]; visibleElements: readonly NonDeletedExcalidrawElement[];
/**
* 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).
*/
scale: number; scale: number;
appState: StaticCanvasAppState; appState: StaticCanvasAppState;
renderConfig: StaticCanvasRenderConfig; renderConfig: StaticCanvasRenderConfig;

View File

@ -6,5 +6,5 @@ exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active too
B --&gt; C{Let me think} B --&gt; C{Let me think}
C --&gt;|One| D[Laptop] C --&gt;|One| D[Laptop]
C --&gt;|Two| E[iPhone] C --&gt;|Two| E[iPhone]
C --&gt;|Three| F[Car]</textarea><div class="ttd-dialog-panel-button-container invisible" style="display: flex; align-items: center;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class=""></div></button></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-panel__header"><label>Preview</label></div><div class="ttd-dialog-output-wrapper"><div style="opacity: 1;" class="ttd-dialog-output-canvas-container"><canvas width="89" height="158" dir="ltr"></canvas></div></div><div class="ttd-dialog-panel-button-container" style="display: flex; align-items: center;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>" C --&gt;|Three| F[Car]</textarea><div class="ttd-dialog-panel-button-container invisible" style="display: flex; align-items: center;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class=""></div></button></div></div><div class="ttd-dialog-panel"><div class="ttd-dialog-panel__header"><label>Preview</label></div><div class="ttd-dialog-output-wrapper"><div style="opacity: 1;" class="ttd-dialog-output-canvas-container"><canvas width="9" height="0" dir="ltr"></canvas></div></div><div class="ttd-dialog-panel-button-container" style="display: flex; align-items: center;"><button type="button" class="excalidraw-button ttd-dialog-panel-button"><div class="">Insert<span><svg aria-hidden="true" focusable="false" role="img" viewBox="0 0 20 20" class="" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.25"><path d="M4.16602 10H15.8327"></path><path d="M12.5 13.3333L15.8333 10"></path><path d="M12.5 6.66666L15.8333 9.99999"></path></g></svg></span></div></button><div class="ttd-dialog-submit-shortcut"><div class="ttd-dialog-submit-shortcut__key">Ctrl</div><div class="ttd-dialog-submit-shortcut__key">Enter</div></div></div></div></div></div></div></div></div></div></div>"
`; `;

View File

@ -162,7 +162,7 @@ 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;

View File

@ -26,11 +26,9 @@ describe("exportToSvg", () => {
}; };
it("with default arguments", async () => { it("with default arguments", async () => {
const svgElement = await exportUtils.exportToSvg( const svgElement = await exportUtils.exportToSvg({
ELEMENTS, data: { elements: ELEMENTS, appState: DEFAULT_OPTIONS, files: null },
DEFAULT_OPTIONS, });
null,
);
expect(svgElement).toMatchSnapshot(); expect(svgElement).toMatchSnapshot();
}); });
@ -38,15 +36,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_OPTIONS,
viewBackgroundColor: BACKGROUND_COLOR, exportBackground: true,
viewBackgroundColor: BACKGROUND_COLOR,
},
files: null,
}, },
null, });
);
expect(svgElement.querySelector("rect")).toHaveAttribute( expect(svgElement.querySelector("rect")).toHaveAttribute(
"fill", "fill",
@ -55,14 +55,16 @@ 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_OPTIONS,
exportWithDarkMode: true,
},
files: null,
}, },
null, });
);
expect(svgElement.getAttribute("filter")).toMatchInlineSnapshot( expect(svgElement.getAttribute("filter")).toMatchInlineSnapshot(
'"_themeFilter_1883f3"', '"_themeFilter_1883f3"',
@ -70,14 +72,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: {
exportPadding: 0, ...DEFAULT_OPTIONS,
exportPadding: 0,
},
files: null,
}, },
null, });
);
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());
@ -90,15 +94,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: {
exportPadding: 0, ...DEFAULT_OPTIONS,
exportScale: SCALE, exportPadding: 0,
exportScale: SCALE,
},
files: null,
}, },
null, });
);
expect(svgElement).toHaveAttribute( expect(svgElement).toHaveAttribute(
"height", "height",
@ -111,23 +117,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_OPTIONS,
exportEmbedScene: true,
},
files: null,
}, },
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_OPTIONS,
); files: null,
},
});
expect(svgElement.innerHTML).toMatchSnapshot(); expect(svgElement.innerHTML).toMatchSnapshot();
}); });
}); });
@ -167,9 +177,13 @@ describe("exporting frames", () => {
]; ];
const canvas = await exportToCanvas({ const canvas = await exportToCanvas({
elements, data: {
files: null, elements,
exportPadding: 0, files: null,
},
config: {
padding: 0,
},
}); });
expect(canvas.width).toEqual(200); expect(canvas.width).toEqual(200);
@ -196,10 +210,14 @@ describe("exporting frames", () => {
]; ];
const canvas = await exportToCanvas({ const canvas = await exportToCanvas({
elements, data: {
files: null, elements,
exportPadding: 0, files: null,
exportingFrame: frame, },
config: {
padding: 0,
exportingFrame: frame,
},
}); });
expect(canvas.width).toEqual(frame.width); expect(canvas.width).toEqual(frame.width);
@ -235,10 +253,11 @@ describe("exporting frames", () => {
}); });
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: [rectOverlapping, frame, frameChild], data: { elements: [rectOverlapping, frame, frameChild], files: null },
files: null, config: {
exportPadding: 0, padding: 0,
exportingFrame: frame, exportingFrame: frame,
},
}); });
// frame itself isn't exported // frame itself isn't exported
@ -279,10 +298,11 @@ describe("exporting frames", () => {
}); });
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: [frameChild, frame, elementOutside], data: { elements: [frameChild, frame, elementOutside], files: null },
files: null, config: {
exportPadding: 0, padding: 0,
exportingFrame: frame, exportingFrame: frame,
},
}); });
// frame itself isn't exported // frame itself isn't exported
@ -347,10 +367,11 @@ describe("exporting frames", () => {
); );
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: exportedElements, data: { elements: exportedElements, files: null },
files: null, config: {
exportPadding: 0, padding: 0,
exportingFrame, exportingFrame,
},
}); });
// frames themselves should be exported when multiple frames selected // frames themselves should be exported when multiple frames selected
@ -392,10 +413,14 @@ describe("exporting frames", () => {
); );
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: exportedElements, data: {
files: null, elements: exportedElements,
exportPadding: 0, files: null,
exportingFrame, },
config: {
padding: 0,
exportingFrame,
},
}); });
// frame itself isn't exported // frame itself isn't exported
@ -451,10 +476,14 @@ describe("exporting frames", () => {
); );
const svg = await exportToSvg({ const svg = await exportToSvg({
elements: exportedElements, data: {
files: null, elements: exportedElements,
exportPadding: 0, files: null,
exportingFrame, },
config: {
padding: 0,
exportingFrame,
},
}); });
// frame shouldn't be exported // frame shouldn't be exported

View File

@ -152,8 +152,6 @@ type _CommonCanvasAppState = {
export type StaticCanvasAppState = Readonly< export type StaticCanvasAppState = Readonly<
_CommonCanvasAppState & { _CommonCanvasAppState & {
shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"]; shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"];
/** null indicates transparent bg */
viewBackgroundColor: AppState["viewBackgroundColor"] | null;
exportScale: AppState["exportScale"]; exportScale: AppState["exportScale"];
selectedElementsAreBeingDragged: AppState["selectedElementsAreBeingDragged"]; selectedElementsAreBeingDragged: AppState["selectedElementsAreBeingDragged"];
gridSize: AppState["gridSize"]; gridSize: AppState["gridSize"];

View File

@ -1,5 +1,5 @@
import { COLOR_PALETTE } from "./colors";
import { import {
COLOR_TRANSPARENT,
DEFAULT_VERSION, DEFAULT_VERSION,
EVENT, EVENT,
FONT_FAMILY, FONT_FAMILY,
@ -530,11 +530,7 @@ export const findLastIndex = <T>(
export const isTransparent = (color: string) => { export const isTransparent = (color: string) => {
const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0"; const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00"; const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
return ( return isRGBTransparent || isRRGGBBTransparent || color === COLOR_TRANSPARENT;
isRGBTransparent ||
isRRGGBBTransparent ||
color === COLOR_PALETTE.transparent
);
}; };
export type ResolvablePromise<T> = Promise<T> & { export type ResolvablePromise<T> = Promise<T> & {
@ -1090,3 +1086,18 @@ export const toBrandedType = <BrandedType, CurrentType = BrandedType>(
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
export const pick = <
R extends Record<string, any>,
K extends readonly (keyof R)[],
>(
source: R,
keys: K,
) => {
return keys.reduce((acc, key: K[number]) => {
if (key in source) {
acc[key] = source[key];
}
return acc;
}, {} as Pick<R, K[number]>) as Pick<R, K[number]>;
};

View File

@ -5,24 +5,27 @@ import * as mockedSceneExportUtils from "../excalidraw/scene/export";
import { MIME_TYPES } from "../excalidraw/constants"; import { MIME_TYPES } from "../excalidraw/constants";
import { exportToCanvas } from "../excalidraw/scene/export";
const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg"); const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg");
describe("exportToCanvas", async () => { describe("exportToCanvas", async () => {
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);
expect(canvas.height).toBe(100 + 2 * EXPORT_PADDING); expect(canvas.height).toBe(100);
}); });
it("when custom width and height", async () => { it("when custom width and height", async () => {
const canvas = await utils.exportToCanvas({ const canvas = await exportToCanvas({
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }), data: {
getDimensions: () => ({ width: 200, height: 200, scale: 1 }), ...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
},
config: {
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
},
}); });
expect(canvas.width).toBe(200); expect(canvas.width).toBe(200);
@ -35,19 +38,24 @@ describe("exportToBlob", async () => {
// afterEach(vi.restoreAllMocks); // afterEach(vi.restoreAllMocks);
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({
...diagramFactory(), data: {
getDimensions: (width, height) => ({ width, height, scale: 1 }), ...diagramFactory(),
// testing typo in MIME type (jpg → jpeg)
mimeType: "image/jpg", appState: {
appState: { exportBackground: true,
exportBackground: true, },
},
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);
}); });
@ -57,9 +65,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`,
@ -69,8 +79,8 @@ describe("exportToBlob", async () => {
}); });
describe("exportToSvg", () => { describe("exportToSvg", () => {
const passedElements = () => exportToSvgSpy.mock.calls[0][0]; const passedElements = () => exportToSvgSpy.mock.calls[0][0].data.elements;
const passedOptions = () => exportToSvgSpy.mock.calls[0][1]; const passedOptions = () => exportToSvgSpy.mock.calls[0][0].data.appState;
afterEach(() => { afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
@ -78,7 +88,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 },
}), }),
}); });
@ -97,7 +107,7 @@ 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 },
}), }),
@ -108,8 +118,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);
@ -120,7 +132,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

@ -1,16 +1,11 @@
import { import {
exportToCanvas as _exportToCanvas, exportToCanvas as _exportToCanvas,
ExportToCanvasConfig,
ExportToCanvasData,
exportToSvg as _exportToSvg, exportToSvg as _exportToSvg,
} from "../excalidraw/scene/export"; } from "../excalidraw/scene/export";
import { getDefaultAppState } from "../excalidraw/appState";
import { AppState, BinaryFiles } from "../excalidraw/types";
import {
ExcalidrawElement,
ExcalidrawFrameLikeElement,
NonDeleted,
} from "../excalidraw/element/types";
import { restore } from "../excalidraw/data/restore"; import { restore } from "../excalidraw/data/restore";
import { MIME_TYPES } from "../excalidraw/constants"; import { COLOR_WHITE, MIME_TYPES } from "../excalidraw/constants";
import { encodePngMetadata } from "../excalidraw/data/image"; import { encodePngMetadata } from "../excalidraw/data/image";
import { serializeAsJSON } from "../excalidraw/data/json"; import { serializeAsJSON } from "../excalidraw/data/json";
import { import {
@ -18,91 +13,46 @@ import {
copyTextToSystemClipboard, copyTextToSystemClipboard,
copyToClipboard, copyToClipboard,
} from "../excalidraw/clipboard"; } from "../excalidraw/clipboard";
import { getNonDeletedElements } from "../excalidraw";
export { MIME_TYPES }; export { MIME_TYPES };
type ExportOpts = { type ExportToBlobConfig = ExportToCanvasConfig & {
elements: readonly NonDeleted<ExcalidrawElement>[]; mimeType?: string;
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>; quality?: number;
files: BinaryFiles | null;
maxWidthOrHeight?: number;
exportingFrame?: ExcalidrawFrameLikeElement | null;
getDimensions?: (
width: number,
height: number,
) => { width: number; height: number; scale?: number };
}; };
export const exportToCanvas = ({ type ExportToSvgConfig = Pick<
elements, ExportToCanvasConfig,
appState, "canvasBackgroundColor" | "padding" | "theme" | "exportingFrame"
files, > & {
maxWidthOrHeight, /**
getDimensions, * if true, all embeddables passed in will be rendered when possible.
exportPadding, */
exportingFrame, renderEmbeddables?: boolean;
}: ExportOpts & { };
exportPadding?: number;
export const exportToCanvas = async ({
data,
config,
}: {
data: ExportToCanvasData;
config?: ExportToCanvasConfig;
}) => { }) => {
const { elements: restoredElements, appState: restoredAppState } = restore( return _exportToCanvas({
{ elements, appState }, data,
null, config,
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 ( export const exportToBlob = async ({
opts: ExportOpts & { data,
mimeType?: string; config,
quality?: number; }: {
exportPadding?: number; data: ExportToCanvasData;
}, config?: ExportToBlobConfig;
): Promise<Blob> => { }): Promise<Blob> => {
let { mimeType = MIME_TYPES.png, quality } = opts; 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`);
@ -113,17 +63,17 @@ 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 || COLOR_WHITE,
}; };
} }
const canvas = await exportToCanvas(opts); const canvas = await _exportToCanvas({ data, 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;
@ -136,7 +86,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,
@ -144,9 +94,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",
), ),
}); });
@ -160,47 +110,49 @@ export const exportToBlob = async (
}; };
export const exportToSvg = async ({ export const exportToSvg = async ({
elements, data,
appState = getDefaultAppState(), config,
files = {}, }: {
exportPadding, data: ExportToCanvasData;
renderEmbeddables, config?: ExportToSvgConfig;
exportingFrame,
}: Omit<ExportOpts, "getDimensions"> & {
exportPadding?: number;
renderEmbeddables?: boolean;
}): 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(restoredElements, exportAppState, files, { return _exportToSvg({
exportingFrame, data: { elements, appState, files },
renderEmbeddables, config: {
exportingFrame: config?.exportingFrame,
renderEmbeddables: config?.renderEmbeddables,
},
}); });
}; };
export const exportToClipboard = async ( export const exportToClipboard = async ({
opts: ExportOpts & { type,
mimeType?: string; data,
quality?: number; config,
type: "png" | "svg" | "json"; }: {
}, data: ExportToCanvasData;
) => { } & (
if (opts.type === "svg") { | { type: "png"; config?: ExportToBlobConfig }
const svg = await exportToSvg(opts); | { 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

@ -16,13 +16,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: {
gridSize: null, viewBackgroundColor: "#ffffff",
exportEmbedScene: true, gridSize: null,
exportEmbedScene: true,
},
files: null,
}, },
files: null,
}); });
const svg = svgNode.outerHTML; const svg = svgNode.outerHTML;
@ -46,14 +48,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",
gridSize: null, gridSize: null,
exportEmbedScene: true, exportEmbedScene: true,
},
files: null,
},
config: {
mimeType: "image/png",
}, },
files: null,
}); });
const parsedString = await decodePngMetadata(blob); const parsedString = await decodePngMetadata(blob);