Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): frame membership, clipping and cut fixes (#12270)
David Luzar541653c7c9d5
diff --git a/packages/element/src/bounds.ts b/packages/element/src/bounds.tsindex 493fe9919f..9c1af8c702 100644--- a/packages/element/src/bounds.ts+++ b/packages/element/src/bounds.ts@@ -1277,6 +1277,7 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({type,excludeElementsInFrames,shouldIgnoreElementFromSelection,+ includeStroke = true,}: {elements: readonly T[];elementsMap?: ElementsMap;@@ -1288,6 +1289,8 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({type: "contain" | "overlap";excludeElementsInFrames?: boolean;shouldIgnoreElementFromSelection?: (element: T) => boolean;+ /** whether elements extend by their stroke, as they render */+ includeStroke?: boolean;}) => {if (!elementsMap) {elementsMap = arrayToMap(elements) as ElementsMap;@@ -1336,7 +1339,7 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({groups[groupId].push(element);}- const strokeWidth = element.strokeWidth;+ const strokeWidth = includeStroke ? element.strokeWidth : 0;let labelAABB: Bounds | null = null;let elementAABB = getElementBounds(element, elementsMap);diff --git a/packages/element/src/frame.ts b/packages/element/src/frame.tsindex bc2cdf2854..d74c99eb14 100644--- a/packages/element/src/frame.ts+++ b/packages/element/src/frame.ts@@ -1,7 +1,8 @@-import { arrayToMap } from "@excalidraw/common";+import { arrayToMap, type Bounds } from "@excalidraw/common";import {isPointWithinBounds,pointFrom,+ PRECISION,segmentsIntersectAt,} from "@excalidraw/math";@@ -13,7 +14,10 @@ import type {import type { ReadonlySetLike } from "@excalidraw/common/utility-types";-import { getElementsWithinSelection, getSelectedElements } from "./selection";+import {+ getSelectedElements,+ shouldIgnoreElementFromSelection,+} from "./selection";import { getElementsInGroup, selectGroupsFromGivenElements } from "./groups";import {@@ -23,6 +27,7 @@ import {doBoundsIntersect,getElementBounds,boundsContainBounds,+ elementsOverlappingBBox,} from "./bounds";import { mutateElement } from "./mutateElement";import { getBoundTextElement, getContainerElement } from "./textElement";@@ -90,13 +95,34 @@ export function isElementIntersectingFrame(return intersecting;}+/**+ * What's in the frame: to a hair beyond its edges, which snapping it to an+ * element's (or an element to its) leaves the element at.+ */+const getFrameInnerBounds = (+ frame: ExcalidrawFrameLikeElement,+ elementsMap: ElementsMap,+): Bounds => {+ const [x1, y1, x2, y2] = getElementBounds(frame, elementsMap);+ return [x1 - PRECISION, y1 - PRECISION, x2 + PRECISION, y2 + PRECISION];+};+export const getElementsCompletelyInFrame = (elements: readonly ExcalidrawElement[],frame: ExcalidrawFrameLikeElement,elementsMap: ElementsMap,) =>omitGroupsContainingFrameLikes(- getElementsWithinSelection(elements, frame, elementsMap, false),+ // by their outlines (as the frame's other bounds checks), so that a frame+ // snapped to an element's edges contains it+ elementsOverlappingBBox({+ elements,+ elementsMap,+ bounds: getFrameInnerBounds(frame, elementsMap),+ type: "contain",+ shouldIgnoreElementFromSelection,+ includeStroke: false,+ }),).filter((element) =>(!isFrameLikeElement(element) && !element.frameId) ||@@ -129,7 +155,7 @@ export const elementsAreInFrameBounds = (frame: ExcalidrawFrameLikeElement,elementsMap: ElementsMap,) => {- const [frameX1, frameY1, frameX2, frameY2] = getElementAbsoluteCoords(+ const [frameX1, frameY1, frameX2, frameY2] = getFrameInnerBounds(frame,elementsMap,);@@ -919,6 +945,21 @@ export const shouldApplyFrameClip = (return false;}+ // a frame's children are clipped to it (as in SVG exports): one inside it+ // may still reach out of it with its stroke. Only those being dragged are+ // checked (as their drop will be), the rest are in it as they stand.+ if (element.frameId === frame.id) {+ const shouldClip = isElementInFrame(element, elementsMap, appState, {+ targetFrame: frame,+ checkedGroups,+ });++ for (const groupId of element.groupIds) {+ checkedGroups?.set(groupId, shouldClip);+ }+ return shouldClip;+ }+// for individual elements, only clip when the element is// a. overlapping with the frame, or// b. containing the frame, for example when an element is used as a background@@ -935,28 +976,17 @@ export const shouldApplyFrameClip = (return true;}- // if an element is outside the frame, but is part of a group that has some elements+ // if an element is outside the frame, but is part of a group being dragged// "in" the frame, we should clip the elementif (- !shouldClipElementItself &&+ appState.selectedElementsAreBeingDragged &&element.groupIds.length > 0 &&!elementsAreInFrameBounds([element], frame, elementsMap)) {- let shouldClip = false;-- // if no elements are being dragged, we can skip the geometry check- // because we know if the element is in the given frame or not- if (!appState.selectedElementsAreBeingDragged) {- shouldClip = element.frameId === frame.id;- for (const groupId of element.groupIds) {- checkedGroups?.set(groupId, shouldClip);- }- } else {- shouldClip = isElementInFrame(element, elementsMap, appState, {- targetFrame: frame,- checkedGroups,- });- }+ const shouldClip = isElementInFrame(element, elementsMap, appState, {+ targetFrame: frame,+ checkedGroups,+ });for (const groupId of element.groupIds) {checkedGroups?.set(groupId, shouldClip);diff --git a/packages/element/src/selection.ts b/packages/element/src/selection.tsindex ab31195cda..c9b07f23dc 100644--- a/packages/element/src/selection.ts+++ b/packages/element/src/selection.ts@@ -26,7 +26,7 @@ import type {NonDeletedExcalidrawElement,} from "./types";-const shouldIgnoreElementFromSelection = (element: ExcalidrawElement) =>+export const shouldIgnoreElementFromSelection = (element: ExcalidrawElement) =>element.locked || isBoundToContainer(element);const excludeElementsFromFrames = <T extends ExcalidrawElement>(diff --git a/packages/element/tests/frame.test.tsx b/packages/element/tests/frame.test.tsxindex 22e406e732..d05b752fcf 100644--- a/packages/element/tests/frame.test.tsx+++ b/packages/element/tests/frame.test.tsx@@ -8,13 +8,14 @@ import { API } from "@excalidraw/excalidraw/tests/helpers/api";import { Keyboard, Pointer, UI } from "@excalidraw/excalidraw/tests/helpers/ui";import { getTextEditor } from "@excalidraw/excalidraw/tests/queries/dom";import {+ act,getCloneByOrigId,render,} from "@excalidraw/excalidraw/tests/test-utils";import { getSelectedElements } from "@excalidraw/excalidraw/scene";-import { elementOverlapsWithFrame } from "../src/frame";+import { elementOverlapsWithFrame, shouldApplyFrameClip } from "../src/frame";import type {ExcalidrawElement,@@ -156,6 +157,108 @@ describe("adding elements to frames", () => {).toBe(true);});+ it("should add a group a new frame matches edge to edge", () => {+ // a hair outside, as snapping the frame to it leaves it+ const rects = [+ [100 - 1e-8, 100],+ [200, 100 + 1e-8],+ ].map(([x, width]) =>+ API.createElement({+ type: "rectangle",+ x,+ y: 100,+ width,+ height: 100,+ strokeWidth: 4,+ groupIds: ["group"],+ }),+ );+ API.setElements(rects);++ act(() => h.app.setActiveTool({ type: "frame" }));+ mouse.downAt(100, 100);+ mouse.moveTo(300, 200);+ mouse.up();++ const newFrame = h.elements.find((el) => el.type === "frame");+ expect(newFrame).toMatchObject({ x: 100, y: 100, width: 200 });+ expect(+ rects.map((rect) => h.elements.find((el) => el.id === rect.id)?.frameId),+ ).toEqual([newFrame!.id, newFrame!.id]);+ });++ it("should add a group a resized frame matches edge to edge", () => {+ // a hair outside, as snapping the frame to it leaves it+ const rects = [+ [160, 40],+ [200, 50 + 1e-8],+ ].map(([x, width]) =>+ API.createElement({+ type: "rectangle",+ x,+ y: 0,+ width,+ height: 100,+ groupIds: ["group"],+ }),+ );+ API.setElements([frame, ...rects]);++ mouse.clickAt(0, 0);+ mouse.downAt(frame.x + frame.width, frame.y + frame.height);+ mouse.moveTo(250, 100);+ mouse.up();++ expect(+ rects.map((rect) => h.elements.find((el) => el.id === rect.id)?.frameId),+ ).toEqual([frame.id, frame.id]);+ });++ it("should clip a frame's child to it, even if inside it (but for its stroke)", () => {+ const child = API.createElement({+ type: "rectangle",+ x: 1e-7,+ y: 1e-7,+ width: 150 - 2e-7,+ height: 100 - 2e-7,+ frameId: frame.id,+ });+ API.setElements([child, frame]);++ expect(+ shouldApplyFrameClip(+ child,+ frame as ExcalidrawFrameLikeElement,+ h.state,+ arrayToMap(h.elements),+ ),+ ).toBe(true);+ });++ it("should not clip a child dragged out of its frame", () => {+ const child = API.createElement({+ type: "rectangle",+ x: 300,+ width: 50,+ height: 50,+ frameId: frame.id,+ });+ API.setElements([child, frame]);++ expect(+ shouldApplyFrameClip(+ child,+ frame as ExcalidrawFrameLikeElement,+ {+ ...h.state,+ selectedElementIds: { [child.id]: true },+ selectedElementsAreBeingDragged: true,+ },+ arrayToMap(h.elements),+ ),+ ).toBe(false);+ });+it("should not add a newly created element to a frame behind a non-frame element", () => {const cover = API.createElement({id: "cover",diff --git a/packages/excalidraw/actions/actionClipboard.tsx b/packages/excalidraw/actions/actionClipboard.tsxindex 07240f0e9e..df5a261730 100644--- a/packages/excalidraw/actions/actionClipboard.tsx+++ b/packages/excalidraw/actions/actionClipboard.tsx@@ -116,7 +116,13 @@ export const actionCut = register<ClipboardEvent | null>({trackEvent: { category: "element" },perform: (elements, appState, event, app) => {actionCopy.perform(elements, appState, event, app);- return actionDeleteSelected.perform(elements, appState, null, app);+ // the cut frame's children are on the clipboard with it, so go with it+ return actionDeleteSelected.perform(+ elements,+ appState,+ { withFrameChildren: true },+ app,+ );},keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X,});diff --git a/packages/excalidraw/actions/actionDeleteSelected.test.tsx b/packages/excalidraw/actions/actionDeleteSelected.test.tsxindex 708d2cc556..8cc39e199c 100644--- a/packages/excalidraw/actions/actionDeleteSelected.test.tsx+++ b/packages/excalidraw/actions/actionDeleteSelected.test.tsx@@ -4,6 +4,7 @@ import { Excalidraw } from "../index";import { API } from "../tests/helpers/api";import { act, assertElements, render } from "../tests/test-utils";+import { actionCut } from "./actionClipboard";import { actionDeleteSelected } from "./actionDeleteSelected";const { h } = window;@@ -211,3 +212,67 @@ describe("deleting selected elements when frame selected should keep children +]);});});++describe("cutting a selected frame takes its children along", () => {+ beforeEach(async () => {+ await render(<Excalidraw />);+ });++ const createFrameWithChildren = () => {+ const f1 = API.createElement({ type: "frame" });+ const r1 = API.createElement({ type: "rectangle", frameId: f1.id });+ const r2 = API.createElement({ type: "rectangle", frameId: f1.id });+ const t1 = API.createElement({+ type: "text",+ containerId: r2.id,+ frameId: f1.id,+ });+ h.app.scene.mutateElement(r2, {+ boundElements: [{ type: "text", id: t1.id }],+ });+ API.setElements([f1, r1, r2, t1]);+ return { f1, r1, r2, t1 };+ };++ /** as on ctrl+x, with the clipboard data of the cut event */+ const cut = () => {+ const data = new Map<string, string>();+ const event = {+ clipboardData: {+ setData: (type: string, value: string) => data.set(type, value),+ getData: (type: string) => data.get(type),+ },+ } as unknown as ClipboardEvent;+ act(() => {+ h.app.actionManager.executeAction(actionCut, "keyboard", event);+ });+ };++ it("frame only", async () => {+ const { f1, r1, r2, t1 } = createFrameWithChildren();+ API.setSelectedElements([f1]);++ cut();++ assertElements(h.elements, [+ { id: f1.id, isDeleted: true },+ { id: r1.id, isDeleted: true },+ { id: r2.id, isDeleted: true },+ { id: t1.id, isDeleted: true },+ ]);+ });++ it("frame + children selected", async () => {+ const { f1, r1, r2, t1 } = createFrameWithChildren();+ API.setSelectedElements([f1, r1, r2]);++ cut();++ assertElements(h.elements, [+ { id: f1.id, isDeleted: true },+ { id: r1.id, isDeleted: true },+ { id: r2.id, isDeleted: true },+ { id: t1.id, isDeleted: true },+ ]);+ });+});diff --git a/packages/excalidraw/actions/actionDeleteSelected.tsx b/packages/excalidraw/actions/actionDeleteSelected.tsxindex 54759ce70c..11c0f2b86b 100644--- a/packages/excalidraw/actions/actionDeleteSelected.tsx+++ b/packages/excalidraw/actions/actionDeleteSelected.tsx@@ -39,6 +39,8 @@ const deleteSelectedElements = (elements: readonly ExcalidrawElement[],appState: AppState,app: AppClassProperties,+ /** a deleted frame takes its children along, rather than leaving them */+ withFrameChildren: boolean,) => {const framesToBeDeleted = new Set(getSelectedElements(@@ -46,6 +48,8 @@ const deleteSelectedElements = (appState,).map((el) => el.id),);+ const isChildOfDeletedFrame = (el: ExcalidrawElement) =>+ !!el.frameId && framesToBeDeleted.has(el.frameId);const selectedElementIds: Record<ExcalidrawElement["id"], true> = {};@@ -53,7 +57,7 @@ const deleteSelectedElements = (const processedElements = new Set<ExcalidrawElement["id"]>();- for (const frameId of framesToBeDeleted) {+ for (const frameId of withFrameChildren ? [] : framesToBeDeleted) {const frameChildren = getFrameChildren(elements, frameId);for (const el of frameChildren) {if (processedElements.has(el.id)) {@@ -75,20 +79,24 @@ const deleteSelectedElements = (let shouldSelectEditingGroup = true;const nextElements = elements.map((el) => {- if (appState.selectedElementIds[el.id]) {+ if (+ appState.selectedElementIds[el.id] ||+ (withFrameChildren && isChildOfDeletedFrame(el))+ ) {const boundElement = isBoundToContainer(el)? getContainerElement(el, elementsMap): null;- if (el.frameId && framesToBeDeleted.has(el.frameId)) {+ if (!withFrameChildren && isChildOfDeletedFrame(el)) {shouldSelectEditingGroup = false;selectedElementIds[el.id] = true;return el;}if (- boundElement?.frameId &&- framesToBeDeleted.has(boundElement?.frameId)+ !withFrameChildren &&+ boundElement &&+ isChildOfDeletedFrame(boundElement)) {return el;}@@ -112,7 +120,7 @@ const deleteSelectedElements = (}// if deleting a frame, remove the children from it and select them- if (el.frameId && framesToBeDeleted.has(el.frameId)) {+ if (isChildOfDeletedFrame(el)) {shouldSelectEditingGroup = false;if (!isBoundToContainer(el)) {selectedElementIds[el.id] = true;@@ -204,7 +212,9 @@ const handleGroupEditingState = (return appState;};-export const actionDeleteSelected = register({+export const actionDeleteSelected = register<{+ withFrameChildren?: boolean;+} | null>({name: "deleteSelectedElements",label: "labels.delete",icon: TrashIcon,@@ -272,7 +282,12 @@ export const actionDeleteSelected = register({}let { elements: nextElements, appState: nextAppState } =- deleteSelectedElements(elements, appState, app);+ deleteSelectedElements(+ elements,+ appState,+ app,+ !!formData?.withFrameChildren,+ );fixBindingsAfterDeletion(nextElements,