Compare commits
5 Commits
master
...
dwelle/fix
Author | SHA1 | Date | |
---|---|---|---|
![]() |
de81123cee | ||
![]() |
a3c20e6663 | ||
![]() |
a218bec343 | ||
![]() |
a6fe2d91a6 | ||
![]() |
f11b81c2e5 |
@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
<h4 align="center">
|
<h4 align="center">
|
||||||
<a href="https://excalidraw.com">Excalidraw Editor</a> |
|
<a href="https://excalidraw.com">Excalidraw Editor</a> |
|
||||||
<a href="https://blog.excalidraw.com">Blog</a> |
|
<a href="https://plus.excalidraw.com/blog">Blog</a> |
|
||||||
<a href="https://docs.excalidraw.com">Documentation</a> |
|
<a href="https://docs.excalidraw.com">Documentation</a> |
|
||||||
<a href="https://plus.excalidraw.com">Excalidraw+</a>
|
<a href="https://plus.excalidraw.com">Excalidraw+</a>
|
||||||
</h4>
|
</h4>
|
||||||
|
@ -66,7 +66,7 @@ const config = {
|
|||||||
label: "Docs",
|
label: "Docs",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
to: "https://blog.excalidraw.com",
|
to: "https://plus.excalidraw.com/blog",
|
||||||
label: "Blog",
|
label: "Blog",
|
||||||
position: "left",
|
position: "left",
|
||||||
},
|
},
|
||||||
@ -111,7 +111,7 @@ const config = {
|
|||||||
items: [
|
items: [
|
||||||
{
|
{
|
||||||
label: "Blog",
|
label: "Blog",
|
||||||
to: "https://blog.excalidraw.com",
|
to: "https://plus.excalidraw.com/blog",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "GitHub",
|
label: "GitHub",
|
||||||
|
@ -369,10 +369,12 @@ export default function ExampleApp({
|
|||||||
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`);
|
||||||
};
|
};
|
||||||
@ -817,6 +819,7 @@ export default function ExampleApp({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
elements: excalidrawAPI?.getSceneElements(),
|
elements: excalidrawAPI?.getSceneElements(),
|
||||||
appState: {
|
appState: {
|
||||||
...initialData.appState,
|
...initialData.appState,
|
||||||
@ -826,6 +829,7 @@ export default function ExampleApp({
|
|||||||
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;
|
||||||
@ -841,14 +845,18 @@ export default function ExampleApp({
|
|||||||
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));
|
||||||
}}
|
}}
|
||||||
@ -864,12 +872,14 @@ export default function ExampleApp({
|
|||||||
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 Excalifont";
|
ctx.font = "30px Excalifont";
|
||||||
@ -885,12 +895,14 @@ export default function ExampleApp({
|
|||||||
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 Excalifont";
|
ctx.font = "30px Excalifont";
|
||||||
|
@ -25,7 +25,12 @@ import {
|
|||||||
TTDDialogTrigger,
|
TTDDialogTrigger,
|
||||||
StoreAction,
|
StoreAction,
|
||||||
reconcileElements,
|
reconcileElements,
|
||||||
|
exportToCanvas,
|
||||||
} from "../packages/excalidraw";
|
} from "../packages/excalidraw";
|
||||||
|
import {
|
||||||
|
exportToBlob,
|
||||||
|
getNonDeletedElements,
|
||||||
|
} from "../packages/excalidraw/index";
|
||||||
import type {
|
import type {
|
||||||
AppState,
|
AppState,
|
||||||
ExcalidrawImperativeAPI,
|
ExcalidrawImperativeAPI,
|
||||||
@ -127,6 +132,8 @@ import DebugCanvas, {
|
|||||||
} from "./components/DebugCanvas";
|
} from "./components/DebugCanvas";
|
||||||
import { AIComponents } from "./components/AI";
|
import { AIComponents } from "./components/AI";
|
||||||
import { ExcalidrawPlusIframeExport } from "./ExcalidrawPlusIframeExport";
|
import { ExcalidrawPlusIframeExport } from "./ExcalidrawPlusIframeExport";
|
||||||
|
import { fileSave } from "../packages/excalidraw/data/filesystem";
|
||||||
|
import type { ExportToCanvasConfig } from "../packages/excalidraw/scene/export";
|
||||||
|
|
||||||
polyfill();
|
polyfill();
|
||||||
|
|
||||||
@ -607,6 +614,24 @@ const ExcalidrawWrapper = () => {
|
|||||||
};
|
};
|
||||||
}, [excalidrawAPI]);
|
}, [excalidrawAPI]);
|
||||||
|
|
||||||
|
const canvasPreviewContainerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const [config, setConfig] = useState<ExportToCanvasConfig>(
|
||||||
|
JSON.parse(localStorage.getItem("_exportConfig") || "null") || {
|
||||||
|
width: 300,
|
||||||
|
height: 100,
|
||||||
|
padding: 2,
|
||||||
|
scale: 1,
|
||||||
|
position: "none",
|
||||||
|
fit: "contain",
|
||||||
|
canvasBackgroundColor: "yellow",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
localStorage.setItem("_exportConfig", JSON.stringify(config));
|
||||||
|
}, [config]);
|
||||||
|
|
||||||
const onChange = (
|
const onChange = (
|
||||||
elements: readonly OrderedExcalidrawElement[],
|
elements: readonly OrderedExcalidrawElement[],
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
@ -616,6 +641,91 @@ const ExcalidrawWrapper = () => {
|
|||||||
collabAPI.syncElements(elements);
|
collabAPI.syncElements(elements);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
const frame = elements.find(
|
||||||
|
(el) => el.strokeStyle === "dashed" && !el.isDeleted,
|
||||||
|
);
|
||||||
|
|
||||||
|
exportToCanvas({
|
||||||
|
data: {
|
||||||
|
elements: getNonDeletedElements(elements).filter(
|
||||||
|
(x) => x.id !== frame?.id,
|
||||||
|
),
|
||||||
|
// .concat(
|
||||||
|
// restoreElements(
|
||||||
|
// [
|
||||||
|
// // @ts-ignore
|
||||||
|
// {
|
||||||
|
// type: "rectangle",
|
||||||
|
// width: appState.width / zoom,
|
||||||
|
// height: appState.height / zoom,
|
||||||
|
// x: -appState.scrollX,
|
||||||
|
// y: -appState.scrollY,
|
||||||
|
// fillStyle: "solid",
|
||||||
|
// strokeColor: "transparent",
|
||||||
|
// backgroundColor: "rgba(0,0,0,0.05)",
|
||||||
|
// roundness: { type: ROUNDNESS.ADAPTIVE_RADIUS, value: 40 },
|
||||||
|
// },
|
||||||
|
// ],
|
||||||
|
// null,
|
||||||
|
// ),
|
||||||
|
// ),
|
||||||
|
appState,
|
||||||
|
files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
// // light yellow
|
||||||
|
// // canvasBackgroundColor: "#fff9c4",
|
||||||
|
// // width,
|
||||||
|
// // maxWidthOrHeight: 120,
|
||||||
|
// // scale: 0.01,
|
||||||
|
// // scale: 2,
|
||||||
|
// // origin: "content",
|
||||||
|
// // fit: "cover",
|
||||||
|
// // scale: 2,
|
||||||
|
// // x: 0,
|
||||||
|
// // y: 0,
|
||||||
|
// padding: 20,
|
||||||
|
|
||||||
|
// ...config,
|
||||||
|
|
||||||
|
// width: config.width,
|
||||||
|
// height: config.height,
|
||||||
|
// maxWidthOrHeight: config.maxWidthOrHeight,
|
||||||
|
// widthOrHeight: config.widthOrHeight,
|
||||||
|
// padding: config.padding,
|
||||||
|
...(frame
|
||||||
|
? {
|
||||||
|
...config,
|
||||||
|
width: frame.width,
|
||||||
|
height: frame.height,
|
||||||
|
x: frame.x,
|
||||||
|
y: frame.y,
|
||||||
|
}
|
||||||
|
: config),
|
||||||
|
// // height: 140,
|
||||||
|
// // x: -appState.scrollX,
|
||||||
|
// // y: -appState.scrollY,
|
||||||
|
// // height: 150,
|
||||||
|
// // height: appState.height,
|
||||||
|
// // scale,
|
||||||
|
// // zoom: { value: appState.zoom.value },
|
||||||
|
// // getDimensions(width,height) {
|
||||||
|
// // setCanvasSize({ width, height })
|
||||||
|
// // return {width: 300, height: 150}
|
||||||
|
// // }
|
||||||
|
},
|
||||||
|
}).then((canvas) => {
|
||||||
|
if (canvasPreviewContainerRef.current) {
|
||||||
|
canvasPreviewContainerRef.current.replaceChildren(canvas);
|
||||||
|
document.querySelector(
|
||||||
|
".dims",
|
||||||
|
)!.innerHTML = `${canvas.width}x${canvas.height}`;
|
||||||
|
// canvas.style.width = "100%";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// this check is redundant, but since this is a hot path, it's best
|
// this check is redundant, but since this is a hot path, it's best
|
||||||
// not to evaludate the nested expression every time
|
// not to evaludate the nested expression every time
|
||||||
if (!LocalData.isSavePaused()) {
|
if (!LocalData.isSavePaused()) {
|
||||||
@ -1121,6 +1231,233 @@ const ExcalidrawWrapper = () => {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</Excalidraw>
|
</Excalidraw>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
position: "fixed",
|
||||||
|
bottom: 60,
|
||||||
|
right: 60,
|
||||||
|
zIndex: 9999999999,
|
||||||
|
color: "black",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", gap: "1rem", flexDirection: "column" }}>
|
||||||
|
<div style={{ display: "flex", gap: "1rem" }}>
|
||||||
|
<label>
|
||||||
|
center{" "}
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={config.position === "center"}
|
||||||
|
onChange={() =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
position: s.position === "center" ? "topLeft" : "center",
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
fit{" "}
|
||||||
|
<select
|
||||||
|
value={config.fit}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
fit: event.target.value as any,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="none">none</option>
|
||||||
|
<option value="contain">contain</option>
|
||||||
|
<option value="cover">cover</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
padding{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
max={600}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.padding}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
padding: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: Math.min(parseInt(event.target.value as any), 600),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
scale{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
max={4}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.scale}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
scale: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: Math.min(parseFloat(event.target.value as any), 4),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", gap: "1rem" }}>
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
opacity:
|
||||||
|
config.maxWidthOrHeight != null ||
|
||||||
|
config.widthOrHeight != null
|
||||||
|
? 0.5
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
width{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
max={600}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.width}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
width: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: Math.min(parseInt(event.target.value as any), 600),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
opacity:
|
||||||
|
config.maxWidthOrHeight != null ||
|
||||||
|
config.widthOrHeight != null
|
||||||
|
? 0.5
|
||||||
|
: undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
height{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
max={600}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.height}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
height: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: Math.min(parseInt(event.target.value as any), 600),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
x{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.x}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
x: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: parseFloat(event.target.value as any) ?? undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
y{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.y}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
y: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: parseFloat(event.target.value as any) ?? undefined,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label
|
||||||
|
style={{
|
||||||
|
opacity: config.widthOrHeight != null ? 0.5 : undefined,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
maxWH{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
// max={600}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.maxWidthOrHeight}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
maxWidthOrHeight: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: parseInt(event.target.value as any),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
widthOrHeight{" "}
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
max={600}
|
||||||
|
style={{ width: "3rem" }}
|
||||||
|
value={config.widthOrHeight}
|
||||||
|
onChange={(event) =>
|
||||||
|
setConfig((s) => ({
|
||||||
|
...s,
|
||||||
|
widthOrHeight: !event.target.value.trim()
|
||||||
|
? undefined
|
||||||
|
: Math.min(parseInt(event.target.value as any), 600),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="dims">0x0</div>
|
||||||
|
<div
|
||||||
|
ref={canvasPreviewContainerRef}
|
||||||
|
onClick={() => {
|
||||||
|
exportToBlob({
|
||||||
|
data: {
|
||||||
|
elements: excalidrawAPI!.getSceneElements(),
|
||||||
|
files: excalidrawAPI?.getFiles() || null,
|
||||||
|
},
|
||||||
|
config,
|
||||||
|
}).then((blob) => {
|
||||||
|
fileSave(blob, {
|
||||||
|
name: "xx",
|
||||||
|
extension: "png",
|
||||||
|
description: "xxx",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
borderRadius: 12,
|
||||||
|
border: "1px solid #777",
|
||||||
|
overflow: "hidden",
|
||||||
|
padding: 10,
|
||||||
|
backgroundColor: "pink",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@ -21,15 +21,19 @@ export const AIComponents = ({
|
|||||||
const appState = excalidrawAPI.getAppState();
|
const appState = excalidrawAPI.getAppState();
|
||||||
|
|
||||||
const blob = await exportToBlob({
|
const blob = await exportToBlob({
|
||||||
|
data: {
|
||||||
elements: children,
|
elements: children,
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
exportBackground: true,
|
exportBackground: true,
|
||||||
viewBackgroundColor: appState.viewBackgroundColor,
|
viewBackgroundColor: appState.viewBackgroundColor,
|
||||||
},
|
},
|
||||||
exportingFrame: frame,
|
|
||||||
files: excalidrawAPI.getFiles(),
|
files: excalidrawAPI.getFiles(),
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
exportingFrame: frame,
|
||||||
mimeType: MIME_TYPES.jpg,
|
mimeType: MIME_TYPES.jpg,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const dataURL = await getDataURL(blob);
|
const dataURL = await getDataURL(blob);
|
||||||
|
@ -84,7 +84,7 @@ const _debugRenderer = (
|
|||||||
scale,
|
scale,
|
||||||
normalizedWidth,
|
normalizedWidth,
|
||||||
normalizedHeight,
|
normalizedHeight,
|
||||||
viewBackgroundColor: "transparent",
|
canvasBackgroundColor: "transparent",
|
||||||
});
|
});
|
||||||
|
|
||||||
// Apply zoom
|
// Apply zoom
|
||||||
|
@ -8,7 +8,7 @@ export const EncryptedIcon = () => {
|
|||||||
return (
|
return (
|
||||||
<a
|
<a
|
||||||
className="encrypted-icon tooltip"
|
className="encrypted-icon tooltip"
|
||||||
href="https://blog.excalidraw.com/end-to-end-encryption/"
|
href="https://plus.excalidraw.com/blog/end-to-end-encryption/"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
aria-label={t("encrypted.link")}
|
aria-label={t("encrypted.link")}
|
||||||
|
@ -54,6 +54,8 @@
|
|||||||
content="https://excalidraw.com/og-image-3.png"
|
content="https://excalidraw.com/og-image-3.png"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<link rel="canonical" href="https://excalidraw.com" />
|
||||||
|
|
||||||
<!------------------------------------------------------------------------->
|
<!------------------------------------------------------------------------->
|
||||||
<!-- to minimize white flash on load when user has dark mode enabled -->
|
<!-- to minimize white flash on load when user has dark mode enabled -->
|
||||||
<script>
|
<script>
|
||||||
|
@ -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 { getTextFromElements, isTextElement } from "../element";
|
import { getTextFromElements, isTextElement } from "../element";
|
||||||
|
import { prepareElementsForExport } from "../data/index";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { isFirefox } from "../constants";
|
import { isFirefox } from "../constants";
|
||||||
import { DuplicateIcon, cutIcon, pngIcon, svgIcon } from "../components/icons";
|
import { DuplicateIcon, cutIcon, pngIcon, svgIcon } from "../components/icons";
|
||||||
@ -136,17 +137,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(),
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
|
|
||||||
const selectedElements = app.scene.getSelectedElements({
|
const selectedElements = app.scene.getSelectedElements({
|
||||||
selectedElementIds: appState.selectedElementIds,
|
selectedElementIds: appState.selectedElementIds,
|
||||||
@ -208,11 +207,16 @@ export const actionCopyAsPng = register({
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await exportCanvas("clipboard", exportedElements, appState, app.files, {
|
await exportAsImage({
|
||||||
|
type: "clipboard",
|
||||||
|
data: { elements: exportedElements, appState, files: app.files },
|
||||||
|
config: {
|
||||||
...appState,
|
...appState,
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
name: app.getName(),
|
name: appState.name || app.getName(),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
|
@ -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 type { Theme } from "../element/types";
|
import type { NonDeletedExcalidrawElement, Theme } from "../element/types";
|
||||||
|
|
||||||
import "../components/ToolIcon.scss";
|
import "../components/ToolIcon.scss";
|
||||||
import { StoreAction } from "../store";
|
import { StoreAction } from "../store";
|
||||||
@ -58,6 +58,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) => {
|
||||||
|
@ -1,17 +1,18 @@
|
|||||||
import { COLOR_PALETTE } from "./colors";
|
|
||||||
import {
|
import {
|
||||||
ARROW_TYPE,
|
ARROW_TYPE,
|
||||||
|
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_GRID_SIZE,
|
DEFAULT_GRID_SIZE,
|
||||||
|
DEFAULT_ZOOM_VALUE,
|
||||||
EXPORT_SCALES,
|
EXPORT_SCALES,
|
||||||
STATS_PANELS,
|
STATS_PANELS,
|
||||||
THEME,
|
THEME,
|
||||||
DEFAULT_GRID_STEP,
|
DEFAULT_GRID_STEP,
|
||||||
} from "./constants";
|
} from "./constants";
|
||||||
import type { AppState, NormalizedZoomValue } from "./types";
|
import type { AppState } from "./types";
|
||||||
|
|
||||||
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
|
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
|
||||||
? devicePixelRatio
|
? devicePixelRatio
|
||||||
@ -99,10 +100,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,
|
||||||
|
@ -1,11 +1,8 @@
|
|||||||
import type { Radians } from "../math";
|
import type { Radians } from "../math";
|
||||||
import { pointFrom } from "../math";
|
import { pointFrom } from "../math";
|
||||||
|
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,
|
||||||
@ -173,7 +170,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,
|
||||||
@ -324,7 +321,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,
|
||||||
})
|
})
|
||||||
|
@ -1,27 +1,25 @@
|
|||||||
import oc from "open-color";
|
import oc from "open-color";
|
||||||
import type { Merge } from "./utility-types";
|
import {
|
||||||
|
COLOR_WHITE,
|
||||||
// FIXME can't put to utils.ts rn because of circular dependency
|
COLOR_CHARCOAL_BLACK,
|
||||||
const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
|
COLOR_TRANSPARENT,
|
||||||
source: R,
|
} from "./constants";
|
||||||
keys: K,
|
import { type Merge } from "./utility-types";
|
||||||
) => {
|
import { pick } from "./utils";
|
||||||
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,
|
||||||
|
@ -90,7 +90,7 @@ import {
|
|||||||
DEFAULT_TEXT_ALIGN,
|
DEFAULT_TEXT_ALIGN,
|
||||||
} from "../constants";
|
} from "../constants";
|
||||||
import type { ExportedElements } from "../data";
|
import type { ExportedElements } from "../data";
|
||||||
import { exportCanvas, loadFromBlob } from "../data";
|
import { exportAsImage, 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 {
|
||||||
@ -1815,18 +1815,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,
|
||||||
|
data: {
|
||||||
elements,
|
elements,
|
||||||
this.state,
|
appState: this.state,
|
||||||
this.files,
|
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);
|
||||||
|
@ -204,7 +204,7 @@ export const colorPickerKeyNavHandler = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!baseColorName) {
|
if (!baseColorName) {
|
||||||
onChange(COLOR_PALETTE.black);
|
onChange(COLOR_PALETTE.charcoal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -23,7 +23,6 @@ import { nativeFileSystemSupported } from "../data/filesystem";
|
|||||||
import type { NonDeletedExcalidrawElement } from "../element/types";
|
import type { NonDeletedExcalidrawElement } from "../element/types";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { isSomeElementSelected } from "../scene";
|
import { isSomeElementSelected } from "../scene";
|
||||||
import { exportToCanvas } from "../../utils/export";
|
|
||||||
|
|
||||||
import { copyIcon, downloadIcon, helpIcon } from "./icons";
|
import { copyIcon, downloadIcon, helpIcon } from "./icons";
|
||||||
import { Dialog } from "./Dialog";
|
import { Dialog } from "./Dialog";
|
||||||
@ -36,6 +35,7 @@ import { FilledButton } from "./FilledButton";
|
|||||||
import { cloneJSON } from "../utils";
|
import { cloneJSON } from "../utils";
|
||||||
import { prepareElementsForExport } from "../data";
|
import { prepareElementsForExport } from "../data";
|
||||||
import { useCopyStatus } from "../hooks/useCopiedIndicator";
|
import { useCopyStatus } from "../hooks/useCopiedIndicator";
|
||||||
|
import { exportToCanvas } from "../scene/export";
|
||||||
|
|
||||||
const supportsContextFilters =
|
const supportsContextFilters =
|
||||||
"filter" in document.createElement("canvas").getContext("2d")!;
|
"filter" in document.createElement("canvas").getContext("2d")!;
|
||||||
@ -123,19 +123,25 @@ const ImageExportModal = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
exportToCanvas({
|
exportToCanvas({
|
||||||
|
data: {
|
||||||
elements: exportedElements,
|
elements: exportedElements,
|
||||||
appState: {
|
appState: {
|
||||||
...appStateSnapshot,
|
...appStateSnapshot,
|
||||||
name: projectName,
|
name: projectName,
|
||||||
exportBackground: exportWithBackground,
|
|
||||||
exportWithDarkMode: exportDarkMode,
|
|
||||||
exportScale,
|
|
||||||
exportEmbedScene: embedScene,
|
exportEmbedScene: embedScene,
|
||||||
},
|
},
|
||||||
files,
|
files,
|
||||||
exportPadding: DEFAULT_EXPORT_PADDING,
|
},
|
||||||
|
config: {
|
||||||
|
canvasBackgroundColor: !exportWithBackground
|
||||||
|
? false
|
||||||
|
: appStateSnapshot.viewBackgroundColor,
|
||||||
|
padding: DEFAULT_EXPORT_PADDING,
|
||||||
|
theme: exportDarkMode ? "dark" : "light",
|
||||||
|
scale: exportScale,
|
||||||
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
|
maxWidthOrHeight: Math.max(maxWidth, maxHeight),
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
.then((canvas) => {
|
.then((canvas) => {
|
||||||
setRenderError(null);
|
setRenderError(null);
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
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 type { ChartElements, Spreadsheet } from "../charts";
|
import type { ChartElements, Spreadsheet } from "../charts";
|
||||||
import { renderSpreadsheet } from "../charts";
|
import { renderSpreadsheet } from "../charts";
|
||||||
import type { ChartType } from "../element/types";
|
import type { ChartType } from "../element/types";
|
||||||
|
import { COLOR_WHITE } from "../constants";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { exportToSvg } from "../scene/export";
|
import { exportToSvg } from "../scene/export";
|
||||||
import type { UIAppState } from "../types";
|
import type { UIAppState } from "../types";
|
||||||
@ -41,17 +41,19 @@ const ChartPreviewBtn = (props: {
|
|||||||
const previewNode = previewRef.current!;
|
const previewNode = previewRef.current!;
|
||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
svg = await exportToSvg(
|
svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
elements,
|
elements,
|
||||||
{
|
appState: {
|
||||||
exportBackground: false,
|
exportBackground: false,
|
||||||
viewBackgroundColor: oc.white,
|
viewBackgroundColor: COLOR_WHITE,
|
||||||
},
|
},
|
||||||
null, // files
|
files: null,
|
||||||
{
|
},
|
||||||
|
config: {
|
||||||
skipInliningFonts: true,
|
skipInliningFonts: true,
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
svg.querySelector(".style-fonts")?.remove();
|
svg.querySelector(".style-fonts")?.remove();
|
||||||
previewNode.replaceChildren();
|
previewNode.replaceChildren();
|
||||||
previewNode.appendChild(svg);
|
previewNode.appendChild(svg);
|
||||||
|
@ -7,8 +7,8 @@ import { t } from "../i18n";
|
|||||||
import Trans from "./Trans";
|
import Trans from "./Trans";
|
||||||
|
|
||||||
import type { LibraryItems, LibraryItem, UIAppState } from "../types";
|
import type { LibraryItems, LibraryItem, UIAppState } from "../types";
|
||||||
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,
|
||||||
@ -24,6 +24,7 @@ import { ToolButton } from "./ToolButton";
|
|||||||
import { EditorLocalStorage } from "../data/EditorLocalStorage";
|
import { EditorLocalStorage } from "../data/EditorLocalStorage";
|
||||||
|
|
||||||
import "./PublishLibrary.scss";
|
import "./PublishLibrary.scss";
|
||||||
|
import { exportToCanvas, exportToSvg } from "../scene/export";
|
||||||
|
|
||||||
interface PublishLibraryDataParams {
|
interface PublishLibraryDataParams {
|
||||||
authorName: string;
|
authorName: string;
|
||||||
@ -55,16 +56,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({
|
||||||
|
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;
|
||||||
@ -126,14 +131,18 @@ const SingleLibraryItem = ({
|
|||||||
}
|
}
|
||||||
(async () => {
|
(async () => {
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
elements: libItem.elements,
|
elements: libItem.elements,
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
viewBackgroundColor: OpenColor.white,
|
viewBackgroundColor: COLOR_WHITE,
|
||||||
exportBackground: true,
|
exportBackground: true,
|
||||||
},
|
},
|
||||||
files: null,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
skipInliningFonts: true,
|
skipInliningFonts: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
node.innerHTML = svg.outerHTML;
|
node.innerHTML = svg.outerHTML;
|
||||||
})();
|
})();
|
||||||
|
@ -91,12 +91,16 @@ export const convertMermaidToExcalidraw = async ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
|
data: {
|
||||||
elements: data.current.elements,
|
elements: data.current.elements,
|
||||||
files: data.current.files,
|
files: data.current.files,
|
||||||
exportPadding: DEFAULT_EXPORT_PADDING,
|
},
|
||||||
|
config: {
|
||||||
|
padding: DEFAULT_EXPORT_PADDING,
|
||||||
maxWidthOrHeight:
|
maxWidthOrHeight:
|
||||||
Math.max(parent.offsetWidth, parent.offsetHeight) *
|
Math.max(parent.offsetWidth, parent.offsetHeight) *
|
||||||
window.devicePixelRatio,
|
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)
|
||||||
|
@ -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,
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import cssVariables from "./css/variables.module.scss";
|
import cssVariables from "./css/variables.module.scss";
|
||||||
import type { AppProps, AppState } from "./types";
|
import type { AppProps, AppState } from "./types";
|
||||||
import type { ExcalidrawElement, FontFamilyValues } from "./element/types";
|
import type { ExcalidrawElement, FontFamilyValues } from "./element/types";
|
||||||
import { COLOR_PALETTE } from "./colors";
|
import type { NormalizedZoomValue } from "./types";
|
||||||
|
|
||||||
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);
|
||||||
@ -108,7 +108,6 @@ export const YOUTUBE_STATES = {
|
|||||||
|
|
||||||
export const ENV = {
|
export const ENV = {
|
||||||
TEST: "test",
|
TEST: "test",
|
||||||
DEVELOPMENT: "development",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const CLASSES = {
|
export const CLASSES = {
|
||||||
@ -184,6 +183,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 SIDE_RESIZING_THRESHOLD = 2 * DEFAULT_TRANSFORM_HANDLE_SPACING;
|
export const SIDE_RESIZING_THRESHOLD = 2 * DEFAULT_TRANSFORM_HANDLE_SPACING;
|
||||||
// a small epsilon to make side resizing always take precedence
|
// a small epsilon to make side resizing always take precedence
|
||||||
@ -192,8 +199,6 @@ const EPSILON = 0.00001;
|
|||||||
export const DEFAULT_COLLISION_THRESHOLD =
|
export const DEFAULT_COLLISION_THRESHOLD =
|
||||||
2 * SIDE_RESIZING_THRESHOLD - EPSILON;
|
2 * SIDE_RESIZING_THRESHOLD - EPSILON;
|
||||||
|
|
||||||
export const COLOR_WHITE = "#ffffff";
|
|
||||||
export const COLOR_CHARCOAL_BLACK = "#1e1e1e";
|
|
||||||
// keep this in sync with CSS
|
// keep this in sync with CSS
|
||||||
export const COLOR_VOICE_CALL = "#a2f1a6";
|
export const COLOR_VOICE_CALL = "#a2f1a6";
|
||||||
|
|
||||||
@ -384,8 +389,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",
|
||||||
|
@ -81,46 +81,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,
|
|
||||||
{
|
|
||||||
exportBackground,
|
|
||||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
|
||||||
viewBackgroundColor,
|
|
||||||
name = appState.name || DEFAULT_FILENAME,
|
|
||||||
fileHandle = null,
|
|
||||||
exportingFrame = null,
|
|
||||||
}: {
|
}: {
|
||||||
|
type: Omit<ExportType, "backend">;
|
||||||
|
data: {
|
||||||
|
elements: ExportedElements;
|
||||||
|
appState: AppState;
|
||||||
|
files: BinaryFiles;
|
||||||
|
};
|
||||||
|
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,
|
files: data.files,
|
||||||
{ exportingFrame },
|
},
|
||||||
);
|
config: { exportingFrame: cfg.exportingFrame },
|
||||||
|
});
|
||||||
if (type === "svg") {
|
if (type === "svg") {
|
||||||
return fileSave(
|
return fileSave(
|
||||||
svgPromise.then((svg) => {
|
svgPromise.then((svg) => {
|
||||||
@ -128,9 +136,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") {
|
||||||
@ -144,22 +152,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",
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@ -167,11 +186,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 {
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import type { ExcalidrawElement } from "../element/types";
|
import type { ExcalidrawElement } from "../element/types";
|
||||||
import type { AppState, BinaryFiles } from "../types";
|
import type { AppState, BinaryFiles } from "../types";
|
||||||
import { exportCanvas, prepareElementsForExport } from ".";
|
import { prepareElementsForExport } from ".";
|
||||||
|
import { exportAsImage } 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({
|
||||||
|
type: fileHandleType,
|
||||||
|
data: { elements: exportedElements, appState, files },
|
||||||
|
config: {
|
||||||
exportBackground,
|
exportBackground,
|
||||||
viewBackgroundColor,
|
viewBackgroundColor,
|
||||||
name,
|
name,
|
||||||
fileHandle,
|
fileHandle,
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
return { fileHandle };
|
return { fileHandle };
|
||||||
|
@ -2,8 +2,8 @@ import { atom, useAtom } from "jotai";
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { COLOR_PALETTE } from "../colors";
|
import { COLOR_PALETTE } from "../colors";
|
||||||
import { jotaiScope } from "../jotai";
|
import { jotaiScope } from "../jotai";
|
||||||
import { exportToSvg } from "../../utils/export";
|
|
||||||
import type { LibraryItem } from "../types";
|
import type { LibraryItem } from "../types";
|
||||||
|
import { exportToSvg } from "../scene/export";
|
||||||
|
|
||||||
export type SvgCache = Map<LibraryItem["id"], SVGSVGElement>;
|
export type SvgCache = Map<LibraryItem["id"], SVGSVGElement>;
|
||||||
|
|
||||||
@ -11,14 +11,18 @@ 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({
|
||||||
|
data: {
|
||||||
elements,
|
elements,
|
||||||
appState: {
|
appState: {
|
||||||
exportBackground: false,
|
exportBackground: false,
|
||||||
viewBackgroundColor: COLOR_PALETTE.white,
|
viewBackgroundColor: COLOR_PALETTE.white,
|
||||||
},
|
},
|
||||||
files: null,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
renderEmbeddables: false,
|
renderEmbeddables: false,
|
||||||
skipInliningFonts: true,
|
skipInliningFonts: true,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -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,
|
||||||
|
appState: {
|
||||||
...getDefaultAppState(),
|
...getDefaultAppState(),
|
||||||
offsetTop: 0,
|
|
||||||
offsetLeft: 0,
|
|
||||||
width: 0,
|
width: 0,
|
||||||
height: 0,
|
height: 0,
|
||||||
},
|
},
|
||||||
{}, // files
|
files: {}, // files
|
||||||
{
|
|
||||||
exportBackground: true,
|
|
||||||
viewBackgroundColor: "#ffffff",
|
|
||||||
},
|
},
|
||||||
|
config: {
|
||||||
|
canvasBackgroundColor: COLOR_WHITE,
|
||||||
createCanvas,
|
createCanvas,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
|
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const out = fs.createWriteStream("test.png");
|
const out = fs.createWriteStream("test.png");
|
||||||
|
@ -225,13 +225,6 @@ export {
|
|||||||
|
|
||||||
export { reconcileElements } from "./data/reconcile";
|
export { reconcileElements } from "./data/reconcile";
|
||||||
|
|
||||||
export {
|
|
||||||
exportToCanvas,
|
|
||||||
exportToBlob,
|
|
||||||
exportToSvg,
|
|
||||||
exportToClipboard,
|
|
||||||
} from "../utils/export";
|
|
||||||
|
|
||||||
export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";
|
export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";
|
||||||
export {
|
export {
|
||||||
loadFromBlob,
|
loadFromBlob,
|
||||||
@ -274,6 +267,13 @@ export { WelcomeScreen };
|
|||||||
export { LiveCollaborationTrigger };
|
export { LiveCollaborationTrigger };
|
||||||
export { Stats } from "./components/Stats";
|
export { Stats } from "./components/Stats";
|
||||||
|
|
||||||
|
export {
|
||||||
|
exportToCanvas,
|
||||||
|
exportToBlob,
|
||||||
|
exportToClipboard,
|
||||||
|
exportToSvg,
|
||||||
|
} 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";
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import type { StaticCanvasAppState, AppState } from "../types";
|
import type { AppState } from "../types";
|
||||||
|
|
||||||
import type { StaticCanvasRenderConfig } from "../scene/types";
|
import type { StaticCanvasRenderConfig } from "../scene/types";
|
||||||
|
|
||||||
@ -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 {
|
||||||
|
@ -216,7 +216,7 @@ const _renderStaticScene = ({
|
|||||||
normalizedHeight,
|
normalizedHeight,
|
||||||
theme: appState.theme,
|
theme: appState.theme,
|
||||||
isExporting,
|
isExporting,
|
||||||
viewBackgroundColor: appState.viewBackgroundColor,
|
canvasBackgroundColor: renderConfig.canvasBackgroundColor,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Apply zoom
|
// Apply zoom
|
||||||
|
@ -164,8 +164,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,
|
||||||
@ -293,7 +295,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 => {
|
||||||
|
@ -8,7 +8,8 @@ import { elementWithCanvasCache } from "../renderer/renderElement";
|
|||||||
import { _generateElementShape } from "./Shape";
|
import { _generateElementShape } from "./Shape";
|
||||||
import type { ElementShape, ElementShapes } from "./types";
|
import type { ElementShape, ElementShapes } from "./types";
|
||||||
import { COLOR_PALETTE } from "../colors";
|
import { COLOR_PALETTE } from "../colors";
|
||||||
import type { AppState, EmbedsValidationStatus } from "../types";
|
import type { EmbedsValidationStatus } from "../types";
|
||||||
|
import type { StaticCanvasRenderConfig } from "./types";
|
||||||
|
|
||||||
export class ShapeCache {
|
export class ShapeCache {
|
||||||
private static rg = new RoughGenerator();
|
private static rg = new RoughGenerator();
|
||||||
@ -50,7 +51,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,
|
||||||
) => {
|
) => {
|
||||||
|
@ -5,6 +5,7 @@ import type {
|
|||||||
ExcalidrawTextElement,
|
ExcalidrawTextElement,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
NonDeletedSceneElementsMap,
|
NonDeletedSceneElementsMap,
|
||||||
|
Theme,
|
||||||
} from "../element/types";
|
} from "../element/types";
|
||||||
import type { Bounds } from "../element/bounds";
|
import type { Bounds } from "../element/bounds";
|
||||||
import { getCommonBounds, getElementAbsoluteCoords } from "../element/bounds";
|
import { getCommonBounds, getElementAbsoluteCoords } from "../element/bounds";
|
||||||
@ -12,12 +13,15 @@ import { renderSceneToSvg } from "../renderer/staticSvgScene";
|
|||||||
import { arrayToMap, distance, getFontString, toBrandedType } from "../utils";
|
import { arrayToMap, distance, getFontString, toBrandedType } from "../utils";
|
||||||
import type { AppState, BinaryFiles } from "../types";
|
import type { AppState, BinaryFiles } from "../types";
|
||||||
import {
|
import {
|
||||||
|
COLOR_WHITE,
|
||||||
DEFAULT_EXPORT_PADDING,
|
DEFAULT_EXPORT_PADDING,
|
||||||
|
DEFAULT_ZOOM_VALUE,
|
||||||
FRAME_STYLE,
|
FRAME_STYLE,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
SVG_NS,
|
SVG_NS,
|
||||||
THEME,
|
THEME,
|
||||||
THEME_FILTER,
|
THEME_FILTER,
|
||||||
|
MIME_TYPES,
|
||||||
} from "../constants";
|
} from "../constants";
|
||||||
import { getDefaultAppState } from "../appState";
|
import { getDefaultAppState } from "../appState";
|
||||||
import { serializeAsJSON } from "../data/json";
|
import { serializeAsJSON } from "../data/json";
|
||||||
@ -25,13 +29,14 @@ import {
|
|||||||
getInitializedImageElements,
|
getInitializedImageElements,
|
||||||
updateImageCache,
|
updateImageCache,
|
||||||
} from "../element/image";
|
} from "../element/image";
|
||||||
|
import { restore, restoreAppState } from "../data/restore";
|
||||||
import {
|
import {
|
||||||
getElementsOverlappingFrame,
|
getElementsOverlappingFrame,
|
||||||
getFrameLikeElements,
|
getFrameLikeElements,
|
||||||
getFrameLikeTitle,
|
getFrameLikeTitle,
|
||||||
getRootElements,
|
getRootElements,
|
||||||
} from "../frame";
|
} from "../frame";
|
||||||
import { newTextElement } from "../element";
|
import { getNonDeletedElements, newTextElement } from "../element";
|
||||||
import { type Mutable } from "../utility-types";
|
import { type Mutable } from "../utility-types";
|
||||||
import { newElementWith } from "../element/mutateElement";
|
import { newElementWith } from "../element/mutateElement";
|
||||||
import { isFrameLikeElement } from "../element/typeChecks";
|
import { isFrameLikeElement } from "../element/typeChecks";
|
||||||
@ -39,6 +44,12 @@ import type { RenderableElementsMap } from "./types";
|
|||||||
import { syncInvalidIndices } from "../fractionalIndex";
|
import { syncInvalidIndices } from "../fractionalIndex";
|
||||||
import { renderStaticScene } from "../renderer/staticScene";
|
import { renderStaticScene } from "../renderer/staticScene";
|
||||||
import { Fonts } from "../fonts";
|
import { Fonts } from "../fonts";
|
||||||
|
import { encodePngMetadata } from "../data/image";
|
||||||
|
import {
|
||||||
|
copyBlobToClipboardAsPng,
|
||||||
|
copyTextToSystemClipboard,
|
||||||
|
copyToClipboard,
|
||||||
|
} from "../clipboard";
|
||||||
|
|
||||||
const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
||||||
|
|
||||||
@ -149,36 +160,208 @@ const prepareElementsForRender = ({
|
|||||||
return nextElements;
|
return nextElements;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToCanvas = async (
|
type ExportToCanvasAppState = Partial<
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
Omit<AppState, "offsetTop" | "offsetLeft">
|
||||||
appState: AppState,
|
>;
|
||||||
files: BinaryFiles,
|
|
||||||
{
|
export type ExportToCanvasData = {
|
||||||
exportBackground,
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
appState?: ExportToCanvasAppState;
|
||||||
viewBackgroundColor,
|
files: BinaryFiles | null;
|
||||||
exportingFrame,
|
};
|
||||||
}: {
|
|
||||||
exportBackground: boolean;
|
export type ExportToCanvasConfig = {
|
||||||
exportPadding?: number;
|
theme?: Theme;
|
||||||
viewBackgroundColor: string;
|
/**
|
||||||
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
* Canvas background. Valid values are:
|
||||||
},
|
*
|
||||||
createCanvas: (
|
* - `undefined` - the background of "appState.viewBackgroundColor" is used.
|
||||||
|
* - `false` - no background is used (set to "transparent").
|
||||||
|
* - `string` - should be a valid CSS color.
|
||||||
|
*
|
||||||
|
* @default undefined
|
||||||
|
*/
|
||||||
|
canvasBackgroundColor?: string | false;
|
||||||
|
/**
|
||||||
|
* Canvas padding in pixels. Affected by `scale`.
|
||||||
|
*
|
||||||
|
* When `fit` is set to `none`, padding is added to the content bounding box
|
||||||
|
* (including if you set `width` or `height` or `maxWidthOrHeight` or
|
||||||
|
* `widthOrHeight`).
|
||||||
|
*
|
||||||
|
* When `fit` set to `contain`, padding is subtracted from the content
|
||||||
|
* bounding box (ensuring the size doesn't exceed the supplied values, with
|
||||||
|
* the exeception of using alongside `scale` as noted above), and the padding
|
||||||
|
* serves as a minimum distance between the content and the canvas edges, as
|
||||||
|
* it may exceed the supplied padding value from one side or the other in
|
||||||
|
* order to maintain the aspect ratio. It is recommended to set `position`
|
||||||
|
* to `center` when using `fit=contain`.
|
||||||
|
*
|
||||||
|
* When `fit` is set to `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 };
|
loadFonts?: () => Promise<void>;
|
||||||
},
|
};
|
||||||
loadFonts: () => Promise<void> = async () => {
|
|
||||||
await Fonts.loadElementsFonts(elements);
|
/**
|
||||||
},
|
* 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.
|
||||||
// load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)
|
*/
|
||||||
await loadFonts();
|
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,
|
||||||
@ -198,24 +381,220 @@ 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;
|
||||||
|
}
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// load font faces before continuing, by default leverages browsers' [FontFace API](https://developer.mozilla.org/en-US/docs/Web/API/FontFace)
|
||||||
|
if (cfg.loadFonts) {
|
||||||
|
await cfg.loadFonts();
|
||||||
|
} else {
|
||||||
|
await Fonts.loadElementsFonts(elements);
|
||||||
|
}
|
||||||
|
|
||||||
|
// value used to scale the canvas context. By default, we use this to
|
||||||
|
// make the canvas fit into the frame (e.g. for `cfg.fit` set to `contain`).
|
||||||
|
// If `cfg.scale` is set, we multiply the resulting canvasScale by it to
|
||||||
|
// scale the output further.
|
||||||
|
let 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({
|
||||||
@ -228,19 +607,29 @@ export const exportToCanvas = async (
|
|||||||
arrayToMap(syncInvalidIndices(elements)),
|
arrayToMap(syncInvalidIndices(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 ? THEME.DARK : THEME.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,
|
||||||
@ -254,52 +643,72 @@ export const exportToCanvas = async (
|
|||||||
return canvas;
|
return canvas;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToSvg = async (
|
type ExportToSvgConfig = Pick<
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
ExportToCanvasConfig,
|
||||||
|
"canvasBackgroundColor" | "padding" | "theme" | "exportingFrame"
|
||||||
|
> & {
|
||||||
|
/**
|
||||||
|
* if true, all embeddables passed in will be rendered when possible.
|
||||||
|
*/
|
||||||
|
renderEmbeddables?: boolean;
|
||||||
|
skipInliningFonts?: true;
|
||||||
|
reuseImages?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const exportToSvg = async ({
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
}: {
|
||||||
|
data: {
|
||||||
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
appState: {
|
appState: {
|
||||||
exportBackground: boolean;
|
exportBackground: boolean;
|
||||||
exportPadding?: number;
|
|
||||||
exportScale?: number;
|
exportScale?: number;
|
||||||
viewBackgroundColor: string;
|
viewBackgroundColor: string;
|
||||||
exportWithDarkMode?: boolean;
|
exportWithDarkMode?: boolean;
|
||||||
exportEmbedScene?: boolean;
|
exportEmbedScene?: boolean;
|
||||||
frameRendering?: AppState["frameRendering"];
|
frameRendering?: AppState["frameRendering"];
|
||||||
},
|
gridModeEnabled?: boolean;
|
||||||
files: BinaryFiles | null,
|
};
|
||||||
opts?: {
|
files: BinaryFiles | null;
|
||||||
/**
|
};
|
||||||
* if true, all embeddables passed in will be rendered when possible.
|
config?: ExportToSvgConfig;
|
||||||
*/
|
}): Promise<SVGSVGElement> => {
|
||||||
renderEmbeddables?: boolean;
|
// clone
|
||||||
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
const cfg = Object.assign({}, config);
|
||||||
skipInliningFonts?: true;
|
|
||||||
reuseImages?: boolean;
|
cfg.exportingFrame = cfg.exportingFrame ?? null;
|
||||||
},
|
|
||||||
): Promise<SVGSVGElement> => {
|
const { elements: restoredElements } = restore(
|
||||||
|
{ ...data, files: data.files || {} },
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const elements = getNonDeletedElements(restoredElements);
|
||||||
|
|
||||||
const frameRendering = getFrameRenderingConfig(
|
const frameRendering = getFrameRenderingConfig(
|
||||||
opts?.exportingFrame ?? null,
|
cfg?.exportingFrame ?? null,
|
||||||
appState.frameRendering ?? null,
|
data.appState.frameRendering ?? null,
|
||||||
);
|
);
|
||||||
|
|
||||||
let {
|
let {
|
||||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
|
||||||
exportWithDarkMode = false,
|
exportWithDarkMode = false,
|
||||||
viewBackgroundColor,
|
viewBackgroundColor,
|
||||||
exportScale = 1,
|
exportScale = 1,
|
||||||
exportEmbedScene,
|
exportEmbedScene,
|
||||||
} = appState;
|
} = data.appState;
|
||||||
|
|
||||||
const { exportingFrame = null } = opts || {};
|
let padding = cfg.padding ?? 0;
|
||||||
|
|
||||||
const elementsForRender = prepareElementsForRender({
|
const elementsForRender = prepareElementsForRender({
|
||||||
elements,
|
elements,
|
||||||
exportingFrame,
|
exportingFrame: cfg.exportingFrame,
|
||||||
exportWithDarkMode,
|
exportWithDarkMode,
|
||||||
frameRendering,
|
frameRendering,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (exportingFrame) {
|
if (cfg.exportingFrame) {
|
||||||
exportPadding = 0;
|
padding = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
let metadata = "";
|
let metadata = "";
|
||||||
@ -313,18 +722,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 += padding * 2;
|
||||||
|
height += padding * 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");
|
||||||
@ -336,8 +754,8 @@ export const exportToSvg = async (
|
|||||||
svgRoot.setAttribute("filter", THEME_FILTER);
|
svgRoot.setAttribute("filter", THEME_FILTER);
|
||||||
}
|
}
|
||||||
|
|
||||||
const offsetX = -minX + exportPadding;
|
const offsetX = -minX + padding;
|
||||||
const offsetY = -minY + exportPadding;
|
const offsetY = -minY + padding;
|
||||||
|
|
||||||
const frameElements = getFrameLikeElements(elements);
|
const frameElements = getFrameLikeElements(elements);
|
||||||
|
|
||||||
@ -355,7 +773,7 @@ export const exportToSvg = async (
|
|||||||
width="${frame.width}"
|
width="${frame.width}"
|
||||||
height="${frame.height}"
|
height="${frame.height}"
|
||||||
${
|
${
|
||||||
exportingFrame
|
cfg.exportingFrame
|
||||||
? ""
|
? ""
|
||||||
: `rx=${FRAME_STYLE.radius} ry=${FRAME_STYLE.radius}`
|
: `rx=${FRAME_STYLE.radius} ry=${FRAME_STYLE.radius}`
|
||||||
}
|
}
|
||||||
@ -364,7 +782,7 @@ export const exportToSvg = async (
|
|||||||
</clipPath>`;
|
</clipPath>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const fontFaces = !opts?.skipInliningFonts
|
const fontFaces = !cfg?.skipInliningFonts
|
||||||
? await Fonts.generateFontFaceDeclarations(elements)
|
? await Fonts.generateFontFaceDeclarations(elements)
|
||||||
: [];
|
: [];
|
||||||
|
|
||||||
@ -381,7 +799,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");
|
||||||
@ -393,14 +811,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,
|
||||||
@ -416,7 +834,7 @@ export const exportToSvg = async (
|
|||||||
.map((element) => [element.id, true]),
|
.map((element) => [element.id, true]),
|
||||||
)
|
)
|
||||||
: new Map(),
|
: new Map(),
|
||||||
reuseImages: opts?.reuseImages ?? true,
|
reuseImages: cfg?.reuseImages ?? true,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -424,25 +842,112 @@ 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 = (
|
export { MIME_TYPES };
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
|
||||||
exportPadding: number,
|
|
||||||
scale: number,
|
|
||||||
): [number, number] => {
|
|
||||||
const [, , width, height] = getCanvasSize(elements, exportPadding).map(
|
|
||||||
(dimension) => Math.trunc(dimension * scale),
|
|
||||||
);
|
|
||||||
|
|
||||||
return [width, height];
|
type ExportToBlobConfig = ExportToCanvasConfig & {
|
||||||
|
mimeType?: string;
|
||||||
|
quality?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
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") {
|
||||||
|
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// typo in MIME type (should be "jpeg")
|
||||||
|
if (mimeType === "image/jpg") {
|
||||||
|
mimeType = MIME_TYPES.jpg;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mimeType === MIME_TYPES.jpg && !config?.canvasBackgroundColor === false) {
|
||||||
|
console.warn(
|
||||||
|
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
|
||||||
|
);
|
||||||
|
config = {
|
||||||
|
...config,
|
||||||
|
canvasBackgroundColor: data.appState?.viewBackgroundColor || COLOR_WHITE,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvas = await exportToCanvas({ data, config });
|
||||||
|
|
||||||
|
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
canvas.toBlob(
|
||||||
|
async (blob) => {
|
||||||
|
if (!blob) {
|
||||||
|
return reject(new Error("couldn't export to blob"));
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
blob &&
|
||||||
|
mimeType === MIME_TYPES.png &&
|
||||||
|
data.appState?.exportEmbedScene
|
||||||
|
) {
|
||||||
|
blob = await encodePngMetadata({
|
||||||
|
blob,
|
||||||
|
metadata: serializeAsJSON(
|
||||||
|
// NOTE as long as we're using the Scene hack, we need to ensure
|
||||||
|
// we pass the original, uncloned elements when serializing
|
||||||
|
// so that we keep ids stable
|
||||||
|
data.elements,
|
||||||
|
data.appState,
|
||||||
|
data.files || {},
|
||||||
|
"local",
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
resolve(blob);
|
||||||
|
},
|
||||||
|
mimeType,
|
||||||
|
quality,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
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: {
|
||||||
|
...data,
|
||||||
|
appState: restoreAppState(data.appState, null),
|
||||||
|
},
|
||||||
|
config,
|
||||||
|
});
|
||||||
|
await copyTextToSystemClipboard(svg.outerHTML);
|
||||||
|
} else if (type === "png") {
|
||||||
|
await copyBlobToClipboardAsPng(exportToBlob({ data, config }));
|
||||||
|
} else if (type === "json") {
|
||||||
|
await copyToClipboard(data.elements, data.files);
|
||||||
|
} else {
|
||||||
|
throw new Error("Invalid export type");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
@ -24,7 +24,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"];
|
||||||
@ -32,6 +31,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;
|
||||||
pendingFlowchartNodes: PendingExcalidrawElements | null;
|
pendingFlowchartNodes: PendingExcalidrawElements | null;
|
||||||
@ -81,6 +82,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;
|
||||||
|
@ -6,7 +6,7 @@ exports[`Test <MermaidToExcalidraw/> > should open mermaid popup when active too
|
|||||||
B --> C{Let me think}
|
B --> C{Let me think}
|
||||||
C -->|One| D[Laptop]
|
C -->|One| D[Laptop]
|
||||||
C -->|Two| E[iPhone]
|
C -->|Two| E[iPhone]
|
||||||
C -->|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 -->|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>"
|
||||||
`;
|
`;
|
||||||
|
|
||||||
exports[`Test <MermaidToExcalidraw/> > should show error in preview when mermaid library throws error 1`] = `
|
exports[`Test <MermaidToExcalidraw/> > should show error in preview when mermaid library throws error 1`] = `
|
||||||
|
File diff suppressed because one or more lines are too long
@ -315,20 +315,28 @@ describe("Cropping and other features", async () => {
|
|||||||
const widthToHeightRatio = image.width / image.height;
|
const widthToHeightRatio = image.width / image.height;
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
|
data: {
|
||||||
elements: [image],
|
elements: [image],
|
||||||
appState: h.state,
|
appState: h.state,
|
||||||
files: h.app.files,
|
files: h.app.files,
|
||||||
exportPadding: 0,
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const exportedCanvasRatio = canvas.width / canvas.height;
|
const exportedCanvasRatio = canvas.width / canvas.height;
|
||||||
|
|
||||||
expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);
|
expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
|
data: {
|
||||||
elements: [image],
|
elements: [image],
|
||||||
appState: h.state,
|
appState: h.state,
|
||||||
files: h.app.files,
|
files: h.app.files,
|
||||||
exportPadding: 0,
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
const svgWidth = svg.getAttribute("width");
|
const svgWidth = svg.getAttribute("width");
|
||||||
const svgHeight = svg.getAttribute("height");
|
const svgHeight = svg.getAttribute("height");
|
||||||
|
@ -163,7 +163,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;
|
||||||
|
|
||||||
|
@ -15,7 +15,11 @@ import { getDefaultAppState } from "../appState";
|
|||||||
import { fireEvent, queryByTestId, waitFor } from "@testing-library/react";
|
import { fireEvent, queryByTestId, waitFor } from "@testing-library/react";
|
||||||
import { createUndoAction, createRedoAction } from "../actions/actionHistory";
|
import { createUndoAction, createRedoAction } from "../actions/actionHistory";
|
||||||
import { actionToggleViewMode } from "../actions/actionToggleViewMode";
|
import { actionToggleViewMode } from "../actions/actionToggleViewMode";
|
||||||
import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants";
|
import {
|
||||||
|
COLOR_CHARCOAL_BLACK,
|
||||||
|
EXPORT_DATA_TYPES,
|
||||||
|
MIME_TYPES,
|
||||||
|
} from "../constants";
|
||||||
import type { AppState } from "../types";
|
import type { AppState } from "../types";
|
||||||
import { arrayToMap } from "../utils";
|
import { arrayToMap } from "../utils";
|
||||||
import {
|
import {
|
||||||
@ -77,7 +81,7 @@ const checkpoint = (name: string) => {
|
|||||||
const renderStaticScene = vi.spyOn(StaticScene, "renderStaticScene");
|
const renderStaticScene = vi.spyOn(StaticScene, "renderStaticScene");
|
||||||
|
|
||||||
const transparent = COLOR_PALETTE.transparent;
|
const transparent = COLOR_PALETTE.transparent;
|
||||||
const black = COLOR_PALETTE.black;
|
const black = COLOR_CHARCOAL_BLACK;
|
||||||
const red = COLOR_PALETTE.red[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
const red = COLOR_PALETTE.red[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
||||||
const blue = COLOR_PALETTE.blue[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
const blue = COLOR_PALETTE.blue[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
||||||
const yellow = COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
const yellow = COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX];
|
||||||
|
@ -24,7 +24,7 @@ exports[`<Excalidraw/> > <MainMenu/> > should render main menu with host menu it
|
|||||||
</button>
|
</button>
|
||||||
<a
|
<a
|
||||||
class="dropdown-menu-item dropdown-menu-item-base"
|
class="dropdown-menu-item dropdown-menu-item-base"
|
||||||
href="blog.excalidaw.com"
|
href="https://plus.excalidraw.com/blog"
|
||||||
rel="noreferrer"
|
rel="noreferrer"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
>
|
>
|
||||||
|
File diff suppressed because one or more lines are too long
@ -11,9 +11,15 @@ import {
|
|||||||
textFixture,
|
textFixture,
|
||||||
} from "../fixtures/elementFixture";
|
} from "../fixtures/elementFixture";
|
||||||
import { API } from "../helpers/api";
|
import { API } from "../helpers/api";
|
||||||
import { exportToCanvas, exportToSvg } from "../../../utils";
|
|
||||||
import { FONT_FAMILY, FRAME_STYLE } from "../../constants";
|
import { FONT_FAMILY, FRAME_STYLE } from "../../constants";
|
||||||
import { prepareElementsForExport } from "../../data";
|
import { prepareElementsForExport } from "../../data";
|
||||||
|
import { diagramFactory } from "../fixtures/diagramFixture";
|
||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
|
const DEFAULT_OPTIONS = {
|
||||||
|
exportBackground: false,
|
||||||
|
viewBackgroundColor: "#ffffff",
|
||||||
|
};
|
||||||
|
|
||||||
describe("exportToSvg", () => {
|
describe("exportToSvg", () => {
|
||||||
const ELEMENT_HEIGHT = 100;
|
const ELEMENT_HEIGHT = 100;
|
||||||
@ -46,25 +52,18 @@ describe("exportToSvg", () => {
|
|||||||
},
|
},
|
||||||
] as NonDeletedExcalidrawElement[];
|
] as NonDeletedExcalidrawElement[];
|
||||||
|
|
||||||
const DEFAULT_OPTIONS = {
|
|
||||||
exportBackground: false,
|
|
||||||
viewBackgroundColor: "#ffffff",
|
|
||||||
files: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: { elements: ELEMENTS, appState: DEFAULT_OPTIONS, files: null },
|
||||||
DEFAULT_OPTIONS,
|
});
|
||||||
null,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(svgElement).toMatchSnapshot();
|
expect(svgElement).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with a CJK font", async () => {
|
it("with a CJK font", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
[
|
data: {
|
||||||
|
elements: [
|
||||||
...ELEMENTS,
|
...ELEMENTS,
|
||||||
{
|
{
|
||||||
...textFixture,
|
...textFixture,
|
||||||
@ -76,9 +75,10 @@ describe("exportToSvg", () => {
|
|||||||
index: "a4" as FractionalIndex,
|
index: "a4" as FractionalIndex,
|
||||||
} as ExcalidrawTextElement,
|
} as ExcalidrawTextElement,
|
||||||
],
|
],
|
||||||
DEFAULT_OPTIONS,
|
files: null,
|
||||||
null,
|
appState: DEFAULT_OPTIONS,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toMatchSnapshot();
|
expect(svgElement).toMatchSnapshot();
|
||||||
// extend the timeout, as it needs to first load the fonts from disk and then perform whole woff2 decode, subset and encode (without workers)
|
// extend the timeout, as it needs to first load the fonts from disk and then perform whole woff2 decode, subset and encode (without workers)
|
||||||
@ -87,15 +87,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,
|
||||||
|
appState: {
|
||||||
...DEFAULT_OPTIONS,
|
...DEFAULT_OPTIONS,
|
||||||
exportBackground: true,
|
exportBackground: true,
|
||||||
viewBackgroundColor: BACKGROUND_COLOR,
|
viewBackgroundColor: BACKGROUND_COLOR,
|
||||||
},
|
},
|
||||||
null,
|
files: null,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement.querySelector("rect")).toHaveAttribute(
|
expect(svgElement.querySelector("rect")).toHaveAttribute(
|
||||||
"fill",
|
"fill",
|
||||||
@ -104,14 +106,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,
|
||||||
|
appState: {
|
||||||
...DEFAULT_OPTIONS,
|
...DEFAULT_OPTIONS,
|
||||||
exportWithDarkMode: true,
|
exportWithDarkMode: true,
|
||||||
},
|
},
|
||||||
null,
|
files: null,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement.getAttribute("filter")).toMatchInlineSnapshot(
|
expect(svgElement.getAttribute("filter")).toMatchInlineSnapshot(
|
||||||
`"_themeFilter_1883f3"`,
|
`"_themeFilter_1883f3"`,
|
||||||
@ -119,14 +123,15 @@ describe("exportToSvg", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("with exportPadding", async () => {
|
it("with exportPadding", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
ELEMENTS,
|
data: {
|
||||||
{
|
elements: ELEMENTS,
|
||||||
|
appState: {
|
||||||
...DEFAULT_OPTIONS,
|
...DEFAULT_OPTIONS,
|
||||||
exportPadding: 0,
|
|
||||||
},
|
},
|
||||||
null,
|
files: 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());
|
||||||
@ -139,15 +144,16 @@ 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,
|
||||||
|
appState: {
|
||||||
...DEFAULT_OPTIONS,
|
...DEFAULT_OPTIONS,
|
||||||
exportPadding: 0,
|
|
||||||
exportScale: SCALE,
|
exportScale: SCALE,
|
||||||
},
|
},
|
||||||
null,
|
files: null,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
|
|
||||||
expect(svgElement).toHaveAttribute(
|
expect(svgElement).toHaveAttribute(
|
||||||
"height",
|
"height",
|
||||||
@ -160,23 +166,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,
|
||||||
|
appState: {
|
||||||
...DEFAULT_OPTIONS,
|
...DEFAULT_OPTIONS,
|
||||||
exportEmbedScene: true,
|
exportEmbedScene: true,
|
||||||
},
|
},
|
||||||
null,
|
files: null,
|
||||||
);
|
},
|
||||||
|
});
|
||||||
expect(svgElement.innerHTML).toMatchSnapshot();
|
expect(svgElement.innerHTML).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("with elements that have a link", async () => {
|
it("with elements that have a link", async () => {
|
||||||
const svgElement = await exportUtils.exportToSvg(
|
const svgElement = await exportUtils.exportToSvg({
|
||||||
[rectangleWithLinkFixture],
|
data: {
|
||||||
DEFAULT_OPTIONS,
|
elements: [rectangleWithLinkFixture],
|
||||||
null,
|
files: null,
|
||||||
);
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
});
|
||||||
expect(svgElement.innerHTML).toMatchSnapshot();
|
expect(svgElement.innerHTML).toMatchSnapshot();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@ -215,10 +225,14 @@ describe("exporting frames", () => {
|
|||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportUtils.exportToCanvas({
|
||||||
|
data: {
|
||||||
elements,
|
elements,
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toEqual(200);
|
expect(canvas.width).toEqual(200);
|
||||||
@ -244,11 +258,15 @@ describe("exporting frames", () => {
|
|||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
|
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportUtils.exportToCanvas({
|
||||||
|
data: {
|
||||||
elements,
|
elements,
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame: frame,
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toEqual(frame.width);
|
expect(canvas.width).toEqual(frame.width);
|
||||||
@ -283,11 +301,16 @@ describe("exporting frames", () => {
|
|||||||
y: 0,
|
y: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportUtils.exportToSvg({
|
||||||
|
data: {
|
||||||
elements: [rectOverlapping, frame, frameChild],
|
elements: [rectOverlapping, frame, frameChild],
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame: frame,
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@ -327,11 +350,16 @@ describe("exporting frames", () => {
|
|||||||
y: 0,
|
y: 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportUtils.exportToSvg({
|
||||||
|
data: {
|
||||||
elements: [frameChild, frame, elementOutside],
|
elements: [frameChild, frame, elementOutside],
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame: frame,
|
exportingFrame: frame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@ -395,11 +423,16 @@ describe("exporting frames", () => {
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportUtils.exportToSvg({
|
||||||
|
data: {
|
||||||
elements: exportedElements,
|
elements: exportedElements,
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frames themselves should be exported when multiple frames selected
|
// frames themselves should be exported when multiple frames selected
|
||||||
@ -440,11 +473,16 @@ describe("exporting frames", () => {
|
|||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportUtils.exportToSvg({
|
||||||
|
data: {
|
||||||
elements: exportedElements,
|
elements: exportedElements,
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame itself isn't exported
|
// frame itself isn't exported
|
||||||
@ -499,11 +537,16 @@ describe("exporting frames", () => {
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
const svg = await exportToSvg({
|
const svg = await exportUtils.exportToSvg({
|
||||||
|
data: {
|
||||||
elements: exportedElements,
|
elements: exportedElements,
|
||||||
files: null,
|
files: null,
|
||||||
exportPadding: 0,
|
appState: DEFAULT_OPTIONS,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
padding: 0,
|
||||||
exportingFrame,
|
exportingFrame,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// frame shouldn't be exported
|
// frame shouldn't be exported
|
||||||
@ -519,3 +562,47 @@ describe("exporting frames", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("exportToBlob", async () => {
|
||||||
|
describe("mime type", () => {
|
||||||
|
it("should change image/jpg to image/jpeg", async () => {
|
||||||
|
const blob = await exportUtils.exportToBlob({
|
||||||
|
data: {
|
||||||
|
...diagramFactory(),
|
||||||
|
|
||||||
|
appState: {
|
||||||
|
exportBackground: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
||||||
|
// testing typo in MIME type (jpg → jpeg)
|
||||||
|
mimeType: "image/jpg",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(blob?.type).toBe(exportUtils.MIME_TYPES.jpg);
|
||||||
|
});
|
||||||
|
it("should default to image/png", async () => {
|
||||||
|
const blob = await exportUtils.exportToBlob({
|
||||||
|
data: diagramFactory(),
|
||||||
|
});
|
||||||
|
expect(blob?.type).toBe(exportUtils.MIME_TYPES.png);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should warn when using quality with image/png", async () => {
|
||||||
|
const consoleSpy = vi
|
||||||
|
.spyOn(console, "warn")
|
||||||
|
.mockImplementationOnce(() => void 0);
|
||||||
|
await exportUtils.exportToBlob({
|
||||||
|
data: diagramFactory(),
|
||||||
|
config: {
|
||||||
|
mimeType: exportUtils.MIME_TYPES.png,
|
||||||
|
quality: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
|
`"quality" will be ignored for "${exportUtils.MIME_TYPES.png}" mimeType`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
@ -173,8 +173,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"];
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import Pool from "es6-promise-pool";
|
import Pool from "es6-promise-pool";
|
||||||
import { average } from "../math";
|
import { average } from "../math";
|
||||||
import { COLOR_PALETTE } from "./colors";
|
|
||||||
import type { EVENT } from "./constants";
|
import type { EVENT } from "./constants";
|
||||||
import {
|
import {
|
||||||
|
COLOR_TRANSPARENT,
|
||||||
DEFAULT_VERSION,
|
DEFAULT_VERSION,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
getFontFamilyFallbacks,
|
getFontFamilyFallbacks,
|
||||||
@ -536,11 +536,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> & {
|
||||||
@ -1225,3 +1221,18 @@ export class PromisePool<T> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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]>;
|
||||||
|
};
|
||||||
|
@ -1,132 +0,0 @@
|
|||||||
import * as utils from ".";
|
|
||||||
import { diagramFactory } from "../excalidraw/tests/fixtures/diagramFixture";
|
|
||||||
import { vi } from "vitest";
|
|
||||||
import * as mockedSceneExportUtils from "../excalidraw/scene/export";
|
|
||||||
|
|
||||||
import { MIME_TYPES } from "../excalidraw/constants";
|
|
||||||
|
|
||||||
const exportToSvgSpy = vi.spyOn(mockedSceneExportUtils, "exportToSvg");
|
|
||||||
|
|
||||||
describe("exportToCanvas", async () => {
|
|
||||||
const EXPORT_PADDING = 10;
|
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
|
||||||
const canvas = await utils.exportToCanvas({
|
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
|
||||||
expect(canvas.height).toBe(100 + 2 * EXPORT_PADDING);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("when custom width and height", async () => {
|
|
||||||
const canvas = await utils.exportToCanvas({
|
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
|
||||||
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(canvas.width).toBe(200);
|
|
||||||
expect(canvas.height).toBe(200);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("exportToBlob", async () => {
|
|
||||||
describe("mime type", () => {
|
|
||||||
it("should change image/jpg to image/jpeg", async () => {
|
|
||||||
const blob = await utils.exportToBlob({
|
|
||||||
...diagramFactory(),
|
|
||||||
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
|
||||||
// testing typo in MIME type (jpg → jpeg)
|
|
||||||
mimeType: "image/jpg",
|
|
||||||
appState: {
|
|
||||||
exportBackground: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
|
||||||
});
|
|
||||||
it("should default to image/png", async () => {
|
|
||||||
const blob = await utils.exportToBlob({
|
|
||||||
...diagramFactory(),
|
|
||||||
});
|
|
||||||
expect(blob?.type).toBe(MIME_TYPES.png);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should warn when using quality with image/png", async () => {
|
|
||||||
const consoleSpy = vi
|
|
||||||
.spyOn(console, "warn")
|
|
||||||
.mockImplementationOnce(() => void 0);
|
|
||||||
await utils.exportToBlob({
|
|
||||||
...diagramFactory(),
|
|
||||||
mimeType: MIME_TYPES.png,
|
|
||||||
quality: 1,
|
|
||||||
});
|
|
||||||
expect(consoleSpy).toHaveBeenCalledWith(
|
|
||||||
`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("exportToSvg", () => {
|
|
||||||
const passedElements = () => exportToSvgSpy.mock.calls[0][0];
|
|
||||||
const passedOptions = () => exportToSvgSpy.mock.calls[0][1];
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
|
||||||
await utils.exportToSvg({
|
|
||||||
...diagramFactory({
|
|
||||||
overrides: { appState: void 0 },
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const passedOptionsWhenDefault = {
|
|
||||||
...passedOptions(),
|
|
||||||
// To avoid varying snapshots
|
|
||||||
name: "name",
|
|
||||||
};
|
|
||||||
expect(passedElements().length).toBe(3);
|
|
||||||
expect(passedOptionsWhenDefault).toMatchSnapshot();
|
|
||||||
});
|
|
||||||
|
|
||||||
// FIXME the utils.exportToSvg no longer filters out deleted elements.
|
|
||||||
// It's already supposed to be passed non-deleted elements by we're not
|
|
||||||
// type-checking for it correctly.
|
|
||||||
it.skip("with deleted elements", async () => {
|
|
||||||
await utils.exportToSvg({
|
|
||||||
...diagramFactory({
|
|
||||||
overrides: { appState: void 0 },
|
|
||||||
elementOverrides: { isDeleted: true },
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(passedElements().length).toBe(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("with exportPadding", async () => {
|
|
||||||
await utils.exportToSvg({
|
|
||||||
...diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
|
|
||||||
exportPadding: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(passedElements().length).toBe(3);
|
|
||||||
expect(passedOptions()).toEqual(
|
|
||||||
expect.objectContaining({ exportPadding: 0 }),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("with exportEmbedScene", async () => {
|
|
||||||
await utils.exportToSvg({
|
|
||||||
...diagramFactory({
|
|
||||||
overrides: {
|
|
||||||
appState: { name: "diagram name", exportEmbedScene: true },
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(passedElements().length).toBe(3);
|
|
||||||
expect(passedOptions().exportEmbedScene).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
@ -1,213 +0,0 @@
|
|||||||
import {
|
|
||||||
exportToCanvas as _exportToCanvas,
|
|
||||||
exportToSvg as _exportToSvg,
|
|
||||||
} from "../excalidraw/scene/export";
|
|
||||||
import { getDefaultAppState } from "../excalidraw/appState";
|
|
||||||
import type { AppState, BinaryFiles } from "../excalidraw/types";
|
|
||||||
import type {
|
|
||||||
ExcalidrawElement,
|
|
||||||
ExcalidrawFrameLikeElement,
|
|
||||||
NonDeleted,
|
|
||||||
} from "../excalidraw/element/types";
|
|
||||||
import { restore } from "../excalidraw/data/restore";
|
|
||||||
import { MIME_TYPES } from "../excalidraw/constants";
|
|
||||||
import { encodePngMetadata } from "../excalidraw/data/image";
|
|
||||||
import { serializeAsJSON } from "../excalidraw/data/json";
|
|
||||||
import {
|
|
||||||
copyBlobToClipboardAsPng,
|
|
||||||
copyTextToSystemClipboard,
|
|
||||||
copyToClipboard,
|
|
||||||
} from "../excalidraw/clipboard";
|
|
||||||
|
|
||||||
export { MIME_TYPES };
|
|
||||||
|
|
||||||
type ExportOpts = {
|
|
||||||
elements: readonly NonDeleted<ExcalidrawElement>[];
|
|
||||||
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
|
|
||||||
files: BinaryFiles | null;
|
|
||||||
maxWidthOrHeight?: number;
|
|
||||||
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
|
||||||
getDimensions?: (
|
|
||||||
width: number,
|
|
||||||
height: number,
|
|
||||||
) => { width: number; height: number; scale?: number };
|
|
||||||
};
|
|
||||||
|
|
||||||
export const exportToCanvas = ({
|
|
||||||
elements,
|
|
||||||
appState,
|
|
||||||
files,
|
|
||||||
maxWidthOrHeight,
|
|
||||||
getDimensions,
|
|
||||||
exportPadding,
|
|
||||||
exportingFrame,
|
|
||||||
}: ExportOpts & {
|
|
||||||
exportPadding?: number;
|
|
||||||
}) => {
|
|
||||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
|
||||||
{ elements, appState },
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const { exportBackground, viewBackgroundColor } = restoredAppState;
|
|
||||||
return _exportToCanvas(
|
|
||||||
restoredElements,
|
|
||||||
{ ...restoredAppState, offsetTop: 0, offsetLeft: 0, width: 0, height: 0 },
|
|
||||||
files || {},
|
|
||||||
{ exportBackground, exportPadding, viewBackgroundColor, exportingFrame },
|
|
||||||
(width: number, height: number) => {
|
|
||||||
const canvas = document.createElement("canvas");
|
|
||||||
|
|
||||||
if (maxWidthOrHeight) {
|
|
||||||
if (typeof getDimensions === "function") {
|
|
||||||
console.warn(
|
|
||||||
"`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const max = Math.max(width, height);
|
|
||||||
|
|
||||||
// if content is less then maxWidthOrHeight, fallback on supplied scale
|
|
||||||
const scale =
|
|
||||||
maxWidthOrHeight < max
|
|
||||||
? maxWidthOrHeight / max
|
|
||||||
: appState?.exportScale ?? 1;
|
|
||||||
|
|
||||||
canvas.width = width * scale;
|
|
||||||
canvas.height = height * scale;
|
|
||||||
|
|
||||||
return {
|
|
||||||
canvas,
|
|
||||||
scale,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const ret = getDimensions?.(width, height) || { width, height };
|
|
||||||
|
|
||||||
canvas.width = ret.width;
|
|
||||||
canvas.height = ret.height;
|
|
||||||
|
|
||||||
return {
|
|
||||||
canvas,
|
|
||||||
scale: ret.scale ?? 1,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const exportToBlob = async (
|
|
||||||
opts: ExportOpts & {
|
|
||||||
mimeType?: string;
|
|
||||||
quality?: number;
|
|
||||||
exportPadding?: number;
|
|
||||||
},
|
|
||||||
): Promise<Blob> => {
|
|
||||||
let { mimeType = MIME_TYPES.png, quality } = opts;
|
|
||||||
|
|
||||||
if (mimeType === MIME_TYPES.png && typeof quality === "number") {
|
|
||||||
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// typo in MIME type (should be "jpeg")
|
|
||||||
if (mimeType === "image/jpg") {
|
|
||||||
mimeType = MIME_TYPES.jpg;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mimeType === MIME_TYPES.jpg && !opts.appState?.exportBackground) {
|
|
||||||
console.warn(
|
|
||||||
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
|
|
||||||
);
|
|
||||||
opts = {
|
|
||||||
...opts,
|
|
||||||
appState: { ...opts.appState, exportBackground: true },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const canvas = await exportToCanvas(opts);
|
|
||||||
|
|
||||||
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
canvas.toBlob(
|
|
||||||
async (blob) => {
|
|
||||||
if (!blob) {
|
|
||||||
return reject(new Error("couldn't export to blob"));
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
blob &&
|
|
||||||
mimeType === MIME_TYPES.png &&
|
|
||||||
opts.appState?.exportEmbedScene
|
|
||||||
) {
|
|
||||||
blob = await encodePngMetadata({
|
|
||||||
blob,
|
|
||||||
metadata: serializeAsJSON(
|
|
||||||
// NOTE as long as we're using the Scene hack, we need to ensure
|
|
||||||
// we pass the original, uncloned elements when serializing
|
|
||||||
// so that we keep ids stable
|
|
||||||
opts.elements,
|
|
||||||
opts.appState,
|
|
||||||
opts.files || {},
|
|
||||||
"local",
|
|
||||||
),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
resolve(blob);
|
|
||||||
},
|
|
||||||
mimeType,
|
|
||||||
quality,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const exportToSvg = async ({
|
|
||||||
elements,
|
|
||||||
appState = getDefaultAppState(),
|
|
||||||
files = {},
|
|
||||||
exportPadding,
|
|
||||||
renderEmbeddables,
|
|
||||||
exportingFrame,
|
|
||||||
skipInliningFonts,
|
|
||||||
reuseImages,
|
|
||||||
}: Omit<ExportOpts, "getDimensions"> & {
|
|
||||||
exportPadding?: number;
|
|
||||||
renderEmbeddables?: boolean;
|
|
||||||
skipInliningFonts?: true;
|
|
||||||
reuseImages?: boolean;
|
|
||||||
}): Promise<SVGSVGElement> => {
|
|
||||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
|
||||||
{ elements, appState },
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
|
|
||||||
const exportAppState = {
|
|
||||||
...restoredAppState,
|
|
||||||
exportPadding,
|
|
||||||
};
|
|
||||||
|
|
||||||
return _exportToSvg(restoredElements, exportAppState, files, {
|
|
||||||
exportingFrame,
|
|
||||||
renderEmbeddables,
|
|
||||||
skipInliningFonts,
|
|
||||||
reuseImages,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
export const exportToClipboard = async (
|
|
||||||
opts: ExportOpts & {
|
|
||||||
mimeType?: string;
|
|
||||||
quality?: number;
|
|
||||||
type: "png" | "svg" | "json";
|
|
||||||
},
|
|
||||||
) => {
|
|
||||||
if (opts.type === "svg") {
|
|
||||||
const svg = await exportToSvg(opts);
|
|
||||||
await copyTextToSystemClipboard(svg.outerHTML);
|
|
||||||
} else if (opts.type === "png") {
|
|
||||||
await copyBlobToClipboardAsPng(exportToBlob(opts));
|
|
||||||
} else if (opts.type === "json") {
|
|
||||||
await copyToClipboard(opts.elements, opts.files);
|
|
||||||
} else {
|
|
||||||
throw new Error("Invalid export type");
|
|
||||||
}
|
|
||||||
};
|
|
@ -1,4 +1,3 @@
|
|||||||
export * from "./export";
|
|
||||||
export * from "./withinBounds";
|
export * from "./withinBounds";
|
||||||
export * from "./bbox";
|
export * from "./bbox";
|
||||||
export { getCommonBounds } from "../excalidraw/element/bounds";
|
export { getCommonBounds } from "../excalidraw/element/bounds";
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { decodePngMetadata, decodeSvgMetadata } from "../excalidraw/data/image";
|
import { decodePngMetadata, decodeSvgMetadata } from "../excalidraw/data/image";
|
||||||
import type { ImportedDataState } from "../excalidraw/data/types";
|
import type { ImportedDataState } from "../excalidraw/data/types";
|
||||||
import * as utils from "../utils";
|
import { exportToBlob, exportToSvg } from "../excalidraw/scene/export";
|
||||||
import { API } from "../excalidraw/tests/helpers/api";
|
import { API } from "../excalidraw/tests/helpers/api";
|
||||||
|
|
||||||
// NOTE this test file is using the actual API, unmocked. Hence splitting it
|
// NOTE this test file is using the actual API, unmocked. Hence splitting it
|
||||||
@ -15,14 +15,17 @@ describe("embedding scene data", () => {
|
|||||||
|
|
||||||
const sourceElements = [rectangle, ellipse];
|
const sourceElements = [rectangle, ellipse];
|
||||||
|
|
||||||
const svgNode = await utils.exportToSvg({
|
const svgNode = await exportToSvg({
|
||||||
|
data: {
|
||||||
elements: sourceElements,
|
elements: sourceElements,
|
||||||
appState: {
|
appState: {
|
||||||
viewBackgroundColor: "#ffffff",
|
viewBackgroundColor: "#ffffff",
|
||||||
gridModeEnabled: false,
|
gridModeEnabled: false,
|
||||||
exportEmbedScene: true,
|
exportEmbedScene: true,
|
||||||
|
exportBackground: true,
|
||||||
},
|
},
|
||||||
files: null,
|
files: null,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const svg = svgNode.outerHTML;
|
const svg = svgNode.outerHTML;
|
||||||
@ -45,8 +48,8 @@ describe("embedding scene data", () => {
|
|||||||
|
|
||||||
const sourceElements = [rectangle, ellipse];
|
const sourceElements = [rectangle, ellipse];
|
||||||
|
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await exportToBlob({
|
||||||
mimeType: "image/png",
|
data: {
|
||||||
elements: sourceElements,
|
elements: sourceElements,
|
||||||
appState: {
|
appState: {
|
||||||
viewBackgroundColor: "#ffffff",
|
viewBackgroundColor: "#ffffff",
|
||||||
@ -54,6 +57,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);
|
||||||
|
50
yarn.lock
50
yarn.lock
@ -3887,11 +3887,6 @@ ansi-regex@^5.0.1:
|
|||||||
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
|
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304"
|
||||||
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
|
integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==
|
||||||
|
|
||||||
ansi-regex@^6.0.1:
|
|
||||||
version "6.1.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.1.0.tgz#95ec409c69619d6cb1b8b34f14b660ef28ebd654"
|
|
||||||
integrity sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA==
|
|
||||||
|
|
||||||
ansi-styles@^2.2.1:
|
ansi-styles@^2.2.1:
|
||||||
version "2.2.1"
|
version "2.2.1"
|
||||||
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe"
|
resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe"
|
||||||
@ -9638,7 +9633,7 @@ string-natural-compare@^3.0.1:
|
|||||||
resolved "https://registry.yarnpkg.com/string-natural-compare/-/string-natural-compare-3.0.1.tgz#7a42d58474454963759e8e8b7ae63d71c1e7fdf4"
|
resolved "https://registry.yarnpkg.com/string-natural-compare/-/string-natural-compare-3.0.1.tgz#7a42d58474454963759e8e8b7ae63d71c1e7fdf4"
|
||||||
integrity sha512-n3sPwynL1nwKi3WJ6AIsClwBMa0zTi54fn2oLU6ndfTSIO05xaznjSf15PcBZU6FNWbmN5Q6cxT4V5hGvB4taw==
|
integrity sha512-n3sPwynL1nwKi3WJ6AIsClwBMa0zTi54fn2oLU6ndfTSIO05xaznjSf15PcBZU6FNWbmN5Q6cxT4V5hGvB4taw==
|
||||||
|
|
||||||
"string-width-cjs@npm:string-width@^4.2.0":
|
"string-width-cjs@npm:string-width@^4.2.0", string-width@^4.2.3:
|
||||||
version "4.2.3"
|
version "4.2.3"
|
||||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
||||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
||||||
@ -9656,15 +9651,6 @@ string-width@^4.1.0, string-width@^4.2.0:
|
|||||||
is-fullwidth-code-point "^3.0.0"
|
is-fullwidth-code-point "^3.0.0"
|
||||||
strip-ansi "^6.0.0"
|
strip-ansi "^6.0.0"
|
||||||
|
|
||||||
string-width@^4.2.3:
|
|
||||||
version "4.2.3"
|
|
||||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010"
|
|
||||||
integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==
|
|
||||||
dependencies:
|
|
||||||
emoji-regex "^8.0.0"
|
|
||||||
is-fullwidth-code-point "^3.0.0"
|
|
||||||
strip-ansi "^6.0.1"
|
|
||||||
|
|
||||||
string-width@^5.0.0, string-width@^5.0.1, string-width@^5.1.2:
|
string-width@^5.0.0, string-width@^5.0.1, string-width@^5.1.2:
|
||||||
version "5.1.2"
|
version "5.1.2"
|
||||||
resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794"
|
resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794"
|
||||||
@ -9736,34 +9722,13 @@ stringify-object@^3.3.0:
|
|||||||
is-obj "^1.0.1"
|
is-obj "^1.0.1"
|
||||||
is-regexp "^1.0.0"
|
is-regexp "^1.0.0"
|
||||||
|
|
||||||
"strip-ansi-cjs@npm:strip-ansi@^6.0.1":
|
"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@6.0.1, strip-ansi@^3.0.0, strip-ansi@^6.0.0, strip-ansi@^6.0.1, strip-ansi@^7.0.1:
|
||||||
version "6.0.1"
|
version "6.0.1"
|
||||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
||||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
||||||
dependencies:
|
dependencies:
|
||||||
ansi-regex "^5.0.1"
|
ansi-regex "^5.0.1"
|
||||||
|
|
||||||
strip-ansi@^3.0.0:
|
|
||||||
version "3.0.1"
|
|
||||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"
|
|
||||||
integrity sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==
|
|
||||||
dependencies:
|
|
||||||
ansi-regex "^2.0.0"
|
|
||||||
|
|
||||||
strip-ansi@^6.0.0, strip-ansi@^6.0.1:
|
|
||||||
version "6.0.1"
|
|
||||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
|
|
||||||
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
|
|
||||||
dependencies:
|
|
||||||
ansi-regex "^5.0.1"
|
|
||||||
|
|
||||||
strip-ansi@^7.0.1:
|
|
||||||
version "7.1.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.1.0.tgz#d5b6568ca689d8561370b0707685d22434faff45"
|
|
||||||
integrity sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==
|
|
||||||
dependencies:
|
|
||||||
ansi-regex "^6.0.1"
|
|
||||||
|
|
||||||
strip-bom@^3.0.0:
|
strip-bom@^3.0.0:
|
||||||
version "3.0.0"
|
version "3.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
|
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-3.0.0.tgz#2334c18e9c759f7bdd56fdef7e9ae3d588e68ed3"
|
||||||
@ -10994,7 +10959,7 @@ workbox-window@7.1.0, workbox-window@^7.0.0:
|
|||||||
"@types/trusted-types" "^2.0.2"
|
"@types/trusted-types" "^2.0.2"
|
||||||
workbox-core "7.1.0"
|
workbox-core "7.1.0"
|
||||||
|
|
||||||
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0":
|
"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0:
|
||||||
version "7.0.0"
|
version "7.0.0"
|
||||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
||||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
||||||
@ -11012,15 +10977,6 @@ wrap-ansi@^6.2.0:
|
|||||||
string-width "^4.1.0"
|
string-width "^4.1.0"
|
||||||
strip-ansi "^6.0.0"
|
strip-ansi "^6.0.0"
|
||||||
|
|
||||||
wrap-ansi@^7.0.0:
|
|
||||||
version "7.0.0"
|
|
||||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43"
|
|
||||||
integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==
|
|
||||||
dependencies:
|
|
||||||
ansi-styles "^4.0.0"
|
|
||||||
string-width "^4.1.0"
|
|
||||||
strip-ansi "^6.0.0"
|
|
||||||
|
|
||||||
wrap-ansi@^8.1.0:
|
wrap-ansi@^8.1.0:
|
||||||
version "8.1.0"
|
version "8.1.0"
|
||||||
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"
|
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"
|
||||||
|
Loading…
x
Reference in New Issue
Block a user