diff --git a/dev-docs/docs/codebase/frames.mdx b/dev-docs/docs/codebase/frames.mdx index 67c84b7921..4e3d461655 100644 --- a/dev-docs/docs/codebase/frames.mdx +++ b/dev-docs/docs/codebase/frames.mdx @@ -20,3 +20,9 @@ Frames should be ordered where frame children come first, followed by the frame ``` If not ordered correctly, the editor will still function, but the elements may not be rendered and clipped correctly. Further, the renderer relies on this ordering for performance optimizations. + +## Clipping + +Frame children are clipped to their frame, and can't be hit (selected, hovered, box- or lasso-selected) outside of it. + +Arrows (with their labels) are the exception: they're never clipped, so that they can connect elements across and out of frames. They still belong to the frame they're drawn from, so they're moved, copied and deleted with it. When exporting a frame, arrows of other frames reaching into it are exported too, as are any other non-children overlapping it. When moving a frame (dragging it, with the arrow keys, or from the stats panel), its arrows bound to elements that don't move with it stay bound to them (see `moveFrameArrows`). diff --git a/packages/element/src/binding.ts b/packages/element/src/binding.ts index f5f0f97386..c31f423bd3 100644 --- a/packages/element/src/binding.ts +++ b/packages/element/src/binding.ts @@ -1442,44 +1442,70 @@ export const updateBoundArrow = ( : elementsMap.get(arrow.endBinding.elementId) : null; - const updates = bindableElementsVisitor( - elementsMap, + LinearElementEditor.movePoints( arrow, - (bindableElement, bindingProp) => { - if ( - bindableElement && - isBindableElement(bindableElement) && - (bindingProp === "startBinding" || bindingProp === "endBinding") - ) { - const point = updateBoundPoint( - arrow, - bindingProp, - arrow[bindingProp], - bindableElement, - elementsMap, - ); - - if (point) { - return [ - bindingProp === "startBinding" ? 0 : arrow.points.length - 1, - { point }, - ] as MapEntry; - } - } - - return null; + scene, + getBoundPointUpdates(arrow, elementsMap), + undefined, + { + moveMidPointsWithElement: + boundElementMoved && + !!startBindingElement && + startBindingElement?.id === endBindingElement?.id, }, - ).filter( - (update): update is MapEntry => update !== null, ); - LinearElementEditor.movePoints(arrow, scene, new Map(updates), undefined, { - moveMidPointsWithElement: - boundElementMoved && - !!startBindingElement && - startBindingElement?.id === endBindingElement?.id, - }); + updateArrowLabel(arrow, scene, elementsMap, renderEnvironment); +}; +/** + * Where `arrow`'s bindings put its bound ends on the elements in `elementsMap` + * they're bound to. + */ +const getBoundPointUpdates = ( + arrow: NonDeleted, + elementsMap: ElementsMap, +): PointsPositionUpdates => + new Map( + bindableElementsVisitor( + elementsMap, + arrow, + (bindableElement, bindingProp) => { + if ( + bindableElement && + isBindableElement(bindableElement) && + (bindingProp === "startBinding" || bindingProp === "endBinding") + ) { + const point = updateBoundPoint( + arrow, + bindingProp, + arrow[bindingProp], + bindableElement, + elementsMap, + ); + + if (point) { + return [ + bindingProp === "startBinding" ? 0 : arrow.points.length - 1, + { point }, + ] as MapEntry; + } + } + + return null; + }, + ).filter( + (update): update is MapEntry => update !== null, + ), + ); + +/** Rewraps `arrow`'s label (if any) along it as placed. */ +const updateArrowLabel = ( + arrow: NonDeleted, + scene: Scene, + elementsMap: ElementsMap, + renderEnvironment?: RenderEnvironment, +) => { const boundText = getBoundTextElement(arrow, elementsMap); if (boundText && !boundText.isDeleted) { handleBindTextResize( @@ -1494,6 +1520,109 @@ export const updateBoundArrow = ( } }; +/** Whether `arrow` is bound to an element not in `elementIds`. */ +export const isBoundToElementNotIn = ( + arrow: ExcalidrawArrowElement, + elementIds: ReadonlySet, +) => + (!!arrow.startBinding && !elementIds.has(arrow.startBinding.elementId)) || + (!!arrow.endBinding && !elementIds.has(arrow.endBinding.elementId)); + +/** + * The arrows that move with a frame being moved (with `movedElements`) but are + * bound to elements that don't (e.g. in other frames). They must neither be + * unbound, nor be left for what they're bound to to move: move everything + * else without them, and then them, with `moveFrameArrows()`. + * + * @param movedElements all the elements moving, frames included + */ +export const getFrameArrowIdsToReattach = ( + movedElements: readonly ExcalidrawElement[], +): ReadonlySet => { + const movedElementIds = getSimultaneouslyUpdatedElementIds(movedElements); + const ids = new Set(); + for (const element of movedElements) { + if ( + isArrowElement(element) && + element.frameId && + movedElementIds.has(element.frameId) && + isBoundToElementNotIn(element, movedElementIds) + ) { + ids.add(element.id); + } + } + return ids; +}; + +/** + * Moves the arrows (see `getFrameArrowIdsToReattach()`) by `offset` from where + * they were in `originalElements` (from where they are, without it), and puts + * their bound ends on what they're bound to: an end bound to a moved element + * thus follows it, and one bound to an unmoved element stays. Call it once + * everything else has moved. + */ +export const moveFrameArrows = ( + arrowIds: ReadonlySet, + offset: { x: number; y: number }, + scene: Scene, + opts?: { + originalElements?: ElementsMap; + /** measures the arrows' labels */ + renderEnvironment?: RenderEnvironment; + }, +) => { + const elementsMap = scene.getNonDeletedElementsMap(); + for (const id of arrowIds) { + const arrow = elementsMap.get(id); + if (!isArrowElement(arrow)) { + continue; + } + const original = + (opts?.originalElements?.get(id) as typeof arrow | undefined) ?? arrow; + // its points too, as putting its ends on what they're bound to (which + // moving it from where it was undoes) changes them + const moved = { + x: original.x + offset.x, + y: original.y + offset.y, + points: original.points, + }; + if (isElbowArrow(arrow)) { + if (isElbowArrow(original) && original.fixedSegments?.length) { + // routing it keeps its fixed segments, as placed relative to its + // route where it is, so first put its route where it was, moved (which + // doesn't route it, its fixed segments being given) + scene.mutateElement(arrow, { + ...moved, + fixedSegments: original.fixedSegments, + startIsSpecial: original.startIsSpecial, + endIsSpecial: original.endIsSpecial, + }); + } + // updating its points routes it, so route it once, with its bound ends + // already on what they're bound to (where its route heads off) + const points = moved.points.slice(); + getBoundPointUpdates({ ...arrow, ...moved }, elementsMap).forEach( + ({ point }, index) => { + points[index] = point; + }, + ); + scene.mutateElement(arrow, { ...moved, points }); + updateArrowLabel(arrow, scene, elementsMap, opts?.renderEnvironment); + } else { + scene.mutateElement(arrow, moved); + updateBoundArrow( + arrow, + scene, + elementsMap, + opts?.renderEnvironment, + // it moved, not what it's bound to: an arrow bound to one element at + // both ends thus keeps its midpoints moved with the frame too + false, + ); + } + } +}; + // Supports translating, rotating and scaling `changedElement` with bound // linear elements. export const updateBoundElements = ( diff --git a/packages/element/src/bounds.ts b/packages/element/src/bounds.ts index 566035e12d..fbdf930a20 100644 --- a/packages/element/src/bounds.ts +++ b/packages/element/src/bounds.ts @@ -52,7 +52,11 @@ import { deconstructRectanguloidElement, } from "./utils"; import { intersectElementWithLineSegment } from "./collision"; -import { elementOverlapsWithFrame, getContainingFrame } from "./frame"; +import { + elementOverlapsWithFrame, + getContainingFrame, + isFrameClippable, +} from "./frame"; import type { Drawable, Op } from "roughjs/bin/core"; import type { Point as RoughPoint } from "roughjs/bin/geometry"; @@ -1627,6 +1631,7 @@ export const elementsOverlappingBBox = ({ const associatedFrame = getContainingFrame(element, elementsMap); if ( associatedFrame && + isFrameClippable(element, elementsMap) && elementOverlapsWithFrame(element, associatedFrame, elementsMap) ) { const frameAABB = getElementBounds(associatedFrame, elementsMap); diff --git a/packages/element/src/dragElements.ts b/packages/element/src/dragElements.ts index ad3cc0eba0..60dd54f497 100644 --- a/packages/element/src/dragElements.ts +++ b/packages/element/src/dragElements.ts @@ -16,7 +16,9 @@ import type { import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types"; import { + getFrameArrowIdsToReattach, getSimultaneouslyUpdatedElementIds, + moveFrameArrows, unbindBindingElement, updateBoundElements, } from "./binding"; @@ -116,8 +118,13 @@ export const dragSelectedElements = ( const elementsToUpdateIds = getSimultaneouslyUpdatedElementIds( elementsToUpdateArray, ); + const frameArrowIds = getFrameArrowIdsToReattach(elementsToUpdateArray); elementsToUpdate.forEach((element) => { + if (frameArrowIds.has(element.id)) { + // moved with their frame once the rest has (below) + return; + } if (!isArrowElement(element)) { updateElementCoords(pointerDownState, element, scene, adjustedOffset); @@ -169,6 +176,11 @@ export const dragSelectedElements = ( } } }); + + moveFrameArrows(frameArrowIds, adjustedOffset, scene, { + originalElements: pointerDownState.originalElements, + renderEnvironment, + }); }; const calculateOffset = ( diff --git a/packages/element/src/frame.ts b/packages/element/src/frame.ts index 49c65aee24..b6bd863929 100644 --- a/packages/element/src/frame.ts +++ b/packages/element/src/frame.ts @@ -33,6 +33,7 @@ import { mutateElement } from "./mutateElement"; import { getBoundTextElement, getContainerElement } from "./textElement"; import { syncMovedIndices } from "./fractionalIndex"; import { + isArrowElement, isFrameElement, isFrameLikeElement, isTextElement, @@ -470,6 +471,24 @@ export const getContainingFrame = ( null) as null | ExcalidrawFrameLikeElement; }; +/** + * Whether frames clip the element to their bounds (as their child, or when + * dragged into them). Arrows (with their labels) aren't, so that they can + * connect elements across and out of frames. + */ +export const isFrameClippable = ( + element: ExcalidrawElement, + elementsMap: ElementsMap, +) => { + if (isArrowElement(element)) { + return false; + } + if (isTextElement(element) && element.containerId) { + return !isArrowElement(elementsMap.get(element.containerId)); + } + return true; +}; + // --------------------------- Frame Operations ------------------------------- /** */ @@ -943,7 +962,11 @@ export const shouldApplyFrameClip = ( elementsMap: ElementsMap, checkedGroups?: Map, ) => { - if (!appState.frameRendering || !appState.frameRendering.clip) { + if ( + !appState.frameRendering || + !appState.frameRendering.clip || + !isFrameClippable(element, elementsMap) + ) { return false; } @@ -1017,16 +1040,25 @@ export const getElementsOverlappingFrame = ( frame: ExcalidrawFrameLikeElement, elementsMap: ElementsMap, ) => { - return elements.filter( - (el) => + const frameBounds = getElementBounds(frame, elementsMap); + + return elements.filter((el) => { + const container = + isTextElement(el) && el.containerId + ? elementsMap.get(el.containerId) + : null; + // an arrow's label is placed, and thus shown, with its arrow + const target = isArrowElement(container) ? container : el; + + return ( // exclude elements which are overlapping, but are in a different frame, - // and thus invisible in target frame - (!el.frameId || el.frameId === frame.id) && - doBoundsIntersect( - getElementBounds(el, elementsMap), - getElementBounds(frame, elementsMap), - ), - ); + // and thus invisible in target frame (unless not clipped by theirs) + (!target.frameId || + target.frameId === frame.id || + !isFrameClippable(target, elementsMap)) && + doBoundsIntersect(getElementBounds(target, elementsMap), frameBounds) + ); + }); }; export const frameAndChildrenSelectedTogether = ( diff --git a/packages/element/src/mutateElement.ts b/packages/element/src/mutateElement.ts index 3efc3bff16..033b6275a1 100644 --- a/packages/element/src/mutateElement.ts +++ b/packages/element/src/mutateElement.ts @@ -65,8 +65,8 @@ export const mutateElement = >( ...updateElbowArrowPoints( { ...(element as ExcalidrawElbowArrowElement), - x: updates.x || element.x, - y: updates.y || element.y, + x: updates.x ?? element.x, + y: updates.y ?? element.y, }, elementsMap as NonDeletedSceneElementsMap, updates as ElementUpdate, diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsx index dd7255b1d2..749e1b8064 100644 --- a/packages/element/tests/elbowArrow.test.tsx +++ b/packages/element/tests/elbowArrow.test.tsx @@ -163,6 +163,21 @@ describe("elbow arrow routing", () => { expect(arrow.height).toEqual(200); }); + it("can move an elbow arrow to the origin while routing it", () => { + const arrow = API.createElement({ + type: "arrow", + elbowed: true, + x: 5, + y: 5, + points: [pointFrom(0, 0), pointFrom(100, 0)], + }) as NonDeleted; + API.setElements([arrow]); + + h.scene.mutateElement(arrow, { x: 0, y: 0, points: arrow.points }); + + expect([arrow.x, arrow.y]).toEqual([0, 0]); + }); + it("can generate proper points for bound elbow arrow", () => { const rectangle1 = API.createElement({ type: "rectangle", diff --git a/packages/element/tests/frame.test.tsx b/packages/element/tests/frame.test.tsx index 4cbb310abc..3158ace40b 100644 --- a/packages/element/tests/frame.test.tsx +++ b/packages/element/tests/frame.test.tsx @@ -2,7 +2,8 @@ import { convertToExcalidrawElements, Excalidraw, } from "@excalidraw/excalidraw"; -import { arrayToMap } from "@excalidraw/common"; +import { arrayToMap, ELEMENT_TRANSLATE_AMOUNT, KEYS } from "@excalidraw/common"; +import { pointFrom } from "@excalidraw/math"; import { API } from "@excalidraw/excalidraw/tests/helpers/api"; import { Keyboard, Pointer, UI } from "@excalidraw/excalidraw/tests/helpers/ui"; @@ -14,10 +15,20 @@ import { } from "@excalidraw/excalidraw/tests/test-utils"; import { getSelectedElements } from "@excalidraw/excalidraw/scene"; +import { exportScene } from "@excalidraw/excalidraw/scene/export"; -import { elementOverlapsWithFrame, shouldApplyFrameClip } from "../src/frame"; +import type { GlobalPoint, LocalPoint } from "@excalidraw/math"; + +import { + elementOverlapsWithFrame, + getElementsOverlappingFrame, + shouldApplyFrameClip, +} from "../src/frame"; +import { LinearElementEditor } from "../src/linearElementEditor"; import type { + ExcalidrawArrowElement, + ExcalidrawElbowArrowElement, ExcalidrawElement, ExcalidrawFrameLikeElement, NonDeleted, @@ -1330,3 +1341,322 @@ describe("adding elements to frames", () => { }); }); }); + +describe("arrows in frames", () => { + // frame A and frame B side by side, a rectangle in each + let frameA: NonDeleted; + let frameB: NonDeleted; + let rectA: NonDeletedExcalidrawElement; + let rectB: NonDeletedExcalidrawElement; + + beforeEach(async () => { + await render(); + frameA = API.createElement({ type: "frame", width: 300, height: 300 }); + frameB = API.createElement({ + type: "frame", + x: 500, + y: 0, + width: 300, + height: 300, + }); + rectA = API.createElement({ + type: "rectangle", + x: 50, + y: 100, + width: 100, + height: 100, + backgroundColor: "red", + fillStyle: "solid", + frameId: frameA.id, + }); + rectB = API.createElement({ + type: "rectangle", + x: 600, + y: 100, + width: 100, + height: 100, + backgroundColor: "red", + fillStyle: "solid", + frameId: frameB.id, + }); + API.setElements([rectA, frameA, rectB, frameB]); + }); + + /** + * draws an arrow from `start` in frame A (rectA by default) to `end` in rectB, + * which is added to frame A + */ + const drawArrowBetweenFrames = ( + start = pointFrom(100, 150), + end = pointFrom(650, 150), + ) => { + UI.clickTool("arrow"); + mouse.downAt(...start); + mouse.moveTo(400, end[1]); + mouse.moveTo(...end); + mouse.up(); + UI.clickTool("selection"); + + const arrow = h.elements.find( + (element): element is ExcalidrawArrowElement => element.type === "arrow", + )!; + expect(arrow.frameId).toBe(frameA.id); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + return arrow; + }; + + const getPoints = (arrow: ExcalidrawArrowElement) => + arrow.points.map((_, index) => + LinearElementEditor.getPointAtIndexGlobalCoordinates( + arrow, + index, + arrayToMap(h.elements), + ), + ); + + /** an arrow (with a label) in frame A, reaching out into frame B */ + const createLabeledArrowOutOfFrame = () => { + const arrow = API.createElement({ + type: "arrow", + x: 100, + y: 150, + width: 550, + height: 0, + points: [pointFrom(0, 0), pointFrom(550, 0)], + frameId: frameA.id, + }); + const label = API.createElement({ + type: "text", + x: 400, + y: 140, + width: 50, + height: 20, + containerId: arrow.id, + frameId: frameA.id, + }); + h.app.scene.mutateElement(arrow, { + boundElements: [{ type: "text", id: label.id }], + }); + API.setElements([rectA, arrow, label, frameA, rectB, frameB]); + return { arrow, label }; + }; + + it("should not clip an arrow, nor its label, to its frame", async () => { + const { arrow, label } = createLabeledArrowOutOfFrame(); + + expect( + shouldApplyFrameClip(arrow, frameA, h.state, arrayToMap(h.elements)), + ).toBe(false); + + const data = { elements: h.app.scene.getNonDeletedElements() }; + // the rectangles to their frames, and the arrow's line around its label + // (drawn with it) + const canvas = await exportScene({ type: "canvas", data }); + expect( + (canvas.getContext("2d") as any) + .__getEvents() + .filter((event: any) => event.type === "clip"), + ).toHaveLength(3); + + const svg = await exportScene({ type: "svg", data }); + const getClipPath = (element: ExcalidrawElement) => + svg.querySelector(`[data-id="${element.id}"]`)?.getAttribute("clip-path"); + expect(getClipPath(rectA)).toBe(`url(#${frameA.id})`); + expect(getClipPath(arrow)).toBe(null); + expect(getClipPath(label)).toBe(null); + }); + + it("should select an arrow by its part outside its frame", () => { + const arrow = drawArrowBetweenFrames(); + mouse.clickAt(0, 0); + + mouse.clickAt(400, 150); + expect(h.state.selectedElementIds).toEqual({ [arrow.id]: true }); + }); + + it("should export an arrow reaching into a frame from another one", () => { + const { arrow, label } = createLabeledArrowOutOfFrame(); + + expect( + getElementsOverlappingFrame(h.elements, frameB, arrayToMap(h.elements)), + ).toEqual([arrow, label, rectB, frameB]); + }); + + it("should keep an arrow bound to an element in another frame when dragging its frame", () => { + const arrow = drawArrowBetweenFrames(); + expect(arrow.startBinding?.elementId).toBe(rectA.id); + const { y } = arrow; + const endPoint = LinearElementEditor.getPointAtIndexGlobalCoordinates( + arrow, + -1, + arrayToMap(h.elements), + ); + + API.setSelectedElements([frameA]); + mouse.downAt(250, 250); + mouse.moveTo(250, 300); + mouse.moveTo(250, 350); + mouse.up(); + + expect(h.app.scene.getElement(frameA.id)?.y).toBe(100); + expect(arrow.startBinding?.elementId).toBe(rectA.id); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + expect(arrow.y).toBe(y + 100); + expect( + LinearElementEditor.getPointAtIndexGlobalCoordinates( + arrow, + -1, + arrayToMap(h.elements), + ), + ).toEqual(endPoint); + }); + + it("should keep an elbow arrow's fixed segment when dragging its frame", () => { + API.setAppState({ currentItemArrowType: "elbow" }); + // routed around rectB, with its middle segment fixed + const arrow = drawArrowBetweenFrames( + undefined, + pointFrom(650, 180), + ) as ExcalidrawElbowArrowElement; + expect(arrow.elbowed).toBe(true); + const index = Math.floor(arrow.points.length / 2); + API.updateElement(arrow, { + fixedSegments: [ + { index, start: arrow.points[index - 1], end: arrow.points[index] }, + ], + }); + const { points, fixedSegments } = arrow; + + API.setSelectedElements([frameA]); + mouse.downAt(250, 250); + mouse.moveTo(285, 350); + mouse.up(); + + expect(arrow.startBinding?.elementId).toBe(rectA.id); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + // moved with its start (and frame), the rest of the route following + expect(arrow.points).toHaveLength(points.length); + expect(arrow.fixedSegments).toHaveLength(1); + expect(arrow.fixedSegments![0].index).toBe(index); + expect(arrow.fixedSegments![0].start).toEqual(fixedSegments![0].start); + }); + + it("should put an elbow arrow's fixed segment back when dragging its frame away and back", () => { + API.setAppState({ currentItemArrowType: "elbow" }); + // from rectB (in frame B) to rectA, in frame A + UI.clickTool("arrow"); + mouse.downAt(650, 180); + mouse.moveTo(400, 150); + mouse.moveTo(100, 150); + mouse.up(); + UI.clickTool("selection"); + const arrow = h.elements.find( + (element): element is ExcalidrawElbowArrowElement => + element.type === "arrow", + )!; + expect(arrow.startBinding?.elementId).toBe(rectB.id); + expect(arrow.endBinding?.elementId).toBe(rectA.id); + const index = Math.floor(arrow.points.length / 2); + API.updateElement(arrow, { + frameId: frameA.id, + fixedSegments: [ + { index, start: arrow.points[index - 1], end: arrow.points[index] }, + ], + }); + const points = getPoints(arrow); + + API.setSelectedElements([frameA]); + mouse.downAt(250, 270); + mouse.moveTo(250, 320); + mouse.moveTo(250, 370); + mouse.moveTo(250, 320); + mouse.moveTo(250, 270); + mouse.up(); + + expect(h.app.scene.getElement(frameA.id)?.y).toBe(0); + const nextPoints = getPoints(arrow); + expect(nextPoints).toHaveLength(points.length); + points.forEach(([x, y], index) => { + expect(nextPoints[index][0]).toBeCloseTo(x); + expect(nextPoints[index][1]).toBeCloseTo(y); + }); + }); + + it("should move the midpoints of an arrow bound at both ends to an element in another frame with its frame", () => { + const arrow = drawArrowBetweenFrames(pointFrom(250, 250)); + // a loop on rectB, bending in frame A + API.updateElement(arrow, { + points: [ + arrow.points[arrow.points.length - 1], + pointFrom(arrow.points[1][0] - 300, 100), + arrow.points[arrow.points.length - 1], + ], + startBinding: arrow.endBinding, + }); + const [startPoint, midPoint, endPoint] = getPoints(arrow); + + API.setSelectedElements([frameA]); + mouse.downAt(150, 250); + mouse.moveTo(150, 300); + mouse.moveTo(150, 350); + mouse.up(); + + expect(arrow.startBinding?.elementId).toBe(rectB.id); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + const [nextStartPoint, nextMidPoint, nextEndPoint] = getPoints(arrow); + expect(nextStartPoint[0]).toBeCloseTo(startPoint[0]); + expect(nextStartPoint[1]).toBeCloseTo(startPoint[1]); + expect(nextMidPoint[0]).toBeCloseTo(midPoint[0]); + expect(nextMidPoint[1]).toBeCloseTo(midPoint[1] + 100); + expect(nextEndPoint[0]).toBeCloseTo(endPoint[0]); + expect(nextEndPoint[1]).toBeCloseTo(endPoint[1]); + }); + + it("should keep an arrow bound to an element in another frame when moving its frame from the stats panel", () => { + const arrow = drawArrowBetweenFrames(); + const [startPoint, endPoint] = getPoints(arrow); + + API.setSelectedElements([frameA]); + API.setAppState({ stats: { ...h.state.stats, open: true } }); + UI.updateInput( + UI.queryStatsProperty("Y")!.querySelector(".drag-input")!, + "100", + ); + + expect(h.app.scene.getElement(frameA.id)?.y).toBe(100); + expect(arrow.startBinding?.elementId).toBe(rectA.id); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + const [nextStartPoint, nextEndPoint] = getPoints(arrow); + expect(nextStartPoint[0]).toBeCloseTo(startPoint[0]); + expect(nextStartPoint[1]).toBeCloseTo(startPoint[1] + 100); + expect(nextEndPoint).toEqual(endPoint); + }); + + it("should move an arrow bound to an element in another frame when nudging its frame", () => { + // from empty space in frame A, bending in it + const arrow = drawArrowBetweenFrames(pointFrom(100, 250)); + expect(arrow.startBinding).toBe(null); + API.updateElement(arrow, { + points: [ + arrow.points[0], + pointFrom(100, 0), + arrow.points[arrow.points.length - 1], + ], + }); + const [startPoint, midPoint, endPoint] = getPoints(arrow); + + API.setSelectedElements([frameA]); + Keyboard.keyPress(KEYS.ARROW_RIGHT); + + expect(h.app.scene.getElement(frameA.id)?.x).toBe(ELEMENT_TRANSLATE_AMOUNT); + expect(arrow.endBinding?.elementId).toBe(rectB.id); + const [nextStartPoint, nextMidPoint, nextEndPoint] = getPoints(arrow); + expect(nextStartPoint).toEqual( + pointFrom(startPoint[0] + ELEMENT_TRANSLATE_AMOUNT, startPoint[1]), + ); + expect(nextMidPoint).toEqual( + pointFrom(midPoint[0] + ELEMENT_TRANSLATE_AMOUNT, midPoint[1]), + ); + expect(nextEndPoint).toEqual(endPoint); + }); +}); diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx index bf9bab2056..61ae73af4d 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -101,6 +101,9 @@ import { getHoveredElementForBinding, isBindingEnabled, updateBoundElements, + getFrameArrowIdsToReattach, + isBoundToElementNotIn, + moveFrameArrows, LinearElementEditor, newElementWith, newFrameElement, @@ -157,6 +160,7 @@ import { hasBoundingBox, getFrameChildrenInsertionIndex, isCursorInFrame, + isFrameClippable, addElementsToFrame, replaceAllElementsInFrame, removeElementsFromFrame, @@ -5413,35 +5417,22 @@ class App extends React.Component { } if (isArrowKey(event.key)) { - let selectedElements = this.scene.getSelectedElements({ + const selectedElements = this.scene.getSelectedElements({ selectedElementIds: this.state.selectedElementIds, includeBoundTextElement: true, includeElementsInFrames: true, }); - - const arrowIdsToRemove = new Set(); - - selectedElements - .filter((el): el is NonDeleted => - isBindingElement(el), - ) - .filter((arrow) => { - const startElementNotInSelection = - arrow.startBinding && - !selectedElements.some( - (el) => el.id === arrow.startBinding?.elementId, - ); - const endElementNotInSelection = - arrow.endBinding && - !selectedElements.some( - (el) => el.id === arrow.endBinding?.elementId, - ); - return startElementNotInSelection || endElementNotInSelection; - }) - .forEach((arrow) => arrowIdsToRemove.add(arrow.id)); - - selectedElements = selectedElements.filter( - (el) => !arrowIdsToRemove.has(el.id), + const selectedElementIds = new Set( + selectedElements.map((element) => element.id), + ); + const frameArrowIds = getFrameArrowIdsToReattach(selectedElements); + // arrows bound to unselected elements are moved only by the selected + // ones they're bound to (if any), unless their frame moves them + const movedElements = selectedElements.filter( + (element) => + !isBindingElement(element) || + frameArrowIds.has(element.id) || + !isBoundToElementNotIn(element, selectedElementIds), ); const step = @@ -5466,7 +5457,11 @@ class App extends React.Component { offsetY = step; } - selectedElements.forEach((element) => { + movedElements.forEach((element) => { + if (frameArrowIds.has(element.id)) { + // moved with their frame once the rest has (below) + return; + } this.scene.mutateElement( element, { @@ -5477,10 +5472,13 @@ class App extends React.Component { ); updateBoundElements(element, this.scene, { - simultaneouslyUpdated: selectedElements, + simultaneouslyUpdated: movedElements, renderEnvironment: this.renderEnvironment, }); }); + moveFrameArrows(frameArrowIds, { x: offsetX, y: offsetY }, this.scene, { + renderEnvironment: this.renderEnvironment, + }); this.scene.triggerUpdate(); @@ -6097,6 +6095,7 @@ class App extends React.Component { // iframe-like elements are rendered as DOM overlays and are not // visually clipped by their containing frames !isIframeLikeElement(element) && + isFrameClippable(element, elementsMap) && !isCursorInFrame( { x, y }, containingFrame as NonDeleted, diff --git a/packages/excalidraw/components/Stats/utils.ts b/packages/excalidraw/components/Stats/utils.ts index 48f8f5c9dc..14309ac577 100644 --- a/packages/excalidraw/components/Stats/utils.ts +++ b/packages/excalidraw/components/Stats/utils.ts @@ -16,7 +16,11 @@ import { import { getFrameChildren } from "@excalidraw/element"; -import { updateBindings } from "@excalidraw/element"; +import { + getFrameArrowIdsToReattach, + moveFrameArrows, + updateBindings, +} from "@excalidraw/element"; import { DRAGGING_THRESHOLD } from "@excalidraw/common"; import type { Radians } from "@excalidraw/math"; @@ -193,10 +197,15 @@ export const moveElement = ( originalElementsMap, originalElement.id, ); + const frameArrowIds = getFrameArrowIdsToReattach([ + originalElement, + ...originalChildren, + ]); originalChildren.forEach((child) => { const latestChildElement = elementsMap.get(child.id); - if (!latestChildElement) { + // moved with their frame once the rest has (below) + if (!latestChildElement || frameArrowIds.has(child.id)) { return; } @@ -232,6 +241,10 @@ export const moveElement = ( renderEnvironment, }); }); + moveFrameArrows(frameArrowIds, { x: changeInX, y: changeInY }, scene, { + originalElements: originalElementsMap, + renderEnvironment, + }); } }; diff --git a/packages/excalidraw/lasso/utils.ts b/packages/excalidraw/lasso/utils.ts index f09c401db0..5895314779 100644 --- a/packages/excalidraw/lasso/utils.ts +++ b/packages/excalidraw/lasso/utils.ts @@ -21,6 +21,7 @@ import { getElementBounds, intersectElementWithLineSegment, isBoundToContainer, + isFrameClippable, pointInsideBoundsInclusive, } from "@excalidraw/element"; @@ -158,7 +159,7 @@ const getFrameClipBounds = ( ): Bounds | null => { const frame = getContainingFrame(element, elementsMap); - if (!frame) { + if (!frame || !isFrameClippable(element, elementsMap)) { return null; } diff --git a/packages/excalidraw/renderer/staticScene.ts b/packages/excalidraw/renderer/staticScene.ts index 631454f26e..ad7c95354b 100644 --- a/packages/excalidraw/renderer/staticScene.ts +++ b/packages/excalidraw/renderer/staticScene.ts @@ -16,6 +16,7 @@ import { import { elementOverlapsWithFrame, getTargetFrame, + isFrameClippable, shouldApplyFrameClip, } from "@excalidraw/element"; @@ -433,7 +434,8 @@ const _renderStaticScene = ({ if ( !(element.frameId || appState.frameToHighlight?.id) || !appState.frameRendering.enabled || - !appState.frameRendering.clip + !appState.frameRendering.clip || + !isFrameClippable(element, elementsMap) ) { return; } diff --git a/packages/excalidraw/renderer/staticSvgScene.ts b/packages/excalidraw/renderer/staticSvgScene.ts index 1ef111739f..ca9952f905 100644 --- a/packages/excalidraw/renderer/staticSvgScene.ts +++ b/packages/excalidraw/renderer/staticSvgScene.ts @@ -33,7 +33,7 @@ import { isTextElement, } from "@excalidraw/element"; -import { getContainingFrame } from "@excalidraw/element"; +import { getContainingFrame, isFrameClippable } from "@excalidraw/element"; import { getCornerRadius, isPathALoop } from "@excalidraw/element"; @@ -80,7 +80,11 @@ const maybeWrapNodesInFrameClipPath = ( frameRendering: AppState["frameRendering"], elementsMap: RenderableElementsMap, ) => { - if (!frameRendering.enabled || !frameRendering.clip) { + if ( + !frameRendering.enabled || + !frameRendering.clip || + !isFrameClippable(element, elementsMap) + ) { return null; } const frame = getContainingFrame(element, elementsMap);