Compare commits

...
Author SHA1 Message Date
dwelle fa9631617f wip: get exact bounding box from bitmap when exporting w/o padding 2022-11-03 18:34:17 +01:00
dwelle 0314e81396 feat: support toggling export padding 2022-11-03 17:31:41 +01:00
8d5d68e589 feat: stop deleting whole line when no point select in line editor (#5676)
* feat: stop deleting whole line when no point select in line editor

* Comments typo

Co-authored-by: DanielJGeiger <1852529+DanielJGeiger@users.noreply.github.com>
2022-11-02 14:52:32 +01:00
David LuzarandGitHub 6c15d9948b fix: syncing 1-point lines to remote clients (#5677) 2022-11-02 14:39:12 +01:00
David LuzarandGitHub e8fba43cf6 fix: incorrectly selecting linear elements on creation while tool-locked (#5785) 2022-11-02 14:38:58 +01:00
Paul YiandGitHub 2e5c798c71 fix: Corrected typo in toggle theme shortcut (#5813) 2022-11-02 14:32:21 +01:00
David LuzarandGitHub 8c298336fc fix: hide canvas-modifying UI in view mode (#5815)
* fix: hide canvas-modifying UI in view mode

* add class for better targeting

* fix missing `key`

* fix: useOutsideClick not working in view mode
2022-11-01 22:25:12 +01:00
18 changed files with 289 additions and 74 deletions
+16 -7
View File
@@ -72,13 +72,22 @@ export const actionDeleteSelected = register({
if (!element) { if (!element) {
return false; return false;
} }
if ( // case: no point selected → do nothing, as deleting the whole element
// case: no point selected delete whole element // is most likely a mistake, where you wanted to delete a specific point
selectedPointsIndices == null || // but failed to select it (or you thought it's selected, while it was
// case: deleting last remaining point // only in a hover state)
element.points.length < 2 if (selectedPointsIndices == null) {
) { return false;
const nextElements = elements.filter((el) => el.id !== element.id); }
// case: deleting last remaining point
if (element.points.length < 2) {
const nextElements = elements.map((el) => {
if (el.id === element.id) {
return newElementWith(el, { isDeleted: true });
}
return el;
});
const nextAppState = handleGroupEditingState(appState, nextElements); const nextAppState = handleGroupEditingState(appState, nextElements);
return { return {
+22
View File
@@ -89,6 +89,28 @@ export const actionChangeExportScale = register({
}, },
}); });
export const actionChangeExportPadding = register({
name: "changeExportPadding",
trackEvent: { category: "export", action: "togglePadding" },
perform: (_elements, appState, value) => {
return {
appState: {
...appState,
exportPadding: value ? DEFAULT_EXPORT_PADDING : 0,
},
commitToHistory: false,
};
},
PanelComponent: ({ appState, updateData }) => (
<CheckboxItem
checked={!!appState.exportPadding}
onChange={(checked) => updateData(checked)}
>
{"Padding"}
</CheckboxItem>
),
});
export const actionChangeExportBackground = register({ export const actionChangeExportBackground = register({
name: "changeExportBackground", name: "changeExportBackground",
trackEvent: { category: "export", action: "toggleBackground" }, trackEvent: { category: "export", action: "toggleBackground" },
+1 -1
View File
@@ -38,7 +38,7 @@ export type ShortcutName =
| "imageExport"; | "imageExport";
const shortcutMap: Record<ShortcutName, string[]> = { const shortcutMap: Record<ShortcutName, string[]> = {
toggleTheme: [getShortcutKey("Shit+Alt+D")], toggleTheme: [getShortcutKey("Shift+Alt+D")],
saveScene: [getShortcutKey("CtrlOrCmd+S")], saveScene: [getShortcutKey("CtrlOrCmd+S")],
loadScene: [getShortcutKey("CtrlOrCmd+O")], loadScene: [getShortcutKey("CtrlOrCmd+O")],
imageExport: [getShortcutKey("CtrlOrCmd+Shift+E")], imageExport: [getShortcutKey("CtrlOrCmd+Shift+E")],
+1
View File
@@ -68,6 +68,7 @@ export type ActionName =
| "finalize" | "finalize"
| "changeProjectName" | "changeProjectName"
| "changeExportBackground" | "changeExportBackground"
| "changeExportPadding"
| "changeExportEmbedScene" | "changeExportEmbedScene"
| "changeExportScale" | "changeExportScale"
| "saveToActiveFile" | "saveToActiveFile"
+3
View File
@@ -1,5 +1,6 @@
import oc from "open-color"; import oc from "open-color";
import { import {
DEFAULT_EXPORT_PADDING,
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
@@ -55,6 +56,7 @@ export const getDefaultAppState = (): Omit<
exportScale: defaultExportScale, exportScale: defaultExportScale,
exportEmbedScene: false, exportEmbedScene: false,
exportWithDarkMode: false, exportWithDarkMode: false,
exportPadding: DEFAULT_EXPORT_PADDING,
fileHandle: null, fileHandle: null,
gridSize: null, gridSize: null,
isBindingEnabled: true, isBindingEnabled: true,
@@ -145,6 +147,7 @@ const APP_STATE_STORAGE_CONF = (<
exportBackground: { browser: true, export: false, server: false }, exportBackground: { browser: true, export: false, server: false },
exportEmbedScene: { browser: true, export: false, server: false }, exportEmbedScene: { browser: true, export: false, server: false },
exportScale: { browser: true, export: false, server: false }, exportScale: { browser: true, export: false, server: false },
exportPadding: { browser: true, export: false, server: false },
exportWithDarkMode: { browser: true, export: false, server: false }, exportWithDarkMode: { browser: true, export: false, server: false },
fileHandle: { browser: false, export: false, server: false }, fileHandle: { browser: false, export: false, server: false },
gridSize: { browser: true, export: true, server: true }, gridSize: { browser: true, export: true, server: true },
+1 -1
View File
@@ -237,7 +237,7 @@ export const ShapesSwitcher = ({
keyBindingLabel={`${numberKey}`} keyBindingLabel={`${numberKey}`}
aria-label={capitalizeString(label)} aria-label={capitalizeString(label)}
aria-keyshortcuts={shortcut} aria-keyshortcuts={shortcut}
data-testid={value} data-testid={`toolbar-${value}`}
onPointerDown={({ pointerType }) => { onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") { if (!appState.penDetected && pointerType === "pen") {
setAppState({ setAppState({
-4
View File
@@ -4836,10 +4836,6 @@ class App extends React.Component<AppProps, AppState> {
} else { } else {
this.setState((prevState) => ({ this.setState((prevState) => ({
draggingElement: null, draggingElement: null,
selectedElementIds: {
...prevState.selectedElementIds,
[draggingElement.id]: true,
},
})); }));
} }
} }
+3 -7
View File
@@ -79,7 +79,6 @@ const ImageExportModal = ({
elements, elements,
appState, appState,
files, files,
exportPadding = DEFAULT_EXPORT_PADDING,
actionManager, actionManager,
onExportToPng, onExportToPng,
onExportToSvg, onExportToSvg,
@@ -88,7 +87,6 @@ const ImageExportModal = ({
appState: AppState; appState: AppState;
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles; files: BinaryFiles;
exportPadding?: number;
actionManager: ActionManager; actionManager: ActionManager;
onExportToPng: ExportCB; onExportToPng: ExportCB;
onExportToSvg: ExportCB; onExportToSvg: ExportCB;
@@ -116,7 +114,7 @@ const ImageExportModal = ({
exportToCanvas(exportedElements, appState, files, { exportToCanvas(exportedElements, appState, files, {
exportBackground, exportBackground,
viewBackgroundColor, viewBackgroundColor,
exportPadding, exportPadding: appState.exportPadding,
}) })
.then((canvas) => { .then((canvas) => {
// if converting to blob fails, there's some problem that will // if converting to blob fails, there's some problem that will
@@ -134,7 +132,6 @@ const ImageExportModal = ({
files, files,
exportedElements, exportedElements,
exportBackground, exportBackground,
exportPadding,
viewBackgroundColor, viewBackgroundColor,
]); ]);
@@ -151,8 +148,10 @@ const ImageExportModal = ({
// dunno why this is needed, but when the items wrap it creates // dunno why this is needed, but when the items wrap it creates
// an overflow // an overflow
overflow: "hidden", overflow: "hidden",
gap: ".6rem",
}} }}
> >
{actionManager.renderAction("changeExportPadding")}
{actionManager.renderAction("changeExportBackground")} {actionManager.renderAction("changeExportBackground")}
{someElementIsSelected && ( {someElementIsSelected && (
<CheckboxItem <CheckboxItem
@@ -221,7 +220,6 @@ export const ImageExportDialog = ({
appState, appState,
setAppState, setAppState,
files, files,
exportPadding = DEFAULT_EXPORT_PADDING,
actionManager, actionManager,
onExportToPng, onExportToPng,
onExportToSvg, onExportToSvg,
@@ -231,7 +229,6 @@ export const ImageExportDialog = ({
setAppState: React.Component<any, AppState>["setState"]; setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles; files: BinaryFiles;
exportPadding?: number;
actionManager: ActionManager; actionManager: ActionManager;
onExportToPng: ExportCB; onExportToPng: ExportCB;
onExportToSvg: ExportCB; onExportToSvg: ExportCB;
@@ -249,7 +246,6 @@ export const ImageExportDialog = ({
elements={elements} elements={elements}
appState={appState} appState={appState}
files={files} files={files}
exportPadding={exportPadding}
actionManager={actionManager} actionManager={actionManager}
onExportToPng={onExportToPng} onExportToPng={onExportToPng}
onExportToSvg={onExportToSvg} onExportToSvg={onExportToSvg}
+19 -12
View File
@@ -144,6 +144,7 @@ const LayerUI = ({
exportBackground: appState.exportBackground, exportBackground: appState.exportBackground,
name: appState.name, name: appState.name,
viewBackgroundColor: appState.viewBackgroundColor, viewBackgroundColor: appState.viewBackgroundColor,
exportPadding: appState.exportPadding,
}, },
) )
.catch(muteFSAbortError) .catch(muteFSAbortError)
@@ -213,7 +214,8 @@ const LayerUI = ({
padding={2} padding={2}
style={{ zIndex: 1 }} style={{ zIndex: 1 }}
> >
{actionManager.renderAction("loadScene")} {!appState.viewModeEnabled &&
actionManager.renderAction("loadScene")}
{/* // TODO barnabasmolnar/editor-redesign */} {/* // TODO barnabasmolnar/editor-redesign */}
{/* is this fine here? */} {/* is this fine here? */}
{appState.fileHandle && {appState.fileHandle &&
@@ -234,7 +236,8 @@ const LayerUI = ({
/> />
)} )}
{actionManager.renderAction("toggleShortcuts", undefined, true)} {actionManager.renderAction("toggleShortcuts", undefined, true)}
{actionManager.renderAction("clearCanvas")} {!appState.viewModeEnabled &&
actionManager.renderAction("clearCanvas")}
<Separator /> <Separator />
<MenuLinks /> <MenuLinks />
<Separator /> <Separator />
@@ -249,14 +252,16 @@ const LayerUI = ({
<div style={{ padding: "0 0.625rem" }}> <div style={{ padding: "0 0.625rem" }}>
<LanguageList style={{ width: "100%" }} /> <LanguageList style={{ width: "100%" }} />
</div> </div>
<div> {!appState.viewModeEnabled && (
<div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}> <div>
{t("labels.canvasBackground")} <div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}>
{t("labels.canvasBackground")}
</div>
<div style={{ padding: "0 0.625rem" }}>
{actionManager.renderAction("changeViewBackgroundColor")}
</div>
</div> </div>
<div style={{ padding: "0 0.625rem" }}> )}
{actionManager.renderAction("changeViewBackgroundColor")}
</div>
</div>
</div> </div>
</Island> </Island>
</Section> </Section>
@@ -299,12 +304,12 @@ const LayerUI = ({
return ( return (
<FixedSideContainer side="top"> <FixedSideContainer side="top">
{renderWelcomeScreen && !appState.isLoading && ( {renderWelcomeScreen && !appState.isLoading && (
<WelcomeScreen actionManager={actionManager} /> <WelcomeScreen appState={appState} actionManager={actionManager} />
)} )}
<div className="App-menu App-menu_top"> <div className="App-menu App-menu_top">
<Stack.Col <Stack.Col
gap={6} gap={6}
className={clsx({ className={clsx("App-menu_top__left", {
"disable-pointerEvents": appState.zenModeEnabled, "disable-pointerEvents": appState.zenModeEnabled,
})} })}
> >
@@ -405,7 +410,9 @@ const LayerUI = ({
/> />
)} )}
{renderTopRightUI?.(device.isMobile, appState)} {renderTopRightUI?.(device.isMobile, appState)}
<LibraryButton appState={appState} setAppState={setAppState} /> {!appState.viewModeEnabled && (
<LibraryButton appState={appState} setAppState={setAppState} />
)}
</div> </div>
</div> </div>
</FixedSideContainer> </FixedSideContainer>
+1
View File
@@ -39,6 +39,7 @@ export const LockButton = (props: LockIconProps) => {
onChange={props.onChange} onChange={props.onChange}
checked={props.checked} checked={props.checked}
aria-label={props.title} aria-label={props.title}
data-testid="toolbar-lock"
/> />
<div className="ToolIcon__icon"> <div className="ToolIcon__icon">
{props.checked ? ICONS.CHECKED : ICONS.UNCHECKED} {props.checked ? ICONS.CHECKED : ICONS.UNCHECKED}
+19 -15
View File
@@ -75,7 +75,7 @@ export const MobileMenu = ({
return ( return (
<FixedSideContainer side="top" className="App-top-bar"> <FixedSideContainer side="top" className="App-top-bar">
{renderWelcomeScreen && !appState.isLoading && ( {renderWelcomeScreen && !appState.isLoading && (
<WelcomeScreen actionManager={actionManager} /> <WelcomeScreen appState={appState} actionManager={actionManager} />
)} )}
<Section heading="shapes"> <Section heading="shapes">
{(heading: React.ReactNode) => ( {(heading: React.ReactNode) => (
@@ -127,11 +127,13 @@ export const MobileMenu = ({
title={t("toolBar.lock")} title={t("toolBar.lock")}
isMobile isMobile
/> />
<LibraryButton {!appState.viewModeEnabled && (
appState={appState} <LibraryButton
setAppState={setAppState} appState={appState}
isMobile setAppState={setAppState}
/> isMobile
/>
)}
</div> </div>
</Stack.Row> </Stack.Row>
</Stack.Col> </Stack.Col>
@@ -187,7 +189,7 @@ export const MobileMenu = ({
} }
return ( return (
<> <>
{actionManager.renderAction("loadScene")} {!appState.viewModeEnabled && actionManager.renderAction("loadScene")}
{renderJSONExportDialog()} {renderJSONExportDialog()}
{renderImageExportDialog()} {renderImageExportDialog()}
<MenuItem <MenuItem
@@ -204,18 +206,20 @@ export const MobileMenu = ({
/> />
)} )}
{actionManager.renderAction("toggleShortcuts", undefined, true)} {actionManager.renderAction("toggleShortcuts", undefined, true)}
{actionManager.renderAction("clearCanvas")} {!appState.viewModeEnabled && actionManager.renderAction("clearCanvas")}
<Separator /> <Separator />
<MenuLinks /> <MenuLinks />
<Separator /> <Separator />
<div style={{ marginBottom: ".5rem" }}> {!appState.viewModeEnabled && (
<div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}> <div style={{ marginBottom: ".5rem" }}>
{t("labels.canvasBackground")} <div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}>
{t("labels.canvasBackground")}
</div>
<div style={{ padding: "0 0.625rem" }}>
{actionManager.renderAction("changeViewBackgroundColor")}
</div>
</div> </div>
<div style={{ padding: "0 0.625rem" }}> )}
{actionManager.renderAction("changeViewBackgroundColor")}
</div>
</div>
{actionManager.renderAction("toggleTheme")} {actionManager.renderAction("toggleTheme")}
</> </>
); );
+21 -11
View File
@@ -5,6 +5,7 @@ import { getShortcutFromShortcutName } from "../actions/shortcuts";
import { COOKIES } from "../constants"; import { COOKIES } from "../constants";
import { collabDialogShownAtom } from "../excalidraw-app/collab/Collab"; import { collabDialogShownAtom } from "../excalidraw-app/collab/Collab";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppState } from "../types";
import { import {
ExcalLogo, ExcalLogo,
HelpIcon, HelpIcon,
@@ -60,7 +61,13 @@ const WelcomeScreenItem = ({
); );
}; };
const WelcomeScreen = ({ actionManager }: { actionManager: ActionManager }) => { const WelcomeScreen = ({
appState,
actionManager,
}: {
appState: AppState;
actionManager: ActionManager;
}) => {
const [, setCollabDialogShown] = useAtom(collabDialogShownAtom); const [, setCollabDialogShown] = useAtom(collabDialogShownAtom);
let subheadingJSX; let subheadingJSX;
@@ -68,12 +75,13 @@ const WelcomeScreen = ({ actionManager }: { actionManager: ActionManager }) => {
if (isExcalidrawPlusSignedUser) { if (isExcalidrawPlusSignedUser) {
subheadingJSX = t("welcomeScreen.switchToPlusApp") subheadingJSX = t("welcomeScreen.switchToPlusApp")
.split(/(Excalidraw\+)/) .split(/(Excalidraw\+)/)
.map((bit) => { .map((bit, idx) => {
if (bit === "Excalidraw+") { if (bit === "Excalidraw+") {
return ( return (
<a <a
style={{ pointerEvents: "all" }} style={{ pointerEvents: "all" }}
href={`${process.env.REACT_APP_PLUS_APP}?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenSignedInUser`} href={`${process.env.REACT_APP_PLUS_APP}?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenSignedInUser`}
key={idx}
> >
Excalidraw+ Excalidraw+
</a> </a>
@@ -94,15 +102,17 @@ const WelcomeScreen = ({ actionManager }: { actionManager: ActionManager }) => {
{subheadingJSX} {subheadingJSX}
</div> </div>
<div className="WelcomeScreen-items"> <div className="WelcomeScreen-items">
<WelcomeScreenItem {!appState.viewModeEnabled && (
// TODO barnabasmolnar/editor-redesign <WelcomeScreenItem
// do we want the internationalized labels here that are currently // TODO barnabasmolnar/editor-redesign
// in use elsewhere or new ones? // do we want the internationalized labels here that are currently
label={t("buttons.load")} // in use elsewhere or new ones?
onClick={() => actionManager.executeAction(actionLoadScene)} label={t("buttons.load")}
shortcut={getShortcutFromShortcutName("loadScene")} onClick={() => actionManager.executeAction(actionLoadScene)}
icon={LoadIcon} shortcut={getShortcutFromShortcutName("loadScene")}
/> icon={LoadIcon}
/>
)}
<WelcomeScreenItem <WelcomeScreenItem
label={t("labels.liveCollaboration")} label={t("labels.liveCollaboration")}
shortcut={null} shortcut={null}
+1 -1
View File
@@ -492,7 +492,7 @@ export const getElementBounds = (
export const getCommonBounds = ( export const getCommonBounds = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
): [number, number, number, number] => { ): [minX: number, minY: number, maxX: number, maxY: number] => {
if (!elements.length) { if (!elements.length) {
return [0, 0, 0, 0]; return [0, 0, 0, 0];
} }
+3 -2
View File
@@ -21,10 +21,11 @@ export const useOutsideClickHook = (handler: (event: Event) => void) => {
handler(event); handler(event);
}; };
document.addEventListener("mousedown", listener);
document.addEventListener("pointerdown", listener);
document.addEventListener("touchstart", listener); document.addEventListener("touchstart", listener);
return () => { return () => {
document.removeEventListener("mousedown", listener); document.removeEventListener("pointerdown", listener);
document.removeEventListener("touchstart", listener); document.removeEventListener("touchstart", listener);
}; };
}, },
+157 -11
View File
@@ -14,6 +14,102 @@ import {
export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`; export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
const getExactBoundingBox = async (
elements: readonly NonDeletedExcalidrawElement[],
appState: {
exportBackground: boolean;
exportPadding?: number;
exportScale?: number;
viewBackgroundColor: string;
exportWithDarkMode?: boolean;
exportEmbedScene?: boolean;
},
files: BinaryFiles,
): Promise<
[offsetLeft: number, offsetTop: number, width: number, height: number]
> => {
const padding = DEFAULT_EXPORT_PADDING;
// const padding = 0;
const [minX, minY, width, height] = getApproximateCanvasSize(
elements,
padding,
);
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const { imageCache } = await updateImageCache({
imageCache: new Map(),
fileIds: getInitializedImageElements(elements).map(
(element) => element.fileId,
),
files,
});
const defaultAppState = getDefaultAppState();
renderScene({
elements,
// @ts-ignore
appState,
scale: 1,
rc: rough.canvas(canvas),
canvas,
renderConfig: {
viewBackgroundColor: null,
scrollX: -minX + padding,
scrollY: -minY + padding,
zoom: defaultAppState.zoom,
remotePointerViewportCoords: {},
remoteSelectedElementIds: {},
shouldCacheIgnoreZoom: false,
remotePointerUsernames: {},
remotePointerUserStates: {},
theme: "light",
imageCache,
renderScrollbars: false,
renderSelection: false,
renderGrid: false,
isExporting: true,
},
});
const ctx = canvas.getContext("2d")!;
const { data } = ctx.getImageData(0, 0, width, height);
let _minX = Infinity;
let _minY = Infinity;
let _maxX = -Infinity;
let _maxY = -Infinity;
const rows = [];
let row: number[][] = [];
for (let i = 0; i < data.length - 1; i = i + 4) {
if (i && i % (width * 4) === 0) {
rows.push(row);
row = [];
}
const pixel = [data[i], data[i + 1], data[i + 2], data[i + 3]];
row.push(pixel);
}
for (const [y, row] of rows.entries()) {
for (const [x, pixel] of row.entries()) {
if (pixel[3] > 0) {
_minX = Math.min(_minX, x);
_minY = Math.min(_minY, y);
_maxX = Math.max(_maxX, x);
_maxY = Math.max(_maxY, y);
}
}
}
const offsetLeft = padding - _minX;
const offsetTop = padding - _minY;
return [offsetLeft, offsetTop, _maxX - _minX, _maxY - _minY];
};
export const exportToCanvas = async ( export const exportToCanvas = async (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
appState: AppState, appState: AppState,
@@ -37,7 +133,12 @@ export const exportToCanvas = async (
return { canvas, scale: appState.exportScale }; return { canvas, scale: appState.exportScale };
}, },
) => { ) => {
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding); const [scrollX, scrollY, width, height] = await getCanvasSize(
elements,
appState,
files,
exportPadding,
);
const { canvas, scale = 1 } = createCanvas(width, height); const { canvas, scale = 1 } = createCanvas(width, height);
@@ -59,8 +160,8 @@ export const exportToCanvas = async (
canvas, canvas,
renderConfig: { renderConfig: {
viewBackgroundColor: exportBackground ? viewBackgroundColor : null, viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
scrollX: -minX + exportPadding, scrollX,
scrollY: -minY + exportPadding, scrollY,
zoom: defaultAppState.zoom, zoom: defaultAppState.zoom,
remotePointerViewportCoords: {}, remotePointerViewportCoords: {},
remoteSelectedElementIds: {}, remoteSelectedElementIds: {},
@@ -109,7 +210,12 @@ export const exportToSvg = async (
console.error(error); console.error(error);
} }
} }
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding); const [minX, minY, width, height] = await getCanvasSize(
elements,
appState,
files || {},
exportPadding,
);
// initialize SVG root // initialize SVG root
const svgRoot = document.createElementNS(SVG_NS, "svg"); const svgRoot = document.createElementNS(SVG_NS, "svg");
@@ -172,26 +278,66 @@ export const exportToSvg = async (
return svgRoot; return svgRoot;
}; };
// calculate smallest area to fit the contents in const getApproximateCanvasSize = (
const getCanvasSize = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
exportPadding: number, exportPadding: number,
): [number, number, number, number] => { ): [number, number, number, number] => {
const [minX, minY, maxX, maxY] = getCommonBounds(elements); const bounds = getCommonBounds(elements);
const minX = Math.floor(bounds[0]);
const minY = Math.floor(bounds[1]);
const maxX = Math.ceil(bounds[2]);
const maxY = Math.ceil(bounds[3]);
const width = distance(minX, maxX) + exportPadding * 2; const width = distance(minX, maxX) + exportPadding * 2;
const height = distance(minY, maxY) + exportPadding + exportPadding; const height =
Math.ceil(distance(minY, maxY)) + exportPadding + exportPadding;
return [minX, minY, width, height]; return [minX, minY, width, height];
}; };
// calculate smallest area to fit the contents in
const getCanvasSize = async (
elements: readonly NonDeletedExcalidrawElement[],
appState: {
exportBackground: boolean;
exportPadding?: number;
exportScale?: number;
viewBackgroundColor: string;
exportWithDarkMode?: boolean;
exportEmbedScene?: boolean;
},
files: BinaryFiles,
exportPadding: number,
): Promise<[number, number, number, number]> => {
if (exportPadding) {
const [minX, minY, width, height] = getApproximateCanvasSize(
elements,
exportPadding,
);
return [-minX + exportPadding, -minY + exportPadding, width, height];
} else {
const [minX, minY] = getApproximateCanvasSize(elements, exportPadding);
const [offsetLeft, offsetRight, width, height] = await getExactBoundingBox(
elements,
appState,
files,
);
return [-minX + offsetLeft, -minY + offsetRight, width, height];
}
};
export const getExportSize = ( export const getExportSize = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
exportPadding: number, exportPadding: number,
scale: number, scale: number,
): [number, number] => { ): [number, number] => {
const [, , width, height] = getCanvasSize(elements, exportPadding).map( const [, , width, height] = getApproximateCanvasSize(
(dimension) => Math.trunc(dimension * scale), elements,
); exportPadding,
).map((dimension) => Math.trunc(dimension * scale));
return [width, height]; return [width, height];
}; };
+2 -1
View File
@@ -1,6 +1,7 @@
import { queries, buildQueries } from "@testing-library/react"; import { queries, buildQueries } from "@testing-library/react";
const toolMap = { const toolMap = {
lock: "lock",
selection: "selection", selection: "selection",
rectangle: "rectangle", rectangle: "rectangle",
diamond: "diamond", diamond: "diamond",
@@ -15,7 +16,7 @@ export type ToolName = keyof typeof toolMap;
const _getAllByToolName = (container: HTMLElement, tool: string) => { const _getAllByToolName = (container: HTMLElement, tool: string) => {
const toolTitle = toolMap[tool as ToolName]; const toolTitle = toolMap[tool as ToolName];
return queries.getAllByTestId(container, toolTitle); return queries.getAllByTestId(container, `toolbar-${toolTitle}`);
}; };
const getMultipleError = (_container: any, tool: any) => const getMultipleError = (_container: any, tool: any) =>
+18 -1
View File
@@ -11,7 +11,8 @@ import * as Renderer from "../renderer/renderScene";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { reseed } from "../random"; import { reseed } from "../random";
import { API } from "./helpers/api"; import { API } from "./helpers/api";
import { Keyboard, Pointer } from "./helpers/ui"; import { Keyboard, Pointer, UI } from "./helpers/ui";
import { SHAPES } from "../shapes";
// Unmount ReactDOM from root // Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!); ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
@@ -380,3 +381,19 @@ describe("select single element on the scene", () => {
h.elements.forEach((element) => expect(element).toMatchSnapshot()); h.elements.forEach((element) => expect(element).toMatchSnapshot());
}); });
}); });
describe("tool locking & selection", () => {
it("should not select newly created element while tool is locked", async () => {
await render(<ExcalidrawApp />);
UI.clickTool("lock");
expect(h.state.activeTool.locked).toBe(true);
for (const { value } of Object.values(SHAPES)) {
if (value !== "image" && value !== "selection") {
const element = UI.createElement(value);
expect(h.state.selectedElementIds[element.id]).not.toBe(true);
}
}
});
});
+1
View File
@@ -113,6 +113,7 @@ export type AppState = {
exportEmbedScene: boolean; exportEmbedScene: boolean;
exportWithDarkMode: boolean; exportWithDarkMode: boolean;
exportScale: number; exportScale: number;
exportPadding: number;
currentItemStrokeColor: string; currentItemStrokeColor: string;
currentItemBackgroundColor: string; currentItemBackgroundColor: string;
currentItemFillStyle: ExcalidrawElement["fillStyle"]; currentItemFillStyle: ExcalidrawElement["fillStyle"];