Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): file drop overlay & shift-to-merge imported scene (#12177)

David Luzard29d86488478
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index 87db242929..b4fdc3ee37 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -457,6 +457,7 @@ import { AppWheel } from "./App.wheel";
import BraveMeasureTextError from "./BraveMeasureTextError";
import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
import { activeEyeDropperAtom } from "./EyeDropper";
+import { FileDropOverlay } from "./FileDropOverlay";
import { ViewportStatusBorder } from "./ViewportStatusFrame/ViewportStatusFrame";
import LayerUI from "./LayerUI";
import { ElementCanvasButton } from "./MagicButton";
@@ -2453,7 +2454,7 @@ class App extends React.Component<AppProps, AppState> {
["--zen-mode-transition-duration" as any]: `${ZEN_MODE_TRANSITION_DURATION}ms`,
}}
ref={this.excalidrawContainerRef}
- onDrop={this.isInteractionEnabled() ? this.handleAppOnDrop : undefined}
+ onDrop={this.isFileDropEnabled() ? this.handleAppOnDrop : undefined}
tabIndex={0}
onKeyDown={
this.props.handleKeyboardGlobally || !this.isInteractionEnabled()
@@ -2542,6 +2543,9 @@ class App extends React.Component<AppProps, AppState> {
]}
/>
{this.isDefaultUIEnabled() && <CursorHint />}
+ {this.isDefaultUIEnabled() &&
+ this.isInteractionEnabled() &&
+ !this.state.viewModeEnabled && <FileDropOverlay />}
{this.isDefaultUIEnabled() &&
selectedElements.length === 1 &&
this.state.openDialog?.name !==
@@ -3259,6 +3263,18 @@ class App extends React.Component<AppProps, AppState> {
event.preventDefault();
};
+ private isFileDropEnabled() {
+ return this.isInteractionEnabled() && !this.state.viewModeEnabled;
+ }
+
+ private onDragOver = (event: DragEvent) => {
+ event.preventDefault();
+ if (!this.isFileDropEnabled() && event.dataTransfer) {
+ // show a no-drop cursor
+ event.dataTransfer.dropEffect = "none";
+ }
+ };
+
// handles only the navigation keyboard: page-scroll keys and
// `navigation`-flagged action shortcuts (canvas zoom & zoom-to-fit — see
// `ActionManager.handleKeyDown` gates); the rest of the keyboard handling
@@ -4010,6 +4026,20 @@ class App extends React.Component<AppProps, AppState> {
this.onWindowMessage,
false,
),
+ // cancelled even when drops are ignored (view mode, non-interactive),
+ // so a dropped file doesn't make the browser navigate away to it
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.DRAG_OVER,
+ this.onDragOver,
+ false,
+ ),
+ addEventListener(
+ this.excalidrawContainerRef.current,
+ EVENT.DROP,
+ this.disableEvent,
+ false,
+ ),
addEventListener(
this.ownerDocument,
EVENT.POINTER_UP,
@@ -4231,18 +4261,6 @@ class App extends React.Component<AppProps, AppState> {
this.wheel.handle,
{ passive: false },
),
- addEventListener(
- this.excalidrawContainerRef.current,
- EVENT.DRAG_OVER,
- this.disableEvent,
- false,
- ),
- addEventListener(
- this.excalidrawContainerRef.current,
- EVENT.DROP,
- this.disableEvent,
- false,
- ),
);
if (this.props.detectScroll) {
@@ -5317,6 +5335,16 @@ class App extends React.Component<AppProps, AppState> {
this.setState({ toast });
};
+ private showSceneReplacedToast() {
+ this.setToast({
+ message: t("fileDrop.replacedToast", {
+ shortcut: getShortcutKey("CtrlOrCmd+Z"),
+ }),
+ closable: true,
+ duration: 8000,
+ });
+ }
+
restoreFileFromShare = async () => {
try {
const webShareTargetCache = await caches.open("web-share-target");
@@ -13093,10 +13121,11 @@ class App extends React.Component<AppProps, AppState> {
};
private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
- // NOTE no preventDefault so the host page can handle the drop itself
- if (!this.isInteractionEnabled()) {
+ if (!this.isFileDropEnabled()) {
return;
}
+ const { shiftKey, clientX, clientY } = event;
+ const insertPosition = shiftKey ? { clientX, clientY } : undefined;
const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
event,
this.state,
@@ -13113,13 +13142,31 @@ class App extends React.Component<AppProps, AppState> {
file &&
(file.type === MIME_TYPES.png || file.type === MIME_TYPES.svg)
) {
+ let scene;
try {
- const scene = await loadFromBlob(
+ scene = await loadFromBlob(
file,
this.state,
this.scene.getElementsIncludingDeleted(),
fileHandle,
);
+ } catch (error: any) {
+ if (error.name !== "EncodingError") {
+ throw new Error(t("alerts.couldNotLoadInvalidFile"));
+ }
+ // if EncodingError, fall through to insert as regular image
+ }
+ if (scene) {
+ if (insertPosition) {
+ this.addElementsFromPasteOrLibrary({
+ elements: scene.elements,
+ files: scene.files,
+ position: insertPosition,
+ retainSeed: true,
+ preserveFrameChildrenOrder: true,
+ });
+ return;
+ }
this.syncActionResult({
...scene,
appState: {
@@ -13129,12 +13176,8 @@ class App extends React.Component<AppProps, AppState> {
replaceFiles: true,
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
});
+ this.showSceneReplacedToast();
return;
- } catch (error: any) {
- if (error.name !== "EncodingError") {
- throw new Error(t("alerts.couldNotLoadInvalidFile"));
- }
- // if EncodingError, fall through to insert as regular image
}
}
}
@@ -13195,7 +13238,9 @@ class App extends React.Component<AppProps, AppState> {
const { file, fileHandle } = fileItems[0];
if (file) {
// Attempt to parse an excalidraw/excalidrawlib file
- await this.loadFileToCanvas(file, fileHandle);
+ if (await this.loadFileToCanvas(file, fileHandle, insertPosition)) {
+ this.showSceneReplacedToast();
+ }
}
}
@@ -13222,9 +13267,11 @@ class App extends React.Component<AppProps, AppState> {
}
};
+ /** @returns true if the file replaced the scene */
loadFileToCanvas = async (
file: File,
fileHandle: FileSystemFileHandle | null,
+ insertPosition?: { clientX: number; clientY: number },
) => {
file = await normalizeFile(file);
try {
@@ -13263,6 +13310,16 @@ class App extends React.Component<AppProps, AppState> {
}
if (ret.type === MIME_TYPES.excalidraw) {
+ if (insertPosition) {
+ this.addElementsFromPasteOrLibrary({
+ elements: ret.data.elements,
+ files: ret.data.files,
+ position: insertPosition,
+ retainSeed: true,
+ preserveFrameChildrenOrder: true,
+ });
+ return;
+ }
// restore the fractional indices by mutating elements
syncInvalidIndices(elements.concat(ret.data.elements));
@@ -13284,6 +13341,7 @@ class App extends React.Component<AppProps, AppState> {
replaceFiles: true,
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
});
+ return true;
} else if (ret.type === MIME_TYPES.excalidrawlib) {
await this.library
.updateLibrary({
diff --git a/packages/excalidraw/components/FileDropOverlay.scss b/packages/excalidraw/components/FileDropOverlay.scss
new file mode 100644
index 0000000000..b9f666af23
--- /dev/null
+++ b/packages/excalidraw/components/FileDropOverlay.scss
@@ -0,0 +1,167 @@
+.excalidraw {
+ .file-drop-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: var(--zIndex-fileDropOverlay);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 1rem;
+ box-sizing: border-box;
+ pointer-events: none;
+ background: var(--overlay-bg-color);
+ animation: file-drop-overlay-appear 120ms ease-out;
+ }
+
+ .file-drop-overlay__card {
+ width: 30rem;
+ max-width: 100%;
+ box-sizing: border-box;
+ padding: 2rem 1.5rem 1.5rem;
+ border: 1px solid var(--color-primary-light-darker);
+ border-radius: 1.5rem;
+ background: var(--island-bg-color);
+ box-shadow: 0 16px 48px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
+ text-align: center;
+ }
+
+ .file-drop-overlay__title {
+ color: var(--text-primary-color);
+ font-size: 1.5rem;
+ font-weight: 700;
+ line-height: 1.3;
+ }
+
+ .file-drop-overlay__hint {
+ margin-top: 0.5rem;
+ color: var(--text-primary-color);
+ opacity: 0.7;
+ font-size: 0.875rem;
+ line-height: 1.75;
+
+ kbd {
+ padding: 0.125rem 0.375rem;
+ border: 1px solid var(--default-border-color);
+ border-radius: 0.25rem;
+ background: var(--color-surface-low);
+ font: inherit;
+ }
+
+ &--secondary {
+ margin-top: 0;
+ opacity: 0.45;
+ font-size: 0.75rem;
+ }
+ }
+
+ .file-drop-overlay__illustration {
+ position: relative;
+ height: 10rem;
+ margin-top: 1.75rem;
+ color: var(--color-primary);
+ }
+
+ .file-drop-overlay__file {
+ position: absolute;
+ top: 0.5rem;
+ left: calc(50% - 3rem);
+ width: 6rem;
+ height: 8rem;
+ overflow: visible;
+ stroke: currentColor;
+ stroke-width: 2.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ animation: file-drop-overlay-float 3.6s ease-in-out infinite;
+
+ &--back {
+ --file-x: -1.5rem;
+ --file-angle: -18deg;
+ top: 1rem;
+ color: var(--color-primary-light-darker);
+ }
+
+ &--front {
+ --file-x: 1.5rem;
+ --file-angle: 12deg;
+ animation-delay: -1.8s;
+ }
+ }
+
+ .file-drop-overlay__paper {
+ fill: var(--island-bg-color);
+ }
+
+ .file-drop-overlay__lines {
+ opacity: 0.35;
+ }
+
+ .file-drop-overlay__cross {
+ stroke-width: 4;
+ }
+
+ // replacing: the existing content (back file) is crossed out
+ .file-drop-overlay:not(.file-drop-overlay--keep)
+ .file-drop-overlay__file--back
+ .file-drop-overlay__lines {
+ opacity: 0;
+ }
+
+ .file-drop-overlay--keep {
+ .file-drop-overlay__file--back {
+ color: var(--color-primary);
+ }
+
+ .file-drop-overlay__cross {
+ opacity: 0;
+ }
+ }
+
+ @keyframes file-drop-overlay-appear {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+ }
+
+ @keyframes file-drop-overlay-float {
+ 0%,
+ 100% {
+ transform: translate(var(--file-x), 0) rotate(var(--file-angle));
+ }
+ 50% {
+ transform: translate(var(--file-x), -0.375rem)
+ rotate(calc(var(--file-angle) + 3deg));
+ }
+ }
+
+ @media (prefers-reduced-motion: reduce) {
+ .file-drop-overlay,
+ .file-drop-overlay__file {
+ animation: none;
+ }
+
+ .file-drop-overlay__file {
+ transform: translate(var(--file-x), 0) rotate(var(--file-angle));
+ }
+ }
+
+ @media (max-height: 420px) {
+ .file-drop-overlay__card {
+ padding: 1.25rem;
+ }
+
+ .file-drop-overlay__illustration {
+ height: 7rem;
+ margin-top: 0.75rem;
+ }
+
+ .file-drop-overlay__file {
+ width: 4.5rem;
+ height: 6rem;
+ left: calc(50% - 2.25rem);
+ }
+ }
+}
diff --git a/packages/excalidraw/components/FileDropOverlay.tsx b/packages/excalidraw/components/FileDropOverlay.tsx
new file mode 100644
index 0000000000..ecfa9495b0
--- /dev/null
+++ b/packages/excalidraw/components/FileDropOverlay.tsx
@@ -0,0 +1,188 @@
+import { useEffect, useState } from "react";
+
+import clsx from "clsx";
+
+import { KEYS, MIME_TYPES } from "@excalidraw/common";
+
+import { useI18n } from "../i18n";
+
+import { useApp, useExcalidrawContainer } from "./App";
+import Trans from "./Trans";
+
+import "./FileDropOverlay.scss";
+
+type FileDropState = {
+ shiftKey: boolean;
+ // "unknown": no MIME type, which is what OS-dragged .excalidraw and
+ // .excalidrawlib files both report, so it can be either until dropped
+ kind: "scene" | "library" | "unknown";
+};
+
+export const FileDropOverlay = () => {
+ const app = useApp();
+ const { container } = useExcalidrawContainer();
+ const { t } = useI18n();
+ const [dragState, setDragState] = useState<FileDropState | null>(null);
+
+ useEffect(() => {
+ if (!container) {
+ return;
+ }
+
+ let dragDepth = 0;
+ const reset = () => {
+ dragDepth = 0;
+ setDragState(null);
+ };
+ const isFileDrag = (event: DragEvent) =>
+ Array.from(event.dataTransfer?.types ?? []).includes("Files");
+
+ const update = (event: DragEvent) => {
+ const files = Array.from(event.dataTransfer?.items ?? []).filter(
+ (item) => item.kind === "file",
+ );
+ // Filenames are protected until drop, so .excalidraw.png/.svg exports
+ // cannot be distinguished here. Keep the canvas visible for all images.
+ if (files.some((file) => file.type.startsWith("image/"))) {
+ setDragState(null);
+ return;
+ }
+
+ const type = files[0]?.type;
+ const kind: FileDropState["kind"] =
+ type === MIME_TYPES.excalidrawlib
+ ? "library"
+ : type
+ ? "scene"
+ : "unknown";
+
+ setDragState((previous) =>
+ previous?.shiftKey === event.shiftKey && previous.kind === kind
+ ? previous
+ : { shiftKey: event.shiftKey, kind },
+ );
+ };
+ const onDragEnter = (event: DragEvent) => {
+ if (isFileDrag(event)) {
+ dragDepth++;
+ update(event);
+ }
+ };
+ const onDragOver = (event: DragEvent) => {
+ // App's own dragover listener already calls preventDefault()
+ if (isFileDrag(event)) {
+ // Shift defaults the drag to "move" (and its cursor), but we only
+ // ever copy the file in
+ if (event.dataTransfer) {
+ event.dataTransfer.dropEffect = "copy";
+ }
+ dragDepth = Math.max(1, dragDepth);
+ update(event);
+ }
+ };
+ const onDragLeave = () => {
+ dragDepth = Math.max(0, dragDepth - 1);
+ if (!dragDepth) {
+ reset();
+ }
+ };
+ const onKeyChange = (event: KeyboardEvent) => {
+ if (event.key === KEYS.ESCAPE) {
+ reset();
+ } else if (event.key === "Shift") {
+ setDragState((previous) =>
+ previous ? { ...previous, shiftKey: event.shiftKey } : previous,
+ );
+ }
+ };
+
+ container.addEventListener("dragenter", onDragEnter);
+ container.addEventListener("dragover", onDragOver);
+ container.addEventListener("dragleave", onDragLeave);
+ app.ownerDocument.addEventListener("drop", reset, true);
+ app.ownerDocument.addEventListener("dragend", reset, true);
+ app.ownerDocument.addEventListener("keydown", onKeyChange, true);
+ app.ownerDocument.addEventListener("keyup", onKeyChange, true);
+ app.ownerWindow.addEventListener("blur", reset);
+
+ return () => {
+ container.removeEventListener("dragenter", onDragEnter);
+ container.removeEventListener("dragover", onDragOver);
+ container.removeEventListener("dragleave", onDragLeave);
+ app.ownerDocument.removeEventListener("drop", reset, true);
+ app.ownerDocument.removeEventListener("dragend", reset, true);
+ app.ownerDocument.removeEventListener("keydown", onKeyChange, true);
+ app.ownerDocument.removeEventListener("keyup", onKeyChange, true);
+ app.ownerWindow.removeEventListener("blur", reset);
+ };
+ }, [app, container]);
+
+ if (!dragState) {
+ return null;
+ }
+
+ const keepsContent = dragState.shiftKey || dragState.kind === "library";
+
+ return (
+ <div
+ className={clsx("file-drop-overlay", {
+ "file-drop-overlay--keep": keepsContent,
+ })}
+ >
+ <div className="file-drop-overlay__card">
+ <div role="status" aria-live="polite" aria-atomic="true">
+ <div className="file-drop-overlay__title">
+ {t(
+ dragState.kind === "library"
+ ? "fileDrop.importLibrary"
+ : dragState.shiftKey
+ ? "fileDrop.add"
+ : "fileDrop.replace",
+ )}
+ </div>
+ <div className="file-drop-overlay__hint">
+ {keepsContent ? (
+ t("fileDrop.keepHint")
+ ) : (
+ <Trans
+ i18nKey="fileDrop.replaceHint"
+ shift={(children) => <kbd>{children}</kbd>}
+ />
+ )}
+ </div>
+ {dragState.kind === "unknown" && (
+ <div className="file-drop-overlay__hint file-drop-overlay__hint--secondary">
+ ({t("fileDrop.libraryHint")})
+ </div>
+ )}
+ </div>
+ <div className="file-drop-overlay__illustration" aria-hidden="true">
+ {(["back", "front"] as const).map((position) => (
+ <svg
+ key={position}
+ className={`file-drop-overlay__file file-drop-overlay__file--${position}`}
+ viewBox="0 0 100 128"
+ fill="none"
+ >
+ <path
+ className="file-drop-overlay__paper"
+ d="M16 3h43l28 28v81c0 7-4 12-12 12H16c-8 0-12-5-12-12V15C4 7 8 3 16 3Z"
+ />
+ <path d="M59 3v20c0 6 3 8 9 8h19" />
+ <path
+ className="file-drop-overlay__lines"
+ d="M24 61h43M24 77h43M24 93h26"
+ />
+ {position === "back" && (
+ <path
+ className="file-drop-overlay__cross"
+ d="M18 44l24 24M42 44L18 68"
+ />
+ )}
+ </svg>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/excalidraw/components/Modal.scss b/packages/excalidraw/components/Modal.scss
index 9154079e28..1f3fd3a47f 100644
--- a/packages/excalidraw/components/Modal.scss
+++ b/packages/excalidraw/components/Modal.scss
@@ -47,7 +47,7 @@
right: 0;
bottom: 0;
z-index: 1;
- background-color: rgba(#121212, 0.2);
+ background-color: var(--overlay-bg-color);
animation: Modal__background__fade-in 0.1s linear forwards;
}
diff --git a/packages/excalidraw/css/styles.scss b/packages/excalidraw/css/styles.scss
index 4e68554993..e7075c4564 100644
--- a/packages/excalidraw/css/styles.scss
+++ b/packages/excalidraw/css/styles.scss
@@ -20,6 +20,7 @@
--zIndex-ui-top: 100;
--zIndex-ui-main-menu: 110;
--zIndex-ui-library: 120;
+ --zIndex-fileDropOverlay: 130;
--zIndex-modal: 1000;
--zIndex-popup: 1001;
diff --git a/packages/excalidraw/css/theme.scss b/packages/excalidraw/css/theme.scss
index 053b09a3ed..08a88cc5ce 100644
--- a/packages/excalidraw/css/theme.scss
+++ b/packages/excalidraw/css/theme.scss
@@ -27,7 +27,7 @@
--link-color: #{$color-blue-7};
--link-color-hover: #{$color-blue-8};
--link-color-active: #{$color-blue-2};
- --overlay-bg-color: #{color.adjust(#fff, $alpha: -0.12)};
+ --overlay-bg-color: rgba(12, 12, 14, 0.35);
--popup-bg-color: var(--island-bg-color);
--popup-secondary-bg-color: #{$color-gray-1};
--popup-text-color: #000;
@@ -204,7 +204,7 @@
--island-bg-color-alt: hsl(240, 12%, 12%);
--keybinding-color: var(--color-gray-60);
--link-color: #{$color-blue-4};
- --overlay-bg-color: #{color.adjust($color-gray-8, $alpha: -0.88)};
+ --overlay-bg-color: rgba(12, 12, 14, 0.65);
--popup-secondary-bg-color: #222;
--popup-text-color: #{$color-gray-4};
--popup-text-inverted-color: #2c2c2c;
diff --git a/packages/excalidraw/hooks/useCreatePortalContainer.ts b/packages/excalidraw/hooks/useCreatePortalContainer.ts
index b85fb16842..142c050700 100644
--- a/packages/excalidraw/hooks/useCreatePortalContainer.ts
+++ b/packages/excalidraw/hooks/useCreatePortalContainer.ts
@@ -1,6 +1,6 @@
import { useState, useLayoutEffect } from "react";
-import { THEME } from "@excalidraw/common";
+import { EVENT, THEME } from "@excalidraw/common";
import { useEditorInterface, useExcalidrawContainer } from "../components/App";
import { useUIAppState } from "../context/ui-appState";
@@ -42,9 +42,24 @@ export const useCreatePortalContainer = (opts?: {
container.appendChild(div);
+ // outside the editor container (whose own listeners cover it), so don't
+ // let a file dropped on e.g. a modal make the browser open it
+ const onFileDrag = (event: DragEvent) => {
+ if (event.dataTransfer?.types.includes("Files")) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "none";
+ }
+ };
+ if (!opts?.parentSelector) {
+ div.addEventListener(EVENT.DRAG_OVER, onFileDrag);
+ div.addEventListener(EVENT.DROP, onFileDrag);
+ }
+
setDiv(div);
return () => {
+ div.removeEventListener(EVENT.DRAG_OVER, onFileDrag);
+ div.removeEventListener(EVENT.DROP, onFileDrag);
container.removeChild(div);
};
}, [excalidrawContainer, opts?.parentSelector]);
diff --git a/packages/excalidraw/locales/en.json b/packages/excalidraw/locales/en.json
index ae2c3f27db..5ba1912e50 100644
--- a/packages/excalidraw/locales/en.json
+++ b/packages/excalidraw/locales/en.json
@@ -659,6 +659,15 @@
}
}
},
+ "fileDrop": {
+ "replace": "Drop to replace content",
+ "add": "Drop to add to canvas",
+ "importLibrary": "Drop to import library",
+ "replaceHint": "Hold <shift>Shift</shift> to keep existing content",
+ "keepHint": "Your existing content will be kept",
+ "libraryHint": "Library files will append",
+ "replacedToast": "Content replaced. {{shortcut}} to undo"
+ },
"mermaid": {
"title": "Mermaid to Excalidraw",
"button": "Insert",
diff --git a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
index f8a0b34d49..9d628d37e1 100644
--- a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
+++ b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
@@ -14732,7 +14732,11 @@ exports[`history > singleplayer undo/redo > should create new history entry on s
"suggestedBinding": null,
"textToolHover": null,
"theme": "light",
- "toast": null,
+ "toast": {
+ "closable": true,
+ "duration": 8000,
+ "message": "Content replaced. Ctrl+Z to undo",
+ },
"viewBackgroundColor": "#000",
"viewModeEnabled": false,
"width": 0,
diff --git a/packages/excalidraw/tests/fileDrop.test.tsx b/packages/excalidraw/tests/fileDrop.test.tsx
new file mode 100644
index 0000000000..69d5330541
--- /dev/null
+++ b/packages/excalidraw/tests/fileDrop.test.tsx
@@ -0,0 +1,330 @@
+import React from "react";
+
+import { MIME_TYPES } from "@excalidraw/common";
+
+import { serializeAsJSON } from "../data/json";
+import { Excalidraw } from "../index";
+
+import { API } from "./helpers/api";
+import { Keyboard } from "./helpers/ui";
+import { act, fireEvent, GlobalTestState, render, waitFor } from "./test-utils";
+
+const { h } = window;
+
+// jsdom has no DragEvent constructor. MouseEvent supplies the coordinates and
+// modifier keys, and the data store models files being protected until drop.
+const drag = (
+ target: Element,
+ type: string,
+ {
+ files = [],
+ types = ["Files"],
+ ...init
+ }: MouseEventInit & { files?: File[]; types?: string[] } = {},
+) => {
+ const event = new target.ownerDocument.defaultView!.MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ clientX: 200,
+ clientY: 200,
+ ...init,
+ });
+ Object.defineProperty(event, "dataTransfer", {
+ value: {
+ dropEffect: "none",
+ types,
+ files: type === "drop" ? files : [],
+ items: files.map((file) => ({
+ kind: "file",
+ type: file.type,
+ getAsFile: () => (type === "drop" ? file : null),
+ })),
+ },
+ });
+ fireEvent(target, event);
+ return event as MouseEvent & { dataTransfer: { dropEffect: string } };
+};
+
+const overlay = () =>
+ GlobalTestState.renderResult.container.querySelector(".file-drop-overlay");
+
+const sceneFile = () =>
+ new h.app.ownerWindow.File(
+ [
+ serializeAsJSON(
+ [API.createElement({ type: "ellipse", id: "existing" })],
+ { ...h.state, viewBackgroundColor: "#ff0000" },
+ {},
+ "local",
+ ),
+ ],
+ "scene.excalidraw",
+ { type: MIME_TYPES.json },
+ );
+
+describe("file drop overlay", () => {
+ it("ignores text and library-item drags, and stays visible across child boundaries", async () => {
+ await render(<Excalidraw />);
+ const canvas = GlobalTestState.interactiveCanvas;
+ const container = canvas.closest(".excalidraw")!;
+
+ for (const type of [MIME_TYPES.text, MIME_TYPES.excalidrawlibIds]) {
+ drag(canvas, "dragenter", { types: [type] });
+ expect(overlay()).toBeNull();
+ }
+
+ drag(container, "dragenter");
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ drag(canvas, "dragenter");
+ drag(container, "dragleave");
+ expect(overlay()).not.toBeNull();
+ drag(canvas, "dragleave");
+ expect(overlay()).toBeNull();
+ });
+
+ it("updates when Shift changes through drag events or keyboard events", async () => {
+ await render(<Excalidraw />);
+ const canvas = GlobalTestState.interactiveCanvas;
+ drag(canvas, "dragenter", { shiftKey: true });
+ expect(overlay()?.textContent).toContain("Drop to add to canvas");
+
+ drag(canvas, "dragover", { shiftKey: false });
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ fireEvent.keyDown(h.app.ownerDocument, { key: "Shift", shiftKey: true });
+ expect(overlay()?.textContent).toContain(
+ "Your existing content will be kept",
+ );
+ fireEvent.keyUp(h.app.ownerDocument, { key: "Shift", shiftKey: false });
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ });
+
+ it.each(["drop", "dragend", "Escape", "blur"])(
+ "clears on %s and can show again for the next drag",
+ async (type) => {
+ await render(<Excalidraw />);
+ const canvas = GlobalTestState.interactiveCanvas;
+ drag(canvas, "dragenter");
+ expect(overlay()).not.toBeNull();
+
+ if (type === "Escape") {
+ fireEvent.keyDown(h.app.ownerDocument, { key: "Escape" });
+ } else if (type === "blur") {
+ fireEvent.blur(h.app.ownerWindow);
+ } else {
+ drag(h.app.ownerDocument.body, type);
+ }
+ expect(overlay()).toBeNull();
+ drag(canvas, "dragenter");
+ expect(overlay()).not.toBeNull();
+ drag(canvas, "dragleave");
+ expect(overlay()).toBeNull();
+ },
+ );
+
+ it.each([
+ { types: [MIME_TYPES.jpg] },
+ { types: [MIME_TYPES.webp] },
+ { types: [MIME_TYPES.gif] },
+ { types: [MIME_TYPES.png] },
+ { types: [MIME_TYPES.svg] },
+ { types: ["image/tiff"] },
+ { types: [MIME_TYPES.png, MIME_TYPES.svg] },
+ { types: [MIME_TYPES.json, MIME_TYPES.jpg] },
+ ])("keeps the canvas visible for image drags: $types", async ({ types }) => {
+ await render(<Excalidraw />);
+ const canvas = GlobalTestState.interactiveCanvas;
+ const files = types.map(
+ (type) => new h.app.ownerWindow.File([], "file", { type }),
+ );
+
+ drag(canvas, "dragenter", { files });
+ expect(overlay()).toBeNull();
+ drag(canvas, "dragover", { files, shiftKey: true });
+ fireEvent.keyDown(h.app.ownerDocument, { key: "Shift", shiftKey: true });
+ expect(overlay()).toBeNull();
+ fireEvent.keyUp(h.app.ownerDocument, { key: "Shift", shiftKey: false });
+ drag(canvas, "dragleave", { files });
+
+ // A later scene drag must still show the overlay.
+ drag(canvas, "dragenter");
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ });
+
+ it("describes library imports without reading protected files", async () => {
+ await render(<Excalidraw />);
+ const file = new h.app.ownerWindow.File([], "file", {
+ type: MIME_TYPES.excalidrawlib,
+ });
+ drag(GlobalTestState.interactiveCanvas, "dragenter", { files: [file] });
+ expect(overlay()?.textContent).toContain("Drop to import library");
+ });
+
+ it("mentions libraries when the file type is unknown, as for OS-dragged .excalidraw(lib) files", async () => {
+ await render(<Excalidraw />);
+ const canvas = GlobalTestState.interactiveCanvas;
+ const untyped = new h.app.ownerWindow.File([], "file", { type: "" });
+ drag(canvas, "dragenter", { files: [untyped] });
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ expect(overlay()?.textContent).toContain("Library files will append");
+ drag(canvas, "dragleave");
+
+ const json = new h.app.ownerWindow.File([], "file", {
+ type: MIME_TYPES.json,
+ });
+ drag(canvas, "dragenter", { files: [json] });
+ expect(overlay()?.textContent).toContain("Drop to replace content");
+ expect(overlay()?.textContent).not.toContain("Library files");
+ });
+
+ it.each([
+ { interaction: false as const },
+ { ui: false as const },
+ { viewModeEnabled: true },
+ ])("respects disabled interaction/UI: %j", async (props) => {
+ await render(<Excalidraw {...props} />);
+ drag(GlobalTestState.interactiveCanvas, "dragenter");
+ expect(overlay()).toBeNull();
+ });
+});
+
+describe("dropping scenes", () => {
+ beforeEach(async () => {
+ await render(
+ <Excalidraw
+ handleKeyboardGlobally
+ initialData={{
+ elements: [API.createElement({ type: "rectangle", id: "existing" })],
+ appState: { viewBackgroundColor: "#ffffff" },
+ }}
+ />,
+ );
+ });
+
+ it("replaces the scene by default, removes the overlay, and toasts how to undo", async () => {
+ const original = h.elements[0];
+ drag(GlobalTestState.interactiveCanvas, "dragenter");
+ drag(GlobalTestState.interactiveCanvas, "drop", { files: [sceneFile()] });
+ expect(overlay()).toBeNull();
+ await waitFor(() => {
+ expect(h.elements).toEqual([
+ expect.objectContaining({ type: "ellipse" }),
+ ]);
+ expect(h.state.viewBackgroundColor).toBe("#ff0000");
+ });
+ expect(h.state.toast?.message).toMatch(/^Content replaced\. .+Z to undo$/);
+
+ await waitFor(() => expect(API.getUndoStack()).toHaveLength(1));
+ Keyboard.undo();
+ expect(h.app.scene.getNonDeletedElements()).toEqual([
+ expect.objectContaining({ id: original.id, type: "rectangle" }),
+ ]);
+ expect(h.state.viewBackgroundColor).toBe("#ffffff");
+ });
+
+ it("toasts how to undo when a scene embedded in an image replaces the scene", async () => {
+ const file = await API.loadFile("./fixtures/smiley_embedded_v2.png");
+ drag(GlobalTestState.interactiveCanvas, "drop", { files: [file] });
+ await waitFor(() =>
+ expect(h.elements).toEqual([
+ expect.objectContaining({ type: "text", text: "😀" }),
+ ]),
+ );
+ expect(h.state.toast?.message).toMatch(/^Content replaced\./);
+ });
+
+ it("Shift-drop keeps existing content and settings, remaps IDs, and can be undone", async () => {
+ const original = h.elements[0];
+ drag(GlobalTestState.interactiveCanvas, "dragenter");
+ drag(GlobalTestState.interactiveCanvas, "drop", {
+ files: [sceneFile()],
+ shiftKey: true,
+ });
+ expect(overlay()).toBeNull();
+ await waitFor(() => expect(h.elements).toHaveLength(2));
+ expect(h.state.toast).toBeNull();
+ expect(h.elements[0]).toEqual(original);
+ expect(h.elements[1].id).not.toBe(original.id);
+ expect(h.elements[1]).toMatchObject({ type: "ellipse", x: 150, y: 150 });
+ expect(h.state.viewBackgroundColor).toBe("#ffffff");
+ expect(h.state.selectedElementIds).toEqual({ [h.elements[1].id]: true });
+
+ await waitFor(() => expect(API.getUndoStack()).toHaveLength(1));
+ Keyboard.undo();
+ expect(h.app.scene.getNonDeletedElements()).toEqual([original]);
+ Keyboard.redo();
+ expect(h.app.scene.getNonDeletedElements()).toHaveLength(2);
+ });
+
+ it.each(["png", "svg"])(
+ "Shift-drop adds the scene embedded in a %s",
+ async (ext) => {
+ const file = await API.loadFile(`./fixtures/smiley_embedded_v2.${ext}`);
+ drag(GlobalTestState.interactiveCanvas, "drop", {
+ files: [file],
+ shiftKey: true,
+ });
+ await waitFor(() => expect(h.elements).toHaveLength(2));
+ expect(h.elements[0].id).toBe("existing");
+ expect(h.elements[1]).toMatchObject({ type: "text", text: "😀" });
+ },
+ );
+});
+
+describe("ignoring drops", () => {
+ it.each([
+ ["in view mode", { viewModeEnabled: true }],
+ ["when non-interactive", { interaction: false as const }],
+ ])(
+ "%s, cancels the browser default and changes nothing",
+ async (_, props) => {
+ await render(
+ <Excalidraw
+ {...props}
+ initialData={{
+ elements: [
+ API.createElement({ type: "rectangle", id: "existing" }),
+ ],
+ appState: { viewBackgroundColor: "#ffffff" },
+ }}
+ />,
+ );
+ const canvas = GlobalTestState.interactiveCanvas;
+ const original = h.elements[0];
+
+ drag(canvas, "dragenter");
+ const dragOver = drag(canvas, "dragover");
+ expect(dragOver.defaultPrevented).toBe(true);
+ expect(dragOver.dataTransfer.dropEffect).toBe("none");
+ expect(overlay()).toBeNull();
+
+ const drop = drag(canvas, "drop", { files: [sceneFile()] });
+ expect(drop.defaultPrevented).toBe(true);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(h.elements).toEqual([original]);
+ expect(h.state.viewBackgroundColor).toBe("#ffffff");
+ },
+ );
+});
+
+it("cancels file drags over a modal so the browser doesn't open the file", async () => {
+ await render(<Excalidraw />);
+ act(() => h.app.setState({ openDialog: { name: "help" } }));
+ const modal = await waitFor(() => {
+ const modal = document.querySelector(".excalidraw-modal-container .Modal");
+ expect(modal).not.toBeNull();
+ return modal!;
+ });
+ expect(GlobalTestState.interactiveCanvas.closest(".excalidraw")).not.toBe(
+ modal.closest(".excalidraw"),
+ );
+
+ const dragOver = drag(modal, "dragover");
+ expect(dragOver.defaultPrevented).toBe(true);
+ expect(dragOver.dataTransfer.dropEffect).toBe("none");
+ expect(drag(modal, "drop").defaultPrevented).toBe(true);
+
+ // text can still be dropped natively, e.g. into a modal's inputs
+ expect(
+ drag(modal, "dragover", { types: [MIME_TYPES.text] }).defaultPrevented,
+ ).toBe(false);
+});