Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): don't clip arrows to their frames (#12516)
David Luzardd2f8fc32b92
diff --git a/dev-docs/docs/codebase/frames.mdx b/dev-docs/docs/codebase/frames.mdxindex 67c84b7921..efab39edb5 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, but only while one of their ends is in it: bound to an element in the frame, or, unbound, inside it (see `removeArrowsWithoutEndInFrame`). An arrow bound only to elements outside the frame thus leaves 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.tsindex 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,- );+ scene,+ getBoundPointUpdates(arrow, elementsMap),+ 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<ExcalidrawArrowElement>,+ 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<PointsPositionUpdates>;+ if (point) {+ return [+ bindingProp === "startBinding" ? 0 : arrow.points.length - 1,+ { point },+ ] as MapEntry<PointsPositionUpdates>;+ }}- }- return null;- },- ).filter(- (update): update is MapEntry<PointsPositionUpdates> => update !== null,+ return null;+ },+ ).filter(+ (update): update is MapEntry<PointsPositionUpdates> => update !== null,+ ),);- LinearElementEditor.movePoints(arrow, scene, new Map(updates), undefined, {- moveMidPointsWithElement:- boundElementMoved &&- !!startBindingElement &&- startBindingElement?.id === endBindingElement?.id,- });-+/** Rewraps `arrow`'s label (if any) along it as placed. */+const updateArrowLabel = (+ arrow: NonDeleted<ExcalidrawArrowElement>,+ 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<ExcalidrawElement["id"]>,+) =>+ (!!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<ExcalidrawElement["id"]> => {+ const movedElementIds = getSimultaneouslyUpdatedElementIds(movedElements);+ const ids = new Set<ExcalidrawElement["id"]>();+ 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<ExcalidrawElement["id"]>,+ 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.tsindex 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 = <T extends ExcalidrawElement>({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.tsindex 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.tsindex 49c65aee24..d68fd8fa30 100644--- a/packages/element/src/frame.ts+++ b/packages/element/src/frame.ts@@ -32,7 +32,9 @@ import {import { mutateElement } from "./mutateElement";import { getBoundTextElement, getContainerElement } from "./textElement";import { syncMovedIndices } from "./fractionalIndex";+import { LinearElementEditor } from "./linearElementEditor";import {+ isArrowElement,isFrameElement,isFrameLikeElement,isTextElement,@@ -45,6 +47,7 @@ import type { ExcalidrawElementsIncludingDeleted } from "./Scene";import type {ElementsMap,ElementsMapOrArray,+ ExcalidrawArrowElement,ExcalidrawElement,ExcalidrawFrameLikeElement,NonDeleted,@@ -470,6 +473,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 -------------------------------/** */@@ -700,6 +721,70 @@ export const removeElementsFromFrame = (}};+/**+ * Whether one of the arrow's ends is in the frame: bound to an element in it,+ * or, unbound, inside it. An arrow belongs to a frame only while one is.+ */+export const isArrowEndInFrame = (+ arrow: ExcalidrawArrowElement,+ frame: ExcalidrawFrameLikeElement,+ elementsMap: ElementsMap,+) => {+ const [x1, y1, x2, y2] = getElementAbsoluteCoords(frame, elementsMap);+ return [arrow.startBinding, arrow.endBinding].some((binding, index) =>+ binding+ ? elementsMap.get(binding.elementId)?.frameId === frame.id+ : isPointWithinBounds(+ pointFrom(x1, y1),+ LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ index ? -1 : 0,+ elementsMap,+ ),+ pointFrom(x2, y2),+ ),+ );+};++/**+ * Takes the arrows among `elements`, and those bound to them, that have no end+ * in their frame (see `isArrowEndInFrame()`) out of it. Call it once their ends+ * (and the elements they're bound to) may have left it. Arrows in groups are+ * left to their group.+ */+export const removeArrowsWithoutEndInFrame = (+ elements: Iterable<ExcalidrawElement>,+ elementsMap: ElementsMap,+) => {+ const arrows = new Set<ExcalidrawArrowElement>();+ for (const element of elements) {+ if (isArrowElement(element)) {+ arrows.add(element);+ }+ for (const { id, type } of element.boundElements ?? []) {+ const arrow = type === "arrow" ? elementsMap.get(id) : undefined;+ if (isArrowElement(arrow)) {+ arrows.add(arrow);+ }+ }+ }++ const arrowsToRemove = [];+ for (const arrow of arrows) {+ const frame = arrow.frameId ? elementsMap.get(arrow.frameId) : undefined;+ if (+ !arrow.isDeleted &&+ !arrow.groupIds.length &&+ frame &&+ isFrameLikeElement(frame) &&+ !isArrowEndInFrame(arrow, frame, elementsMap)+ ) {+ arrowsToRemove.push(arrow);+ }+ }+ removeElementsFromFrame(arrowsToRemove, elementsMap);+};+export const removeAllElementsFromFrame = <T extends ExcalidrawElement>(allElements: readonly T[],frame: ExcalidrawFrameLikeElement,@@ -714,11 +799,13 @@ export const replaceAllElementsInFrame = <T extends ExcalidrawElement>(nextElementsInFrame: ExcalidrawElement[],frame: ExcalidrawFrameLikeElement,): T[] => {- return addElementsToFrame(+ const nextElements = addElementsToFrame(removeAllElementsFromFrame(allElements, frame),nextElementsInFrame,frame,).slice();+ removeArrowsWithoutEndInFrame(nextElementsInFrame, arrayToMap(nextElements));+ return nextElements;};/** does not mutate elements, but returns new ones */@@ -943,7 +1030,11 @@ export const shouldApplyFrameClip = (elementsMap: ElementsMap,checkedGroups?: Map<string, boolean>,) => {- if (!appState.frameRendering || !appState.frameRendering.clip) {+ if (+ !appState.frameRendering ||+ !appState.frameRendering.clip ||+ !isFrameClippable(element, elementsMap)+ ) {return false;}@@ -1017,16 +1108,25 @@ export const getElementsOverlappingFrame = <T extends ExcalidrawElement>(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.tsindex 3efc3bff16..033b6275a1 100644--- a/packages/element/src/mutateElement.ts+++ b/packages/element/src/mutateElement.ts@@ -65,8 +65,8 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(...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<ExcalidrawElbowArrowElement>,diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsxindex 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<ExcalidrawElbowArrowElement>;+ 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.tsxindex 4cbb310abc..002b5bdabf 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,408 @@ describe("adding elements to frames", () => {});});});++describe("arrows in frames", () => {+ // frame A and frame B side by side, a rectangle in each+ let frameA: NonDeleted<ExcalidrawFrameLikeElement>;+ let frameB: NonDeleted<ExcalidrawFrameLikeElement>;+ let rectA: NonDeletedExcalidrawElement;+ let rectB: NonDeletedExcalidrawElement;++ beforeEach(async () => {+ await render(<Excalidraw handleKeyboardGlobally={true} />);+ 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<GlobalPoint>(100, 150),+ end = pointFrom<GlobalPoint>(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<LocalPoint>(0, 0), pointFrom<LocalPoint>(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 take an arrow out of its frame when neither of its ends is in it", () => {+ const rectC = API.createElement({+ type: "rectangle",+ x: -300,+ y: 100,+ width: 100,+ height: 100,+ backgroundColor: "red",+ fillStyle: "solid",+ });+ API.setElements([rectC, ...h.elements]);+ // from inside frame A+ const arrow = drawArrowBetweenFrames(pointFrom<GlobalPoint>(250, 250));++ // onto rectC, crossing frame A+ mouse.downAt(250, 250);+ mouse.moveTo(-250, 150);+ mouse.up();++ expect(arrow.startBinding?.elementId).toBe(rectC.id);+ expect(arrow.frameId).toBe(null);+ });++ it("should take an arrow out of its frame when what it's bound to in it leaves it", () => {+ const arrow = drawArrowBetweenFrames();++ mouse.downAt(60, 110);+ mouse.moveTo(-240, 110);+ mouse.up();++ expect(rectA.frameId).toBe(null);+ expect(arrow.startBinding?.elementId).toBe(rectA.id);+ expect(arrow.frameId).toBe(null);+ });++ /** an arrow in frame A, just inside its right edge */+ const createArrowAtFrameEdge = () => {+ const arrow = API.createElement({+ type: "arrow",+ x: 291,+ y: 50,+ width: 5,+ height: 0,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(5, 0)],+ frameId: frameA.id,+ });+ API.setElements([...h.elements, arrow]);+ API.setSelectedElements([arrow]);+ return arrow;+ };++ it("should take an arrow out of its frame when nudging its ends out of it", () => {+ const arrow = createArrowAtFrameEdge();++ Keyboard.withModifierKeys({ shift: true }, () => {+ Keyboard.keyPress(KEYS.ARROW_RIGHT);+ });+ expect(arrow.frameId).toBe(frameA.id);+ Keyboard.withModifierKeys({ shift: true }, () => {+ Keyboard.keyPress(KEYS.ARROW_RIGHT);+ });+ expect(arrow.frameId).toBe(null);+ });++ it("should take an arrow out of its frame when moving its ends out of it from the stats panel", () => {+ const arrow = createArrowAtFrameEdge();++ API.setAppState({ stats: { ...h.state.stats, open: true } });+ UI.updateInput(+ UI.queryStatsProperty("X")!.querySelector(".drag-input")!,+ "350",+ );++ expect(arrow.x).toBe(350);+ expect(arrow.frameId).toBe(null);+ });++ it("should take an arrow out of its frame when resizing the frame leaves its ends out", () => {+ const arrow = drawArrowBetweenFrames();++ UI.resize(frameA, "w", [200, 0]);++ expect(rectA.frameId).toBe(null);+ expect(arrow.frameId).toBe(null);+ });++ 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<GlobalPoint>(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<GlobalPoint>(250, 250));+ // a loop on rectB, bending in frame A+ API.updateElement(arrow, {+ points: [+ arrow.points[arrow.points.length - 1],+ pointFrom<LocalPoint>(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<GlobalPoint>(100, 250));+ expect(arrow.startBinding).toBe(null);+ API.updateElement(arrow, {+ points: [+ arrow.points[0],+ pointFrom<LocalPoint>(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/CHANGELOG.md b/packages/excalidraw/CHANGELOG.mdindex f2050e6f76..05aa2f97d8 100644--- a/packages/excalidraw/CHANGELOG.md+++ b/packages/excalidraw/CHANGELOG.md@@ -13,6 +13,12 @@ Please add the latest change on the top under the correct section.## Unreleased+### Arrows aren't clipped to frames (2026-10-31) [#12516](https://github.com/excalidraw/excalidraw/pull/12516)++- Arrows and their labels are no longer clipped to the frame they belong to, so they can connect elements across and out of frames, and their part outside the frame can be selected. They still belong to their frame, so they're moved, copied and deleted with it, but only while one of their ends is in it (bound to an element in the frame, or inside it). An arrow whose ends both leave its frame (moved, bound to elements outside it, or with the elements it's bound to) leaves the frame.+- Exporting a frame (and `getElementsOverlappingFrame`) now includes other frames' arrows that reach into it, like other elements overlapping it.+- Moving a frame (dragging it, with the arrow keys or from the stats panel) keeps its arrows bound to the elements that don't move with it, instead of unbinding them.+### Flowchart navigation (2026-10-30) [#12502](https://github.com/excalidraw/excalidraw/pull/12502)- Alt+arrow keys move the selection to the flowchart node that's visually next in that direction, whether or not it's linked to the selected node. They used to follow only the arrows bound to the pressed side, cycle through siblings on repeated presses, and fall back to any linked node when nothing was that way.diff --git a/packages/excalidraw/actions/actionFinalize.tsx b/packages/excalidraw/actions/actionFinalize.tsxindex 69d208d40f..50b2e56a74 100644--- a/packages/excalidraw/actions/actionFinalize.tsx+++ b/packages/excalidraw/actions/actionFinalize.tsx@@ -5,6 +5,7 @@ import {isValidPolygon,LinearElementEditor,newElementWith,+ removeArrowsWithoutEndInFrame,} from "@excalidraw/element";import {@@ -146,6 +147,8 @@ export const actionFinalize = register<FormData>({});}}+ // with its ends where they ended up+ removeArrowsWithoutEndInFrame([element], elementsMap);if (linearElementEditor !== appState.selectedLinearElement) {// `handlePointerUp()` updated the linear element instance,diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.tsindex da95743f71..0fedf01d15 100644--- a/packages/excalidraw/components/App.selectionTool.ts+++ b/packages/excalidraw/components/App.selectionTool.ts@@ -44,6 +44,7 @@ import {transformElements,uncropElementSides,updateBoundElements,+ removeArrowsWithoutEndInFrame,updateFrameMembershipOfSelectedElements,} from "@excalidraw/element";import {@@ -1217,6 +1218,8 @@ export class AppSelectionTool {this.app.state,this.app,);+ // the dragged arrows, and those bound to the dragged elements+ removeArrowsWithoutEndInFrame(selectedElements, nextElements);this.app.scene.replaceAllElements(nextElements);};diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex bf9bab2056..88144c4907 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,8 +160,10 @@ import {hasBoundingBox,getFrameChildrenInsertionIndex,isCursorInFrame,+ isFrameClippable,addElementsToFrame,replaceAllElementsInFrame,+ removeArrowsWithoutEndInFrame,removeElementsFromFrame,getElementsInResizingFrame,getElementsInNewFrame,@@ -5413,35 +5418,22 @@ class App extends React.Component<AppProps, AppState> {}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<string>();-- selectedElements- .filter((el): el is NonDeleted<ExcalidrawArrowElement> =>- 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 +5458,11 @@ class App extends React.Component<AppProps, AppState> {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 +5473,18 @@ class App extends React.Component<AppProps, AppState> {);updateBoundElements(element, this.scene, {- simultaneouslyUpdated: selectedElements,+ simultaneouslyUpdated: movedElements,renderEnvironment: this.renderEnvironment,});});+ moveFrameArrows(frameArrowIds, { x: offsetX, y: offsetY }, this.scene, {+ renderEnvironment: this.renderEnvironment,+ });+ // a moved arrow's ends may have left its frame+ removeArrowsWithoutEndInFrame(+ movedElements,+ this.scene.getNonDeletedElementsMap(),+ );this.scene.triggerUpdate();@@ -6097,6 +6101,7 @@ class App extends React.Component<AppProps, AppState> {// 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<ExcalidrawFrameLikeElement>,diff --git a/packages/excalidraw/components/Stats/utils.ts b/packages/excalidraw/components/Stats/utils.tsindex 48f8f5c9dc..6400476e89 100644--- a/packages/excalidraw/components/Stats/utils.ts+++ b/packages/excalidraw/components/Stats/utils.ts@@ -16,7 +16,12 @@ import {import { getFrameChildren } from "@excalidraw/element";-import { updateBindings } from "@excalidraw/element";+import {+ getFrameArrowIdsToReattach,+ moveFrameArrows,+ removeArrowsWithoutEndInFrame,+ updateBindings,+} from "@excalidraw/element";import { DRAGGING_THRESHOLD } from "@excalidraw/common";import type { Radians } from "@excalidraw/math";@@ -193,10 +198,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,7 +242,17 @@ export const moveElement = (renderEnvironment,});});+ moveFrameArrows(frameArrowIds, { x: changeInX, y: changeInY }, scene, {+ originalElements: originalElementsMap,+ renderEnvironment,+ });}++ // a moved arrow's ends may have left its frame+ removeArrowsWithoutEndInFrame(+ [latestElement],+ scene.getNonDeletedElementsMap(),+ );};export const getAtomicUnits = (diff --git a/packages/excalidraw/lasso/utils.ts b/packages/excalidraw/lasso/utils.tsindex 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.tsindex 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.tsindex 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);