Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(packages/excalidraw): support onDuplicate replacements, vetoes and lookups (#12124)

David Luzar14e1c614d477
diff --git a/packages/element/src/duplicate.ts b/packages/element/src/duplicate.ts
index affe3916ac..431186eb29 100644
--- a/packages/element/src/duplicate.ts
+++ b/packages/element/src/duplicate.ts
@@ -30,6 +30,7 @@ import { bumpVersion } from "./mutateElement";
import {
hasBoundTextElement,
+ isArrowElement,
isBoundToContainer,
isFrameLikeElement,
} from "./typeChecks";
@@ -38,16 +39,54 @@ import { getBoundTextElement, getContainerElement } from "./textElement";
import { fixDuplicatedBindingsAfterDuplication } from "./binding";
+import { ShapeCache } from "./shape";
+
import { isNonDeletedElement } from ".";
+import type { ElementUpdate } from "./mutateElement";
+
import type {
ElementsMap,
+ ExcalidrawArrowElement,
ExcalidrawElement,
GroupId,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "./types";
+/**
+ * Lookups supplied to the host's `props.onDuplicate`, covering just the
+ * elements taking part in the duplication.
+ */
+export type OnDuplicateData = {
+ /** the duplicates, by their id */
+ duplicateElements: ReadonlyMap<ExcalidrawElement["id"], ExcalidrawElement>;
+ /**
+ * The elements the duplicates were made from, by their id.
+ *
+ * On paste and library insert these are the inserted elements, which aren't
+ * part of the scene (though they may share ids with the scene elements they
+ * were copied from).
+ */
+ originalElements: ReadonlyMap<ExcalidrawElement["id"], ExcalidrawElement>;
+ /**
+ * id of an original -> id of its duplicate (e.g. to remap element ids you
+ * keep in `customData`, which the duplicate copied from its original)
+ */
+ origIdToDuplicateId: ReadonlyMap<
+ ExcalidrawElement["id"],
+ ExcalidrawElement["id"]
+ >;
+ /**
+ * id of a duplicate -> id of its original (e.g. to look up the original in
+ * `originalElements` while modifying the duplicate)
+ */
+ duplicateIdToOrigId: ReadonlyMap<
+ ExcalidrawElement["id"],
+ ExcalidrawElement["id"]
+ >;
+};
+
/**
* Duplicate an element, often used in the alt-drag operation.
* Note that this method has gotten a bit complicated since the
@@ -167,11 +206,12 @@ export const duplicateElements = (
ExcalidrawElement["id"],
ExcalidrawElement["id"]
>();
- const duplicateIdToOrigElement = new Map<
+ const duplicateIdToOrigId = new Map<
ExcalidrawElement["id"],
- ExcalidrawElement
+ ExcalidrawElement["id"]
>();
const duplicateElementsMap = new Map<string, NonDeletedExcalidrawElement>();
+ const origElementsMap = new Map<ExcalidrawElement["id"], ExcalidrawElement>();
const elementsMap = arrayToMap(elements) as ElementsMap;
const _idsOfElementsToDuplicate =
opts.type === "in-place"
@@ -231,8 +271,9 @@ export const duplicateElements = (
processedIds.set(newElement.id, true);
duplicateElementsMap.set(newElement.id, newElement);
+ origElementsMap.set(element.id, element);
origIdToDuplicateId.set(element.id, newElement.id);
- duplicateIdToOrigElement.set(newElement.id, element);
+ duplicateIdToOrigId.set(newElement.id, element.id);
origElements.push(element);
duplicatedElements.push(newElement);
@@ -411,7 +452,9 @@ export const duplicateElements = (
if (opts.overrides) {
for (const duplicateElement of duplicatedElements) {
- const origElement = duplicateIdToOrigElement.get(duplicateElement.id);
+ const origElement = origElementsMap.get(
+ duplicateIdToOrigId.get(duplicateElement.id)!,
+ );
if (origElement) {
Object.assign(
duplicateElement,
@@ -428,11 +471,150 @@ export const duplicateElements = (
return {
duplicatedElements,
duplicateElementsMap,
+ origElementsMap,
elementsWithDuplicates,
origIdToDuplicateId,
+ duplicateIdToOrigId,
};
};
+/**
+ * Folds the elements returned by the host (`props.onDuplicate`) back into the
+ * duplicates the editor created, so that everything that follows (frame
+ * assignment, bound text redraw, selection, alt-drag handover) can keep
+ * working with the editor's own objects, whether the host mutated the
+ * duplicates or returned new objects for them.
+ *
+ * - A returned element with a duplicate's id is shallow-merged into that
+ * duplicate, which takes its place in the returned array. Properties the
+ * host omits are kept, so that a partial element can't invalidate the
+ * duplicate. Safe only because the duplicates are fresh (not in the scene or
+ * the store snapshot yet), which is why nothing but the passed duplicates is
+ * ever merged into. Since the merge goes around `mutateElement`, what may
+ * have been cached for the duplicate by then is invalidated here.
+ * - A duplicate missing from the returned array (or returned as deleted) is
+ * vetoed. So is the bound text of a vetoed container. What the remaining
+ * duplicates reference of the vetoed ones is cleared, as if those were never
+ * part of the duplication (see `fixDuplicatedBindingsAfterDuplication`).
+ * - Any other returned element is used as is (existing elements must not be
+ * mutated, so the host replaces them).
+ * - `false` vetoes all the duplicates.
+ *
+ * @returns next elements, and the duplicates that weren't vetoed
+ */
+export const reconcileDuplicatedElements = <
+ TDuplicate extends ExcalidrawElement,
+>(
+ /** what the host returned from `props.onDuplicate`, if anything */
+ hostElements: readonly ExcalidrawElement[] | void | false,
+ /** elements that were passed to the host */
+ nextElements: ExcalidrawElement[],
+ duplicatedElements: TDuplicate[],
+): {
+ elements: ExcalidrawElement[];
+ duplicatedElements: TDuplicate[];
+} => {
+ if (hostElements === false) {
+ return { elements: nextElements, duplicatedElements: [] };
+ }
+
+ if (!hostElements) {
+ return { elements: nextElements, duplicatedElements };
+ }
+
+ const duplicatesMap = arrayToMap(duplicatedElements);
+ // (if a duplicate is returned more than once, the last one wins)
+ const hostDuplicates = new Map<ExcalidrawElement["id"], ExcalidrawElement>();
+
+ for (const element of hostElements) {
+ if (duplicatesMap.has(element.id)) {
+ hostDuplicates.set(element.id, element);
+ }
+ }
+
+ // merge first, so that everything below sees the duplicates as the host
+ // wants them (what the host returned may be partial)
+ const survivedIds = new Set<ExcalidrawElement["id"]>();
+
+ for (const [id, element] of hostDuplicates) {
+ const duplicate = duplicatesMap.get(id)!;
+
+ if (element !== duplicate) {
+ Object.assign(duplicate, element);
+ // The duplicate may have been measured already (e.g. to resolve the
+ // frame it's pasted into), and we're going around `mutateElement`.
+ // The shape is cached by identity, the bounds by version.
+ ShapeCache.delete(duplicate);
+ bumpVersion(duplicate);
+ }
+
+ if (!duplicate.isDeleted) {
+ survivedIds.add(id);
+ }
+ }
+
+ const isVetoed = (id: ExcalidrawElement["id"]) =>
+ duplicatesMap.has(id) && !survivedIds.has(id);
+
+ for (const id of survivedIds) {
+ const duplicate = duplicatesMap.get(id)!;
+ if (isBoundToContainer(duplicate) && isVetoed(duplicate.containerId)) {
+ survivedIds.delete(id);
+ }
+ }
+
+ const elements: ExcalidrawElement[] = [];
+
+ for (const element of hostElements) {
+ const duplicate = duplicatesMap.get(element.id);
+
+ if (!duplicate) {
+ elements.push(element);
+ } else if (
+ survivedIds.has(element.id) &&
+ hostDuplicates.get(element.id) === element
+ ) {
+ elements.push(duplicate);
+ }
+ }
+
+ if (survivedIds.size === duplicatedElements.length) {
+ return { elements, duplicatedElements };
+ }
+
+ const survivedDuplicates = duplicatedElements.filter((duplicate) =>
+ survivedIds.has(duplicate.id),
+ );
+
+ for (const duplicate of survivedDuplicates) {
+ const updates: Mutable<ElementUpdate<ExcalidrawArrowElement>> = {};
+
+ if (duplicate.boundElements?.some((binding) => isVetoed(binding.id))) {
+ updates.boundElements = duplicate.boundElements.filter(
+ (binding) => !isVetoed(binding.id),
+ );
+ }
+ if (duplicate.frameId && isVetoed(duplicate.frameId)) {
+ updates.frameId = null;
+ }
+ if (isArrowElement(duplicate)) {
+ if (
+ duplicate.startBinding &&
+ isVetoed(duplicate.startBinding.elementId)
+ ) {
+ updates.startBinding = null;
+ }
+ if (duplicate.endBinding && isVetoed(duplicate.endBinding.elementId)) {
+ updates.endBinding = null;
+ }
+ }
+
+ Object.assign(duplicate, updates);
+ }
+
+ return { elements, duplicatedElements: survivedDuplicates };
+};
+
// Simplified deep clone for the purpose of cloning ExcalidrawElement.
//
// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,
diff --git a/packages/excalidraw/CHANGELOG.md b/packages/excalidraw/CHANGELOG.md
index ac26f21d79..69463882a9 100644
--- a/packages/excalidraw/CHANGELOG.md
+++ b/packages/excalidraw/CHANGELOG.md
@@ -31,6 +31,14 @@ Please add the latest change on the top under the correct section.
## Excalidraw API
+### `onDuplicate` can replace and veto duplicates (2026-09-18) [#XXXX](https://github.com/excalidraw/excalidraw/pull/XXXX)
+
+- `props.onDuplicate` may now return new objects for the duplicated elements in every duplication path. Previously the editor kept using the objects it created, so on paste (and library insert) the frame assignment and bound text redraw went to objects that were no longer in the scene, and alt-drag dragged an element that wasn't in the scene. The returned changes are now merged into the editor's duplicates, so they're part of the duplication's own undo entry and durable increment (no follow-up `updateScene` needed).
+- When pasting or inserting onto a frame, the duplicates passed to `onDuplicate` already have their `frameId` set (and are ordered under the frame).
+- Omitting a duplicate from the returned array (or returning it as deleted) now reliably prevents that element from being duplicated — previously pasting over a frame brought it back, and alt-drag broke. References to it from the remaining duplicates (bindings, `boundElements`, `frameId`) are cleared, and a bound text isn't duplicated without its container. If no duplicate remains, the duplication is cancelled and the returned elements are ignored: paste and the duplicate action do nothing, and alt-drag moves the original elements instead. When only some duplicates are vetoed during alt-drag, their originals stay where they were.
+- `onDuplicate` may return `false` to prevent the duplication as a whole (same as omitting every duplicate, without having to find them).
+- `onDuplicate` receives a third argument with lookups covering just the elements taking part in the duplication, so you don't have to derive them by scanning the scene: `{ duplicateElements, originalElements, origIdToDuplicateId, duplicateIdToOrigId }` — the duplicates by id, the elements they were made from by id, and their ids mapped in both directions (`duplicateIdToOrigId` to look up a duplicate's original while modifying it, `origIdToDuplicateId` e.g. for remapping element ids you keep in `customData`). On paste and library insert the originals are the inserted elements, which aren't part of the scene. The maps are read-only.
+
### Host-controlled active tool (2026-07-14) [#11665](https://github.com/excalidraw/excalidraw/pull/11665)
- Added `activeTool` prop (`{ type: ToolType } | { type: "custom"; customType: string }`) for forcing the active editor tool (controlled). While set, user- and API-driven tool switching is ignored — `setActiveTool` refuses non-matching activations with a console warning, non-forced toolbar buttons render disabled, and the tool-lock toggle (`Q`) is inert — and the editor snaps back if internal flows reset the tool (e.g. `restore()` on scene load). The forced tool behaves as if locked — it doesn't revert to selection after use and drawn elements aren't auto-selected — without mutating `appState.activeTool.locked`, so the user's persisted padlock preference stays untouched. Unset the prop to return tool control to the editor (the current tool stays active). The forced tool must be activatable to take effect — not disabled via `UIOptions.tools`, and (while non-interactive) allowed via `interaction.enabled.tools`; otherwise the editor stays on the `selection` tool and applies the forced tool once it becomes activatable. `image` cannot be forced (its activation opens the file picker). Composes with `interaction.enabled.tools` for presentation-style hosts: force `laser` for the presenter, `selection` + `interaction={false}` for viewers.
diff --git a/packages/excalidraw/actions/actionDuplicateSelection.tsx b/packages/excalidraw/actions/actionDuplicateSelection.tsx
index 21d48ffd8e..7af6cfc74b 100644
--- a/packages/excalidraw/actions/actionDuplicateSelection.tsx
+++ b/packages/excalidraw/actions/actionDuplicateSelection.tsx
@@ -16,7 +16,10 @@ import {
import { syncMovedIndices } from "@excalidraw/element";
-import { duplicateElements } from "@excalidraw/element";
+import {
+ duplicateElements,
+ reconcileDuplicatedElements,
+} from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
@@ -60,7 +63,7 @@ export const actionDuplicateSelection = register({
}
}
- let { duplicatedElements, elementsWithDuplicates } = duplicateElements({
+ const duplication = duplicateElements({
type: "in-place",
elements,
idsOfElementsToDuplicate: arrayToMap(
@@ -82,13 +85,24 @@ export const actionDuplicateSelection = register({
},
});
- if (app.props.onDuplicate && elementsWithDuplicates) {
- const mappedElements = app.props.onDuplicate(
- elementsWithDuplicates,
- elements,
- );
- if (mappedElements) {
- elementsWithDuplicates = mappedElements;
+ let { duplicatedElements, elementsWithDuplicates } = duplication;
+
+ if (app.props.onDuplicate) {
+ ({ elements: elementsWithDuplicates, duplicatedElements } =
+ reconcileDuplicatedElements(
+ app.props.onDuplicate(elementsWithDuplicates, elements, {
+ duplicateElements: duplication.duplicateElementsMap,
+ originalElements: duplication.origElementsMap,
+ origIdToDuplicateId: duplication.origIdToDuplicateId,
+ duplicateIdToOrigId: duplication.duplicateIdToOrigId,
+ }),
+ elementsWithDuplicates,
+ duplicatedElements,
+ ));
+
+ // host vetoed the duplication
+ if (!duplicatedElements.length) {
+ return false;
}
}
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index c730c7023e..3b8dfbc525 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -136,6 +136,7 @@ import {
refreshTextDimensions,
deepCopyElement,
duplicateElements,
+ reconcileDuplicatedElements,
hasBoundTextElement,
isArrowElement,
isBindingElement,
@@ -4853,7 +4854,7 @@ class App extends React.Component<AppProps, AppState> {
const [gridX, gridY] = getGridPoint(dx, dy, this.getEffectiveGridSize());
- const { duplicatedElements } = duplicateElements({
+ const duplication = duplicateElements({
type: "everything",
elements: elements.map((element) => {
return newElementWith(element, {
@@ -4864,6 +4865,7 @@ class App extends React.Component<AppProps, AppState> {
randomizeSeed: !opts.retainSeed,
preserveFrameChildrenOrder: opts.preserveFrameChildrenOrder,
});
+ let { duplicatedElements } = duplication;
const prevElements = this.scene.getElementsIncludingDeleted();
let nextElements: ExcalidrawElement[] = [
@@ -4871,15 +4873,10 @@ class App extends React.Component<AppProps, AppState> {
...duplicatedElements,
];
- const mappedNewSceneElements = this.props.onDuplicate?.(
- nextElements,
- prevElements,
- );
-
- nextElements = mappedNewSceneElements || nextElements;
-
syncMovedIndices(nextElements, arrayToMap(duplicatedElements));
+ // resolved ahead of `onDuplicate` so that the host sees the duplicates
+ // the way they end up in the scene
const topLayerFrame = this.getTopLayerFrameAtSceneCoords({ x, y });
if (topLayerFrame) {
@@ -4894,6 +4891,28 @@ class App extends React.Component<AppProps, AppState> {
);
}
+ if (this.props.onDuplicate) {
+ ({ elements: nextElements, duplicatedElements } =
+ reconcileDuplicatedElements(
+ this.props.onDuplicate(nextElements, prevElements, {
+ duplicateElements: duplication.duplicateElementsMap,
+ originalElements: duplication.origElementsMap,
+ origIdToDuplicateId: duplication.origIdToDuplicateId,
+ duplicateIdToOrigId: duplication.duplicateIdToOrigId,
+ }),
+ nextElements,
+ duplicatedElements,
+ ));
+
+ // host vetoed the duplication
+ if (!duplicatedElements.length) {
+ return;
+ }
+
+ // host may have reordered the elements
+ syncMovedIndices(nextElements, arrayToMap(duplicatedElements));
+ }
+
this.scene.replaceAllElements(nextElements);
duplicatedElements.forEach((newElement) => {
@@ -11189,10 +11208,12 @@ class App extends React.Component<AppProps, AppState> {
);
const {
- duplicatedElements,
- duplicateElementsMap,
+ duplicatedElements: _duplicatedElements,
+ duplicateElementsMap: _duplicateElementsMap,
+ origElementsMap,
elementsWithDuplicates,
origIdToDuplicateId,
+ duplicateIdToOrigId,
} = duplicateElements({
type: "in-place",
elements,
@@ -11212,35 +11233,57 @@ class App extends React.Component<AppProps, AppState> {
};
},
});
- duplicatedElements.forEach((element) => {
- pointerDownState.originalElements.set(
- element.id,
- deepCopyElement(element),
- );
- });
const mappedClonedElements = elementsWithDuplicates.map((el) => {
if (idsOfElementsToDuplicate.has(el.id)) {
const origEl = pointerDownState.originalElements.get(el.id);
if (origEl) {
- return newElementWith(el, {
+ const resetElement = newElementWith(el, {
x: origEl.x,
y: origEl.y,
});
+ // so that the host gets the originals as they are in the
+ // next elements
+ if (origElementsMap.has(el.id)) {
+ origElementsMap.set(el.id, resetElement);
+ }
+ return resetElement;
}
}
return el;
});
- const mappedNewSceneElements = this.props.onDuplicate?.(
- mappedClonedElements,
- elements,
- );
+ const { elements: nextElements, duplicatedElements } =
+ reconcileDuplicatedElements(
+ this.props.onDuplicate?.(mappedClonedElements, elements, {
+ duplicateElements: _duplicateElementsMap,
+ originalElements: origElementsMap,
+ origIdToDuplicateId,
+ duplicateIdToOrigId,
+ }),
+ mappedClonedElements,
+ _duplicatedElements,
+ );
+
+ // host vetoed the duplication, so we keep dragging the originals
+ if (!duplicatedElements.length) {
+ return;
+ }
+
+ // (originals whose duplicates were vetoed are left behind)
+ const duplicateElementsMap = arrayToMap(duplicatedElements);
+
+ duplicatedElements.forEach((element) => {
+ pointerDownState.originalElements.set(
+ element.id,
+ deepCopyElement(element),
+ );
+ });
const elementsWithIndices = syncMovedIndices(
- mappedNewSceneElements || mappedClonedElements,
- arrayToMap(duplicatedElements),
+ nextElements,
+ duplicateElementsMap,
);
// we need to update synchronously so as to keep pointerDownState,
diff --git a/packages/excalidraw/tests/onDuplicate.test.tsx b/packages/excalidraw/tests/onDuplicate.test.tsx
new file mode 100644
index 0000000000..dd016a37b1
--- /dev/null
+++ b/packages/excalidraw/tests/onDuplicate.test.tsx
@@ -0,0 +1,816 @@
+import React from "react";
+import { vi } from "vitest";
+
+import { KEYS, ORIG_ID } from "@excalidraw/common";
+
+import {
+ getElementBounds,
+ newElementWith,
+ reconcileDuplicatedElements,
+ duplicateElements,
+} from "@excalidraw/element";
+
+import { pointFrom } from "@excalidraw/math";
+
+import type { LocalPoint } from "@excalidraw/math";
+
+import type {
+ ExcalidrawArrowElement,
+ ExcalidrawElement,
+ NonDeletedExcalidrawElement,
+} from "@excalidraw/element/types";
+
+import { actionDuplicateSelection } from "../actions";
+import { createPasteEvent, serializeAsClipboardJSON } from "../clipboard";
+import { Excalidraw } from "../index";
+
+import { API } from "./helpers/api";
+import { Pointer, Keyboard } from "./helpers/ui";
+import {
+ act,
+ assertElements,
+ getCloneByOrigId,
+ render,
+ waitFor,
+ GlobalTestState,
+ unmountComponent,
+} from "./test-utils";
+
+import type { ExcalidrawProps, NormalizedZoomValue } from "../types";
+
+const { h } = window;
+
+const mouse = new Pointer("mouse");
+
+vi.mock("@excalidraw/common", async (importOriginal) => {
+ const module = await importOriginal<typeof import("@excalidraw/common")>();
+ const { mockThrottleRAF } = await import("./helpers/mocks");
+
+ return {
+ __esmodule: true,
+ ...module,
+ isDarwin: false,
+ KEYS: {
+ ...module.KEYS,
+ CTRL_OR_CMD: "ctrlKey",
+ },
+ throttleRAF: mockThrottleRAF,
+ };
+});
+
+type OnDuplicate = NonNullable<ExcalidrawProps["onDuplicate"]>;
+
+const isDuplicate = (
+ element: ExcalidrawElement,
+ prevElements: readonly ExcalidrawElement[],
+) => !prevElements.some((prevElement) => prevElement.id === element.id);
+
+/** returns new objects for every duplicate */
+const stampDuplicates: OnDuplicate = (nextElements, prevElements) =>
+ nextElements.map((element) =>
+ isDuplicate(element, prevElements)
+ ? newElementWith(element, {
+ customData: { stamped: true, frameId: element.frameId },
+ })
+ : element,
+ );
+
+/** vetoes duplicates of elements with the supplied ids */
+const vetoDuplicatesOf =
+ (...origIds: ExcalidrawElement["id"][]): OnDuplicate =>
+ (nextElements, prevElements) =>
+ nextElements.filter(
+ (element) =>
+ !isDuplicate(element, prevElements) ||
+ !origIds.includes((element as any)[ORIG_ID]),
+ );
+
+const renderWithOnDuplicate = async (onDuplicate: OnDuplicate) => {
+ await render(
+ <Excalidraw
+ autoFocus={true}
+ handleKeyboardGlobally={true}
+ initialData={{ appState: { zoom: { value: 1 as NormalizedZoomValue } } }}
+ onDuplicate={onDuplicate}
+ />,
+ );
+ Object.assign(document, {
+ elementFromPoint: () => GlobalTestState.canvas,
+ });
+};
+
+const paste = async (elements: readonly NonDeletedExcalidrawElement[]) => {
+ const clipboardJSON = await serializeAsClipboardJSON({
+ elements,
+ files: null,
+ });
+ Keyboard.withModifierKeys({ ctrl: true }, () => {
+ Keyboard.keyPress(KEYS.V);
+ document.dispatchEvent(
+ createPasteEvent({ types: { "text/plain": clipboardJSON } }),
+ );
+ });
+};
+
+const altDrag = (element: ExcalidrawElement, offset: number) => {
+ const x = element.x + element.width / 2;
+ const y = element.y + element.height / 2;
+ Keyboard.withModifierKeys({ alt: true }, () => {
+ mouse.downAt(x, y);
+ mouse.moveTo(x + offset / 2, y + offset / 2);
+ mouse.moveTo(x + offset, y + offset);
+ mouse.up();
+ });
+};
+
+const createFrame = () =>
+ API.createElement({
+ type: "frame",
+ x: 0,
+ y: 0,
+ width: 400,
+ height: 400,
+ });
+
+beforeEach(() => {
+ unmountComponent();
+ localStorage.clear();
+ mouse.reset();
+});
+
+describe("props.onDuplicate returning new objects for duplicates", () => {
+ beforeEach(async () => {
+ await renderWithOnDuplicate(stampDuplicates);
+ });
+
+ it("duplicate action", () => {
+ const rectangle = API.createElement({ type: "rectangle" });
+ API.setElements([rectangle]);
+ API.setSelectedElements([rectangle]);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionDuplicateSelection);
+ });
+
+ assertElements(h.elements, [
+ { id: rectangle.id },
+ {
+ [ORIG_ID]: rectangle.id,
+ selected: true,
+ customData: { stamped: true, frameId: null },
+ },
+ ]);
+ });
+
+ it("alt-drag", () => {
+ const rectangle = API.createElement({
+ type: "rectangle",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ });
+ API.setElements([rectangle]);
+
+ mouse.select(rectangle);
+ altDrag(rectangle, 50);
+
+ assertElements(h.elements, [
+ { id: rectangle.id, x: 0, y: 0 },
+ {
+ [ORIG_ID]: rectangle.id,
+ selected: true,
+ x: 50,
+ y: 50,
+ customData: { stamped: true, frameId: null },
+ },
+ ]);
+ });
+
+ it("alt-drag of a container with bound text", () => {
+ const [container, text] = API.createTextContainer();
+ API.setElements([container, text]);
+
+ expect([container.x, container.y, text.x, text.y]).toEqual([0, 0, 0, 0]);
+
+ mouse.select(container);
+ altDrag(container, 50);
+
+ const containerDuplicate = getCloneByOrigId(container.id);
+ const textDuplicate = getCloneByOrigId(text.id);
+
+ assertElements(h.elements, [
+ { id: container.id, x: 0, y: 0 },
+ { id: text.id, x: 0, y: 0, containerId: container.id },
+ {
+ [ORIG_ID]: container.id,
+ selected: true,
+ x: 50,
+ y: 50,
+ boundElements: [{ type: "text", id: textDuplicate.id }],
+ customData: { stamped: true, frameId: null },
+ },
+ {
+ [ORIG_ID]: text.id,
+ x: 50,
+ y: 50,
+ containerId: containerDuplicate.id,
+ customData: { stamped: true, frameId: null },
+ },
+ ]);
+ });
+
+ it("paste over a frame", async () => {
+ const frame = createFrame();
+ const [container, text] = API.createTextContainer();
+ API.setElements([frame]);
+
+ mouse.moveTo(200, 200);
+ // bound text which needs to be redrawn to fit its container
+ await paste([container, newElementWith(text, { x: -50, y: -50 })]);
+
+ await waitFor(() => {
+ expect(h.elements.length).toBe(3);
+ });
+
+ const containerDuplicate = getCloneByOrigId(container.id);
+ const textDuplicate = getCloneByOrigId(text.id);
+
+ assertElements(h.elements, [
+ {
+ [ORIG_ID]: container.id,
+ selected: true,
+ frameId: frame.id,
+ // host sees the duplicates already assigned to the frame
+ customData: { stamped: true, frameId: frame.id },
+ },
+ {
+ [ORIG_ID]: text.id,
+ frameId: frame.id,
+ containerId: containerDuplicate.id,
+ customData: { stamped: true, frameId: frame.id },
+ },
+ { id: frame.id },
+ ]);
+
+ expect(textDuplicate.x).toBeGreaterThan(containerDuplicate.x);
+ expect(textDuplicate.y).toBeGreaterThan(containerDuplicate.y);
+ expect(textDuplicate.x + textDuplicate.width).toBeLessThan(
+ containerDuplicate.x + containerDuplicate.width,
+ );
+ });
+});
+
+describe("props.onDuplicate changing already measured duplicates", () => {
+ // pasting over a frame measures the duplicates (generating their shapes)
+ // ahead of the callback
+ it("should not keep stale shapes or bounds", async () => {
+ await renderWithOnDuplicate((nextElements, prevElements) =>
+ nextElements.map((element) => {
+ if (!isDuplicate(element, prevElements)) {
+ return element;
+ }
+ return element.type === "arrow"
+ ? newElementWith(element, {
+ strokeColor: "#ff0000",
+ width: 200,
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(200, 0),
+ ],
+ })
+ : // partial element (version isn't bumped)
+ ({ id: element.id, width: 50 } as ExcalidrawElement);
+ }),
+ );
+
+ const frame = createFrame();
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
+ });
+ const rectangle = API.createElement({
+ type: "rectangle",
+ x: 0,
+ y: 50,
+ width: 100,
+ height: 100,
+ });
+ API.setElements([frame]);
+
+ mouse.moveTo(200, 200);
+ await paste([arrow, rectangle]);
+
+ await waitFor(() => {
+ expect(h.elements.length).toBe(3);
+ });
+
+ const elementsMap = h.app.scene.getNonDeletedElementsMap();
+ const getWidth = (element: ExcalidrawElement) => {
+ const [x1, , x2] = getElementBounds(element, elementsMap);
+ return Math.round(x2 - x1);
+ };
+
+ const arrowDuplicate = getCloneByOrigId(arrow.id);
+ const rectangleDuplicate = getCloneByOrigId(rectangle.id);
+
+ expect(arrowDuplicate.frameId).toBe(frame.id);
+ expect(getWidth(arrowDuplicate)).toBe(200);
+ expect(getWidth(rectangleDuplicate)).toBe(50);
+ });
+});
+
+describe("props.onDuplicate vetoing duplicates", () => {
+ const createRectangles = () => {
+ const rectangle1 = API.createElement({
+ id: "rectangle1",
+ type: "rectangle",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ });
+ const rectangle2 = API.createElement({
+ id: "rectangle2",
+ type: "rectangle",
+ x: 200,
+ y: 0,
+ width: 100,
+ height: 100,
+ });
+ return [rectangle1, rectangle2] as const;
+ };
+
+ describe("some", () => {
+ beforeEach(async () => {
+ await renderWithOnDuplicate(vetoDuplicatesOf("rectangle1"));
+ });
+
+ it("duplicate action", () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ API.setElements([rectangle1, rectangle2]);
+ API.setSelectedElements([rectangle1, rectangle2]);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionDuplicateSelection);
+ });
+
+ assertElements(h.elements, [
+ { id: rectangle1.id },
+ { id: rectangle2.id },
+ { [ORIG_ID]: rectangle2.id, selected: true },
+ ]);
+ });
+
+ it("alt-drag leaves the original behind", () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ API.setElements([rectangle1, rectangle2]);
+ API.setSelectedElements([rectangle1, rectangle2]);
+
+ altDrag(rectangle1, 50);
+
+ assertElements(h.elements, [
+ { id: rectangle1.id, x: 0, y: 0 },
+ { id: rectangle2.id, x: 200, y: 0 },
+ { [ORIG_ID]: rectangle2.id, selected: true, x: 250, y: 50 },
+ ]);
+ });
+
+ it("paste over a frame", async () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ const frame = createFrame();
+ API.setElements([frame]);
+
+ mouse.moveTo(200, 200);
+ await paste([rectangle1, rectangle2]);
+
+ await waitFor(() => {
+ expect(h.elements.length).toBe(2);
+ });
+
+ assertElements(h.elements, [
+ { [ORIG_ID]: rectangle2.id, selected: true, frameId: frame.id },
+ { id: frame.id },
+ ]);
+ });
+ });
+
+ describe.each([
+ ["by omitting them", vetoDuplicatesOf("rectangle1", "rectangle2")],
+ ["by returning false", (() => false) as OnDuplicate],
+ ])("all, %s", (_, handler) => {
+ const onDuplicate = vi.fn(handler);
+
+ beforeEach(async () => {
+ onDuplicate.mockClear();
+ await renderWithOnDuplicate(onDuplicate);
+ });
+
+ it("duplicate action", () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ API.setElements([rectangle1, rectangle2]);
+ API.setSelectedElements([rectangle1, rectangle2]);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionDuplicateSelection);
+ });
+
+ expect(onDuplicate).toHaveBeenCalledTimes(1);
+ expect(API.getUndoStack().length).toBe(0);
+ assertElements(h.elements, [
+ { id: rectangle1.id, selected: true },
+ { id: rectangle2.id, selected: true },
+ ]);
+ });
+
+ it("alt-drag moves the originals", () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ API.setElements([rectangle1, rectangle2]);
+ API.setSelectedElements([rectangle1, rectangle2]);
+
+ altDrag(rectangle1, 50);
+
+ expect(onDuplicate).toHaveBeenCalledTimes(1);
+ assertElements(h.elements, [
+ { id: rectangle1.id, selected: true, x: 50, y: 50 },
+ { id: rectangle2.id, selected: true, x: 250, y: 50 },
+ ]);
+ });
+
+ it("paste over a frame", async () => {
+ const [rectangle1, rectangle2] = createRectangles();
+ const frame = createFrame();
+ API.setElements([frame]);
+
+ mouse.moveTo(200, 200);
+ await paste([rectangle1, rectangle2]);
+
+ await waitFor(() => {
+ expect(onDuplicate).toHaveBeenCalledTimes(1);
+ });
+
+ expect(API.getUndoStack().length).toBe(0);
+ assertElements(h.elements, [{ id: frame.id }]);
+ });
+ });
+});
+
+describe("props.onDuplicate data", () => {
+ const onDuplicate = vi.fn<OnDuplicate>();
+
+ const getCall = () => {
+ expect(onDuplicate).toHaveBeenCalledTimes(1);
+ const [nextElements, prevElements, data] = onDuplicate.mock.calls[0];
+ return { nextElements, prevElements, ...data };
+ };
+
+ beforeEach(async () => {
+ onDuplicate.mockClear();
+ await renderWithOnDuplicate(onDuplicate);
+ });
+
+ it("duplicate action", () => {
+ const [container, text] = API.createTextContainer();
+ const rectangle = API.createElement({ type: "rectangle" });
+ API.setElements([container, text, rectangle]);
+ API.setSelectedElements([container]);
+
+ act(() => {
+ h.app.actionManager.executeAction(actionDuplicateSelection);
+ });
+
+ const {
+ duplicateElements,
+ originalElements,
+ origIdToDuplicateId,
+ duplicateIdToOrigId,
+ } = getCall();
+
+ const containerDuplicate = getCloneByOrigId(container.id);
+ const textDuplicate = getCloneByOrigId(text.id);
+
+ // only what takes part in the duplication
+ expect([...originalElements]).toEqual([
+ [container.id, container],
+ [text.id, text],
+ ]);
+ expect([...duplicateElements.keys()]).toEqual([
+ containerDuplicate.id,
+ textDuplicate.id,
+ ]);
+ expect(duplicateElements.get(containerDuplicate.id)).toBe(
+ containerDuplicate,
+ );
+ expect([...origIdToDuplicateId]).toEqual([
+ [container.id, containerDuplicate.id],
+ [text.id, textDuplicate.id],
+ ]);
+ expect([...duplicateIdToOrigId]).toEqual([
+ [containerDuplicate.id, container.id],
+ [textDuplicate.id, text.id],
+ ]);
+ // the original of a duplicate
+ expect(
+ originalElements.get(duplicateIdToOrigId.get(textDuplicate.id)!),
+ ).toBe(text);
+ });
+
+ it("alt-drag supplies the originals as they are in next elements", () => {
+ const rectangle = API.createElement({
+ type: "rectangle",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ });
+ API.setElements([rectangle]);
+
+ mouse.select(rectangle);
+ altDrag(rectangle, 50);
+
+ const { nextElements, duplicateElements, originalElements } = getCall();
+
+ expect(originalElements.size).toBe(1);
+ expect(originalElements.get(rectangle.id)).toBe(
+ nextElements.find((element) => element.id === rectangle.id),
+ );
+ expect(originalElements.get(rectangle.id)).toMatchObject({ x: 0, y: 0 });
+ expect([...duplicateElements.values()]).toEqual([
+ getCloneByOrigId(rectangle.id),
+ ]);
+ });
+
+ it("paste supplies the pasted elements as originals", async () => {
+ const rectangle = API.createElement({ id: "rectangle", type: "rectangle" });
+ API.setElements([rectangle]);
+
+ await paste([rectangle]);
+
+ await waitFor(() => {
+ expect(h.elements.length).toBe(2);
+ });
+
+ const { prevElements, originalElements, origIdToDuplicateId } = getCall();
+
+ const original = originalElements.get(rectangle.id)!;
+ expect(prevElements).toEqual([rectangle]);
+ // the pasted element, not the scene element it was copied from
+ expect(original).not.toBe(rectangle);
+ expect(h.elements).not.toContain(original);
+ expect(origIdToDuplicateId.get(rectangle.id)).toBe(
+ getCloneByOrigId(rectangle.id).id,
+ );
+ });
+});
+
+describe("reconcileDuplicatedElements()", () => {
+ const duplicate = (elements: readonly ExcalidrawElement[]) => {
+ const { duplicatedElements } = duplicateElements({
+ type: "everything",
+ elements,
+ });
+ const byOrigId = (origId: ExcalidrawElement["id"]) =>
+ duplicatedElements.find(
+ (element) => (element as any)[ORIG_ID] === origId,
+ )!;
+ return { duplicatedElements, byOrigId };
+ };
+
+ it("should return the supplied elements if host returns nothing", () => {
+ const rectangle = API.createElement({ type: "rectangle" });
+ const { duplicatedElements } = duplicate([rectangle]);
+ const nextElements = [rectangle, ...duplicatedElements];
+
+ const result = reconcileDuplicatedElements(
+ undefined,
+ nextElements,
+ duplicatedElements,
+ );
+
+ expect(result.elements).toBe(nextElements);
+ expect(result.duplicatedElements).toBe(duplicatedElements);
+ });
+
+ it("should veto all duplicates if host returns false", () => {
+ const rectangle = API.createElement({ type: "rectangle" });
+ const { duplicatedElements } = duplicate([rectangle]);
+ const nextElements = [rectangle, ...duplicatedElements];
+
+ const result = reconcileDuplicatedElements(
+ false,
+ nextElements,
+ duplicatedElements,
+ );
+
+ expect(result.duplicatedElements).toEqual([]);
+ });
+
+ it("should merge into duplicates, and replace other elements", () => {
+ const rectangle = newElementWith(API.createElement({ type: "rectangle" }), {
+ customData: { a: 1 },
+ });
+ const { duplicatedElements } = duplicate([rectangle]);
+ const [rectangleDuplicate] = duplicatedElements;
+
+ const hostRectangle = newElementWith(rectangle, { locked: true });
+
+ const result = reconcileDuplicatedElements(
+ [
+ hostRectangle,
+ newElementWith(rectangleDuplicate, {
+ link: "https://excalidraw.com",
+ customData: { b: 2 },
+ }),
+ ],
+ [rectangle, rectangleDuplicate],
+ duplicatedElements,
+ );
+
+ expect(result.elements[0]).toBe(hostRectangle);
+ expect(rectangle.locked).toBe(false);
+
+ expect(result.elements[1]).toBe(rectangleDuplicate);
+ expect(result.duplicatedElements).toEqual([rectangleDuplicate]);
+ expect(rectangleDuplicate.link).toBe("https://excalidraw.com");
+ // shallow merge (nested objects are replaced)
+ expect(rectangleDuplicate.customData).toEqual({ b: 2 });
+ });
+
+ it("should keep properties omitted by the host", () => {
+ const rectangle = API.createElement({ type: "rectangle", x: 0 });
+ const { duplicatedElements } = duplicate([rectangle]);
+ const [rectangleDuplicate] = duplicatedElements;
+ const expected = { ...rectangleDuplicate, x: 100 };
+
+ const result = reconcileDuplicatedElements(
+ [
+ rectangle,
+ { id: rectangleDuplicate.id, x: 100 } as unknown as ExcalidrawElement,
+ ],
+ [rectangle, rectangleDuplicate],
+ duplicatedElements,
+ );
+
+ expect(result.elements[1]).toBe(rectangleDuplicate);
+ expect(rectangleDuplicate).toEqual({
+ ...expected,
+ // bumped, so that what's cached by version is invalidated
+ version: expected.version + 1,
+ versionNonce: expect.any(Number),
+ updated: expect.any(Number),
+ });
+ });
+
+ it("should veto duplicates returned as deleted", () => {
+ const rectangle = API.createElement({ type: "rectangle" });
+ const { duplicatedElements } = duplicate([rectangle]);
+
+ const result = reconcileDuplicatedElements(
+ [
+ rectangle,
+ newElementWith<ExcalidrawElement>(duplicatedElements[0], {
+ isDeleted: true,
+ }),
+ ],
+ [rectangle, ...duplicatedElements],
+ duplicatedElements,
+ );
+
+ expect(result.elements).toEqual([rectangle]);
+ expect(result.duplicatedElements).toEqual([]);
+ });
+
+ it("should veto bound text of a vetoed container", () => {
+ const rectangle = API.createElement({
+ id: "rectangle",
+ type: "rectangle",
+ boundElements: [{ type: "text", id: "text" }],
+ });
+ const text = API.createElement({
+ id: "text",
+ type: "text",
+ containerId: rectangle.id,
+ });
+ const { duplicatedElements, byOrigId } = duplicate([rectangle, text]);
+ const nextElements = [rectangle, text, ...duplicatedElements];
+
+ const result = reconcileDuplicatedElements(
+ nextElements.filter((element) => element !== byOrigId(rectangle.id)),
+ nextElements,
+ duplicatedElements,
+ );
+
+ expect(result.elements).toEqual([rectangle, text]);
+ expect(result.duplicatedElements).toEqual([]);
+ });
+
+ it("should veto bound text of a vetoed container (partial element)", () => {
+ const rectangle = API.createElement({
+ id: "rectangle",
+ type: "rectangle",
+ boundElements: [{ type: "text", id: "text" }],
+ });
+ const text = API.createElement({
+ id: "text",
+ type: "text",
+ containerId: rectangle.id,
+ });
+ const { duplicatedElements, byOrigId } = duplicate([rectangle, text]);
+
+ const result = reconcileDuplicatedElements(
+ [
+ rectangle,
+ text,
+ {
+ id: byOrigId(text.id).id,
+ text: "changed",
+ } as unknown as ExcalidrawElement,
+ ],
+ [rectangle, text, ...duplicatedElements],
+ duplicatedElements,
+ );
+
+ expect(result.elements).toEqual([rectangle, text]);
+ expect(result.duplicatedElements).toEqual([]);
+ });
+
+ it("should clear references to vetoed duplicates", () => {
+ const frame = API.createElement({ id: "frame", type: "frame" });
+ const rectangle = API.createElement({
+ id: "rectangle",
+ type: "rectangle",
+ frameId: frame.id,
+ boundElements: [
+ { type: "text", id: "text" },
+ { type: "arrow", id: "arrow" },
+ ],
+ });
+ const text = API.createElement({
+ id: "text",
+ type: "text",
+ frameId: frame.id,
+ containerId: rectangle.id,
+ });
+ const ellipse = API.createElement({
+ id: "ellipse",
+ type: "ellipse",
+ boundElements: [{ type: "arrow", id: "arrow" }],
+ });
+ const arrow = API.createElement({
+ id: "arrow",
+ type: "arrow",
+ startBinding: {
+ elementId: rectangle.id,
+ fixedPoint: [0.5, 0.5],
+ mode: "orbit",
+ },
+ endBinding: {
+ elementId: ellipse.id,
+ fixedPoint: [0.5, 0.5],
+ mode: "orbit",
+ },
+ });
+ const elements = [rectangle, text, frame, ellipse, arrow];
+ const { duplicatedElements, byOrigId } = duplicate(elements);
+ const nextElements = [...elements, ...duplicatedElements];
+
+ // sanity check
+ expect(byOrigId(rectangle.id).frameId).toBe(byOrigId(frame.id).id);
+
+ const vetoed = [
+ byOrigId(frame.id),
+ byOrigId(text.id),
+ byOrigId(ellipse.id),
+ ];
+
+ const result = reconcileDuplicatedElements(
+ nextElements.filter((element) => !vetoed.includes(element as any)),
+ nextElements,
+ duplicatedElements,
+ );
+
+ const rectangleDuplicate = byOrigId(rectangle.id);
+ const arrowDuplicate = byOrigId(arrow.id) as ExcalidrawArrowElement;
+
+ expect(result.elements).toEqual([
+ ...elements,
+ rectangleDuplicate,
+ arrowDuplicate,
+ ]);
+ expect(result.duplicatedElements).toEqual([
+ rectangleDuplicate,
+ arrowDuplicate,
+ ]);
+
+ expect(rectangleDuplicate.frameId).toBe(null);
+ expect(rectangleDuplicate.boundElements).toEqual([
+ { type: "arrow", id: arrowDuplicate.id },
+ ]);
+ expect(arrowDuplicate.startBinding?.elementId).toBe(rectangleDuplicate.id);
+ expect(arrowDuplicate.endBinding).toBe(null);
+ });
+});
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index e719119dd5..995c5c67c4 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -49,6 +49,7 @@ import type {
CaptureUpdateActionType,
DurableIncrement,
EphemeralIncrement,
+ OnDuplicateData,
} from "@excalidraw/element";
import type { GlobalPoint } from "@excalidraw/math";
@@ -881,13 +882,29 @@ export interface ExcalidrawProps {
*
* Returned elements will be used in place of the next elements
* (you should return all elements, including deleted, and not mutate
- * the element if changes are made)
+ * the element if changes are made).
+ *
+ * The duplicates are the elements in `nextElements` which are not in
+ * `prevElements` (see also `data.duplicateElements`). When pasting or
+ * inserting onto a frame, their `frameId` is already set. To change a
+ * duplicate, return a new object with the same `id`. It is shallow-merged
+ * into the duplicate (omitted properties are kept), and your changes are
+ * part of the duplication itself (same undo entry, same durable increment).
+ *
+ * To prevent an element from being duplicated, omit its duplicate from the
+ * returned array. References to it from the remaining duplicates are
+ * cleared, and a bound text isn't duplicated without its container. To
+ * prevent the duplication as a whole, return `false`. If no duplicate
+ * remains, the duplication is cancelled and the returned elements are
+ * ignored (alt-drag then moves the original elements instead).
*/
onDuplicate?: (
nextElements: readonly ExcalidrawElement[],
/** excludes the duplicated elements */
prevElements: readonly ExcalidrawElement[],
- ) => ExcalidrawElement[] | void;
+ /** lookups covering just the elements taking part in the duplication */
+ data: OnDuplicateData,
+ ) => ExcalidrawElement[] | void | false;
renderTopLeftUI?: (
isMobile: boolean,
appState: UIAppState,