Virtual whiteboard for sketching hand-drawn like diagrams
refactor(editor): split out duplication logic into App.duplicate.ts (#12125)
David Luzar97c68dd371e1
diff --git a/packages/excalidraw/actions/actionDuplicateSelection.tsx b/packages/excalidraw/actions/actionDuplicateSelection.tsxindex 7af6cfc74b..f0386108f0 100644--- a/packages/excalidraw/actions/actionDuplicateSelection.tsx+++ b/packages/excalidraw/actions/actionDuplicateSelection.tsx@@ -16,10 +16,7 @@ import {import { syncMovedIndices } from "@excalidraw/element";-import {- duplicateElements,- reconcileDuplicatedElements,-} from "@excalidraw/element";+import { duplicateElements } from "@excalidraw/element";import { CaptureUpdateAction } from "@excalidraw/element";@@ -89,15 +86,10 @@ export const actionDuplicateSelection = register({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,- }),+ app.duplicate.runOnDuplicate(+ duplication,elementsWithDuplicates,- duplicatedElements,+ elements,));// host vetoed the duplicationdiff --git a/packages/excalidraw/components/App.duplicate.ts b/packages/excalidraw/components/App.duplicate.tsnew file mode 100644index 0000000000..f9118b2d62--- /dev/null+++ b/packages/excalidraw/components/App.duplicate.ts@@ -0,0 +1,320 @@+import { flushSync } from "react-dom";++import {+ arrayToMap,+ distance,+ getGridPoint,+ randomInteger,+ viewportCoordsToSceneCoords,+} from "@excalidraw/common";++import {+ addElementsToFrame,+ deepCopyElement,+ duplicateElements,+ filterElementsEligibleAsFrameChildren,+ getCommonBounds,+ getSelectionStateForElements,+ isBindableElement,+ newElementWith,+ reconcileDuplicatedElements,+ syncMovedIndices,+ updateBoundElements,+} from "@excalidraw/element";++import type { ExcalidrawElement } from "@excalidraw/element/types";++import type { PointerDownState } from "../types";++import type App from "./App";++type Duplication = Pick<+ ReturnType<typeof duplicateElements>,+ | "duplicatedElements"+ | "duplicateElementsMap"+ | "origElementsMap"+ | "origIdToDuplicateId"+ | "duplicateIdToOrigId"+>;++/**+ * Owns the duplication paths which involve the host (`props.onDuplicate`):+ * duplicating elements into the scene (paste, library insert etc.), and+ * duplicating the dragged selection (alt-drag). The duplicate action shares+ * `runOnDuplicate()`.+ */+export class AppDuplicate {+ constructor(private app: App) {}++ /**+ * Hands the duplication over to the host's `props.onDuplicate` (if any),+ * and reconciles what it returned with the duplicates.+ *+ * @returns next elements, and the duplicates that weren't vetoed+ */+ runOnDuplicate = (+ duplication: Duplication,+ nextElements: ExcalidrawElement[],+ /** excludes the duplicated elements */+ prevElements: readonly ExcalidrawElement[],+ ) => {+ return reconcileDuplicatedElements(+ this.app.props.onDuplicate?.(nextElements, prevElements, {+ duplicateElements: duplication.duplicateElementsMap,+ originalElements: duplication.origElementsMap,+ origIdToDuplicateId: duplication.origIdToDuplicateId,+ duplicateIdToOrigId: duplication.duplicateIdToOrigId,+ }),+ nextElements,+ duplication.duplicatedElements,+ );+ };++ /**+ * Duplicates elements so that they end up centered at the scene coords+ * (and in the frame at that point, if any). Doesn't update the scene.+ *+ * @returns `null` if the host vetoed the duplication+ */+ duplicateAtSceneCoords = (+ elements: readonly ExcalidrawElement[],+ { x, y }: { x: number; y: number },+ opts?: {+ retainSeed?: boolean;+ preserveFrameChildrenOrder?: boolean;+ },+ ) => {+ const [minX, minY, maxX, maxY] = getCommonBounds(elements);++ const elementsCenterX = distance(minX, maxX) / 2;+ const elementsCenterY = distance(minY, maxY) / 2;++ const dx = x - elementsCenterX;+ const dy = y - elementsCenterY;++ const [gridX, gridY] = getGridPoint(+ dx,+ dy,+ this.app.getEffectiveGridSize(),+ );++ const duplication = duplicateElements({+ type: "everything",+ elements: elements.map((element) => {+ return newElementWith(element, {+ x: element.x + gridX - minX,+ y: element.y + gridY - minY,+ });+ }),+ randomizeSeed: !opts?.retainSeed,+ preserveFrameChildrenOrder: opts?.preserveFrameChildrenOrder,+ });+ let { duplicatedElements } = duplication;++ const prevElements = this.app.scene.getElementsIncludingDeleted();+ let nextElements: ExcalidrawElement[] = [+ ...prevElements,+ ...duplicatedElements,+ ];++ 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.app.getTopLayerFrameAtSceneCoords({ x, y });++ if (topLayerFrame) {+ const eligibleElements = filterElementsEligibleAsFrameChildren(+ duplicatedElements,+ topLayerFrame,+ );+ nextElements = addElementsToFrame(+ nextElements,+ eligibleElements,+ topLayerFrame,+ );+ }++ if (this.app.props.onDuplicate) {+ ({ elements: nextElements, duplicatedElements } = this.runOnDuplicate(+ duplication,+ nextElements,+ prevElements,+ ));++ // host vetoed the duplication+ if (!duplicatedElements.length) {+ return null;+ }++ // host may have reordered the elements+ syncMovedIndices(nextElements, arrayToMap(duplicatedElements));+ }++ return { nextElements, duplicatedElements };+ };++ /**+ * Duplicates the selection being dragged: the originals go back to where+ * the drag started, and the drag continues with the duplicates.+ *+ * If the host vetoes the duplication, the originals keep being dragged.+ */+ duplicateDraggedSelection = (+ pointerDownState: PointerDownState,+ event: PointerEvent,+ ) => {+ // Move the currently selected elements to the top of the z index stack, and+ // put the duplicates where the selected elements used to be.+ // (the origin point where the dragging started)++ pointerDownState.hit.hasBeenDuplicated = true;++ const elements = this.app.scene.getElementsIncludingDeleted();+ const hitElement = pointerDownState.hit.element;+ const selectedElements = this.app.scene.getSelectedElements({+ selectedElementIds: this.app.state.selectedElementIds,+ includeBoundTextElement: true,+ includeElementsInFrames: true,+ });+ if (+ hitElement &&+ // hit element may not end up being selected+ // if we're alt-dragging a common bounding box+ // over the hit element+ pointerDownState.hit.wasAddedToSelection &&+ !selectedElements.find((el) => el.id === hitElement.id)+ ) {+ selectedElements.push(hitElement);+ }++ const idsOfElementsToDuplicate = new Map(+ selectedElements.map((el) => [el.id, el]),+ );++ const duplication = duplicateElements({+ type: "in-place",+ elements,+ appState: this.app.state,+ randomizeSeed: true,+ idsOfElementsToDuplicate,+ overrides: ({ duplicateElement, origElement }) => {+ return {+ // reset to the original element's frameId (unless we've+ // duplicated alongside a frame in which case we need to+ // keep the duplicate frame's id) so that the element+ // frame membership is refreshed on pointerup+ // NOTE this is a hacky solution and should be done+ // differently+ frameId: duplicateElement.frameId ?? origElement.frameId,+ seed: randomInteger(),+ };+ },+ });+ const { origElementsMap, origIdToDuplicateId } = duplication;++ const mappedClonedElements = duplication.elementsWithDuplicates.map(+ (el) => {+ if (idsOfElementsToDuplicate.has(el.id)) {+ const origEl = pointerDownState.originalElements.get(el.id);++ if (origEl) {+ 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 { elements: nextElements, duplicatedElements } = this.runOnDuplicate(+ duplication,+ mappedClonedElements,+ elements,+ );++ // 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(+ nextElements,+ duplicateElementsMap,+ );++ // we need to update synchronously so as to keep pointerDownState,+ // appState, and scene elements in sync+ flushSync(() => {+ // swap hit element with the duplicated one+ if (pointerDownState.hit.element) {+ const cloneId = origIdToDuplicateId.get(+ pointerDownState.hit.element.id,+ );+ const clonedElement = cloneId && duplicateElementsMap.get(cloneId);+ pointerDownState.hit.element = clonedElement || null;+ }+ // swap hit elements with the duplicated ones+ pointerDownState.hit.allHitElements =+ pointerDownState.hit.allHitElements.reduce(+ (acc: typeof pointerDownState.hit.allHitElements, origHitElement) => {+ const cloneId = origIdToDuplicateId.get(origHitElement.id);+ const clonedElement = cloneId && duplicateElementsMap.get(cloneId);+ if (clonedElement) {+ acc.push(clonedElement);+ }++ return acc;+ },+ [],+ );++ // update drag origin to the position at which we started+ // the duplication so that the drag offset is correct+ pointerDownState.drag.origin = viewportCoordsToSceneCoords(+ event,+ this.app.state,+ );++ // switch selected elements to the duplicated ones+ this.app.setState((prevState) => ({+ ...getSelectionStateForElements(+ duplicatedElements,+ this.app.scene.getNonDeletedElements(),+ prevState,+ ),+ }));++ this.app.scene.replaceAllElements(elementsWithIndices);+ selectedElements.forEach((element) => {+ if (+ isBindableElement(element) &&+ element.boundElements?.some((other) => other.type === "arrow")+ ) {+ updateBoundElements(element, this.app.scene);+ }+ });++ this.app.maybeCacheVisibleGaps(event, selectedElements, true);+ this.app.maybeCacheReferenceSnapPoints(event, selectedElements, true);+ });+ };+}diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex 3b8dfbc525..4f10409f9b 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -88,7 +88,6 @@ import {applyDarkModeFilter,AppEventBus,type EXPORT_IMAGE_TYPES,- randomInteger,CLASSES,Emitter,MINIMUM_ARROW_SIZE,@@ -136,7 +135,6 @@ import {refreshTextDimensions,deepCopyElement,duplicateElements,- reconcileDuplicatedElements,hasBoundTextElement,isArrowElement,isBindingElement,@@ -194,7 +192,6 @@ import {isElementInFrame,getFrameLikeTitle,getElementsOverlappingFrame,- filterElementsEligibleAsFrameChildren,hitElementBoundText,hitElementBoundingBoxOnly,hitElementItself,@@ -220,7 +217,6 @@ import {isSelectedViaGroup,selectGroupsForSelectedElements,syncInvalidIndices,- syncMovedIndices,excludeElementsInFramesFromSelection,getSelectionStateForElements,makeNextSelectedElementIds,@@ -454,6 +450,7 @@ import { AppBucketFill } from "./App.bucketFill";import { AppToolDrag, TOOL_DRAG_PREVIEW_OPACITY } from "./App.toolDrag";import { AppCursor } from "./App.cursor";import { AppDrawShape } from "./App.drawshape";+import { AppDuplicate } from "./App.duplicate";import { AppFlowchart } from "./App.flowchart";import { AppPan } from "./App.pan";import { AppViewport, RIGHT_SIDEBAR_WIDTH } from "./App.viewport";@@ -718,6 +715,7 @@ class App extends React.Component<AppProps, AppState> {public onStateChange: OnStateChange = this.appStateObserver.onStateChange;public bucketFill: AppBucketFill = new AppBucketFill(this);+ public duplicate: AppDuplicate = new AppDuplicate(this);public toolDrag: AppToolDrag = new AppToolDrag(this);public flowchart: AppFlowchart = new AppFlowchart(this);public cursor: AppCursor = new AppCursor(this);@@ -4826,11 +4824,6 @@ class App extends React.Component<AppProps, AppState> {const elements = restoreElements(opts.elements, null, {deleteInvisibleElements: true,});- const [minX, minY, maxX, maxY] = getCommonBounds(elements);-- const elementsCenterX = distance(minX, maxX) / 2;- const elementsCenterY = distance(minY, maxY) / 2;-const clientX =typeof opts.position === "object"? opts.position.clientX@@ -4844,74 +4837,20 @@ class App extends React.Component<AppProps, AppState> {? this.viewport.lastPosition.y: this.state.height / 2 + this.state.offsetTop;- const { x, y } = viewportCoordsToSceneCoords(- { clientX, clientY },- this.state,+ const duplication = this.duplicate.duplicateAtSceneCoords(+ elements,+ viewportCoordsToSceneCoords({ clientX, clientY }, this.state),+ {+ retainSeed: opts.retainSeed,+ preserveFrameChildrenOrder: opts.preserveFrameChildrenOrder,+ },);- const dx = x - elementsCenterX;- const dy = y - elementsCenterY;-- const [gridX, gridY] = getGridPoint(dx, dy, this.getEffectiveGridSize());-- const duplication = duplicateElements({- type: "everything",- elements: elements.map((element) => {- return newElementWith(element, {- x: element.x + gridX - minX,- y: element.y + gridY - minY,- });- }),- randomizeSeed: !opts.retainSeed,- preserveFrameChildrenOrder: opts.preserveFrameChildrenOrder,- });- let { duplicatedElements } = duplication;-- const prevElements = this.scene.getElementsIncludingDeleted();- let nextElements: ExcalidrawElement[] = [- ...prevElements,- ...duplicatedElements,- ];-- 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) {- const eligibleElements = filterElementsEligibleAsFrameChildren(- duplicatedElements,- topLayerFrame,- );- nextElements = addElementsToFrame(- nextElements,- eligibleElements,- topLayerFrame,- );+ if (!duplication) {+ return;}- 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));- }+ const { nextElements, duplicatedElements } = duplication;this.scene.replaceAllElements(nextElements);@@ -10590,7 +10529,7 @@ class App extends React.Component<AppProps, AppState> {});};- private maybeCacheReferenceSnapPoints(+ public maybeCacheReferenceSnapPoints(event: KeyboardModifiersObject,selectedElements: readonly NonDeletedExcalidrawElement[],recomputeAnyways: boolean = false,@@ -10614,7 +10553,7 @@ class App extends React.Component<AppProps, AppState> {}}- private maybeCacheVisibleGaps(+ public maybeCacheVisibleGaps(event: KeyboardModifiersObject,selectedElements: readonly NonDeletedExcalidrawElement[],recomputeAnyways: boolean = false,@@ -11179,173 +11118,7 @@ class App extends React.Component<AppProps, AppState> {// We duplicate the selected element if alt is pressed on pointer moveif (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {- // Move the currently selected elements to the top of the z index stack, and- // put the duplicates where the selected elements used to be.- // (the origin point where the dragging started)-- pointerDownState.hit.hasBeenDuplicated = true;-- const elements = this.scene.getElementsIncludingDeleted();- const hitElement = pointerDownState.hit.element;- const selectedElements = this.scene.getSelectedElements({- selectedElementIds: this.state.selectedElementIds,- includeBoundTextElement: true,- includeElementsInFrames: true,- });- if (- hitElement &&- // hit element may not end up being selected- // if we're alt-dragging a common bounding box- // over the hit element- pointerDownState.hit.wasAddedToSelection &&- !selectedElements.find((el) => el.id === hitElement.id)- ) {- selectedElements.push(hitElement);- }-- const idsOfElementsToDuplicate = new Map(- selectedElements.map((el) => [el.id, el]),- );-- const {- duplicatedElements: _duplicatedElements,- duplicateElementsMap: _duplicateElementsMap,- origElementsMap,- elementsWithDuplicates,- origIdToDuplicateId,- duplicateIdToOrigId,- } = duplicateElements({- type: "in-place",- elements,- appState: this.state,- randomizeSeed: true,- idsOfElementsToDuplicate,- overrides: ({ duplicateElement, origElement }) => {- return {- // reset to the original element's frameId (unless we've- // duplicated alongside a frame in which case we need to- // keep the duplicate frame's id) so that the element- // frame membership is refreshed on pointerup- // NOTE this is a hacky solution and should be done- // differently- frameId: duplicateElement.frameId ?? origElement.frameId,- seed: randomInteger(),- };- },- });-- const mappedClonedElements = elementsWithDuplicates.map((el) => {- if (idsOfElementsToDuplicate.has(el.id)) {- const origEl = pointerDownState.originalElements.get(el.id);-- if (origEl) {- 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 { 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(- nextElements,- duplicateElementsMap,- );-- // we need to update synchronously so as to keep pointerDownState,- // appState, and scene elements in sync- flushSync(() => {- // swap hit element with the duplicated one- if (pointerDownState.hit.element) {- const cloneId = origIdToDuplicateId.get(- pointerDownState.hit.element.id,- );- const clonedElement =- cloneId && duplicateElementsMap.get(cloneId);- pointerDownState.hit.element = clonedElement || null;- }- // swap hit elements with the duplicated ones- pointerDownState.hit.allHitElements =- pointerDownState.hit.allHitElements.reduce(- (- acc: typeof pointerDownState.hit.allHitElements,- origHitElement,- ) => {- const cloneId = origIdToDuplicateId.get(origHitElement.id);- const clonedElement =- cloneId && duplicateElementsMap.get(cloneId);- if (clonedElement) {- acc.push(clonedElement);- }-- return acc;- },- [],- );-- // update drag origin to the position at which we started- // the duplication so that the drag offset is correct- pointerDownState.drag.origin = viewportCoordsToSceneCoords(- event,- this.state,- );-- // switch selected elements to the duplicated ones- this.setState((prevState) => ({- ...getSelectionStateForElements(- duplicatedElements,- this.scene.getNonDeletedElements(),- prevState,- ),- }));-- this.scene.replaceAllElements(elementsWithIndices);- selectedElements.forEach((element) => {- if (- isBindableElement(element) &&- element.boundElements?.some((other) => other.type === "arrow")- ) {- updateBoundElements(element, this.scene);- }- });-- this.maybeCacheVisibleGaps(event, selectedElements, true);- this.maybeCacheReferenceSnapPoints(event, selectedElements, true);- });+ this.duplicate.duplicateDraggedSelection(pointerDownState, event);}return;diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex 995c5c67c4..5326c731ac 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -1202,6 +1202,7 @@ export type AppClassProperties = {arrowText: App["arrowText"];cursor: App["cursor"];bucketFill: App["bucketFill"];+ duplicate: App["duplicate"];toolDrag: App["toolDrag"];activeResizeHandle: App["activeResizeHandle"];isToolLocked: App["isToolLocked"];