Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): Dragged arrow endpoint ignore grid and angle locks (#10972)
Márk Tolmács3b9e1c07f5d3
diff --git a/packages/common/src/points.ts b/packages/common/src/points.tsindex e8f988203b..5eac4fc52d 100644--- a/packages/common/src/points.ts+++ b/packages/common/src/points.ts@@ -1,4 +1,5 @@import {+ pointFrom,pointFromPair,type GlobalPoint,type LocalPoint,@@ -69,12 +70,12 @@ export const getGridPoint = (x: number,y: number,gridSize: NullableGridSize,-): [number, number] => {+): GlobalPoint => {if (gridSize) {- return [+ return pointFrom<GlobalPoint>(Math.round(x / gridSize) * gridSize,Math.round(y / gridSize) * gridSize,- ];+ );}- return [x, y];+ return pointFrom<GlobalPoint>(x, y);};diff --git a/packages/element/src/binding.ts b/packages/element/src/binding.tsindex bf308ae793..74ca3cb98d 100644--- a/packages/element/src/binding.ts+++ b/packages/element/src/binding.ts@@ -1,6 +1,7 @@import {arrayToMap,getFeatureFlag,+ getGridPoint,invariant,isTransparent,} from "@excalidraw/common";@@ -22,7 +23,7 @@ import {} from "@excalidraw/math";import type { LineSegment, LocalPoint, Radians } from "@excalidraw/math";-import type { AppState } from "@excalidraw/excalidraw/types";+import type { AppState, NullableGridSize } from "@excalidraw/excalidraw/types";import type { MapEntry, Mutable } from "@excalidraw/common/utility-types";import type { Bounds } from "@excalidraw/common";@@ -160,6 +161,7 @@ export const bindOrUnbindBindingElement = (altKey?: boolean;angleLocked?: boolean;initialBinding?: boolean;+ gridSize?: NullableGridSize;},) => {const { start, end } = getBindingStrategyForDraggingBindingElementEndpoints(@@ -176,12 +178,18 @@ export const bindOrUnbindBindingElement = (},);+ const isMidpointSnappingEnabled =+ appState.isMidpointSnappingEnabled &&+ !opts?.angleLocked &&+ !appState.gridModeEnabled;+bindOrUnbindBindingElementEdge(arrow,start,"start",scene,appState.isBindingEnabled,+ isMidpointSnappingEnabled,);bindOrUnbindBindingElementEdge(arrow,@@ -189,6 +197,7 @@ export const bindOrUnbindBindingElement = ("end",scene,appState.isBindingEnabled,+ isMidpointSnappingEnabled,);if (start.focusPoint || end.focusPoint) {// If the strategy dictates a focus point override, then@@ -233,6 +242,7 @@ const bindOrUnbindBindingElementEdge = (startOrEnd: "start" | "end",scene: Scene,shouldSnapToOutline = true,+ isMidpointSnappingEnabled = true,): void => {if (mode === null) {// null means break the binding@@ -246,6 +256,7 @@ const bindOrUnbindBindingElementEdge = (scene,focusPoint,shouldSnapToOutline,+ isMidpointSnappingEnabled,);}};@@ -601,6 +612,7 @@ export const getBindingStrategyForDraggingBindingElementEndpoints = (finalize?: boolean;initialBinding?: boolean;zoom?: AppState["zoom"];+ gridSize?: NullableGridSize;},): { start: BindingStrategy; end: BindingStrategy } => {if (getFeatureFlag("COMPLEX_BINDINGS")) {@@ -641,6 +653,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (finalize?: boolean;initialBinding?: boolean;zoom?: AppState["zoom"];+ gridSize?: NullableGridSize;},): { start: BindingStrategy; end: BindingStrategy } => {const startIdx = 0;@@ -706,7 +719,9 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (elementsMap,);const hit = getHoveredElementForBinding(- globalPoint,+ opts?.angleLocked || appState.gridModeEnabled+ ? pointFrom<GlobalPoint>(scenePointerX, scenePointerY)+ : globalPoint,elements,elementsMap,maxBindingDistance_simple(appState.zoom),@@ -758,7 +773,11 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (? globalPoint: // NOTE: Can only affect the start point because new arrows always drag the end pointopts?.newArrow- ? appState.selectedLinearElement!.initialState.origin!+ ? getGridPoint(+ appState.selectedLinearElement!.initialState.origin![0],+ appState.selectedLinearElement!.initialState.origin![1],+ opts.gridSize as NullableGridSize,+ ): LinearElementEditor.getPointAtIndexGlobalCoordinates(arrow,0,@@ -817,12 +836,29 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (focusPoint:projectFixedPointOntoDiagonal(arrow,- globalPoint,+ opts?.angleLocked+ ? globalPoint+ : appState.gridModeEnabled+ ? snapBoundPointToGrid(+ pointFrom<GlobalPoint>(scenePointerX, scenePointerY),+ hit,+ elementsMap,+ appState.gridSize as NullableGridSize,+ arrow,+ LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ startDragged ? 1 : -2,+ elementsMap,+ ),+ )+ : globalPoint,hit,startDragged ? "start" : "end",elementsMap,appState.zoom,- appState.isMidpointSnappingEnabled,+ appState.isMidpointSnappingEnabled &&+ !opts?.angleLocked &&+ !appState.gridModeEnabled,) || globalPoint,}: { mode: null };@@ -867,7 +903,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (startDragged ? "end" : "start",elementsMap,appState.zoom,- appState.isMidpointSnappingEnabled,+ false,) || otherEndpoint,}: { mode: undefined }@@ -1035,6 +1071,7 @@ export const bindBindingElement = (scene: Scene,focusPoint?: GlobalPoint,shouldSnapToOutline = true,+ isMidpointSnappingEnabled = true,): void => {const elementsMap = scene.getNonDeletedElementsMap();@@ -1050,6 +1087,7 @@ export const bindBindingElement = (startOrEnd,elementsMap,shouldSnapToOutline,+ isMidpointSnappingEnabled,),};} else {@@ -1763,6 +1801,86 @@ const extractBinding = (};};+/**+ * Snaps a bound arrow endpoint to the grid on the axis parallel to the+ * bindable element's side, while preserving the binding gap distance on the+ * perpendicular axis. In other words, the grid axis closest to the side's+ * perpendicular (normal) is used as the snap axis and the other axis is kept at+ * the binding gap distance.+ */+const snapBoundPointToGrid = (+ outlinePoint: GlobalPoint,+ bindableElement: ExcalidrawBindableElement,+ elementsMap: ElementsMap,+ gridSize: NullableGridSize,+ arrowElement: ExcalidrawArrowElement,+ adjacentPoint?: GlobalPoint,+): GlobalPoint => {+ if (!gridSize) {+ return outlinePoint;+ }++ const aabb = aabbForElement(bindableElement, elementsMap);+ // For ellipses and diamonds use the arrow's incoming direction instead of+ // the position-based heading, which can give the wrong axis when the+ // outline point is near a cardinal zone or an angled diamond face.+ const heading =+ adjacentPoint &&+ (bindableElement.type === "ellipse" || bindableElement.type === "diamond")+ ? vectorToHeading(vectorFromPoint(adjacentPoint, outlinePoint))+ : headingForPointFromElement(bindableElement, aabb, outlinePoint);++ const bindingGap = getBindingGap(bindableElement, arrowElement);+ const extent =+ Math.max(bindableElement.width, bindableElement.height) + bindingGap * 2;+ const center = getCenterForBounds(aabb);++ // Both heading strategies above return global-axis directions.+ const absNX = Math.abs(heading[0]);+ const absNY = Math.abs(heading[1]);+ if (absNX >= absNY) {+ // Global X is closest to the perpendicular so snap Y, intersect horizontal line+ const [, snappedY] = getGridPoint(+ outlinePoint[0],+ outlinePoint[1],+ gridSize,+ );+ const intersector = lineSegment<GlobalPoint>(+ pointFrom<GlobalPoint>(center[0] - extent, snappedY),+ pointFrom<GlobalPoint>(center[0] + extent, snappedY),+ );+ const intersection = intersectElementWithLineSegment(+ bindableElement,+ elementsMap,+ intersector,+ bindingGap,+ ).sort(+ (a, b) =>+ pointDistanceSq(a, outlinePoint) - pointDistanceSq(b, outlinePoint),+ )[0];++ return intersection ?? pointFrom<GlobalPoint>(outlinePoint[0], snappedY);+ }++ // Global Y is closest to the perpendicular so snap X, intersect vertical line+ const [snappedX] = getGridPoint(outlinePoint[0], outlinePoint[1], gridSize);+ const intersector = lineSegment<GlobalPoint>(+ pointFrom<GlobalPoint>(snappedX, center[1] - extent),+ pointFrom<GlobalPoint>(snappedX, center[1] + extent),+ );+ const intersection = intersectElementWithLineSegment(+ bindableElement,+ elementsMap,+ intersector,+ bindingGap,+ ).sort(+ (a, b) =>+ pointDistanceSq(a, outlinePoint) - pointDistanceSq(b, outlinePoint),+ )[0];++ return intersection ?? pointFrom<GlobalPoint>(snappedX, outlinePoint[1]);+};+const elementArea = (element: ExcalidrawBindableElement) =>element.width * element.height;diff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.tsindex 40c20dd3fc..044b4fef83 100644--- a/packages/element/src/linearElementEditor.ts+++ b/packages/element/src/linearElementEditor.ts@@ -359,6 +359,7 @@ export class LinearElementEditor {linearElementEditor,);+ const angleLocked = shouldRotateWithDiscreteAngle(event);LinearElementEditor.movePoints(element,app.scene,@@ -370,7 +371,10 @@ export class LinearElementEditor {},{isBindingEnabled: app.state.isBindingEnabled,- isMidpointSnappingEnabled: app.state.isMidpointSnappingEnabled,+ isMidpointSnappingEnabled:+ app.state.isMidpointSnappingEnabled &&+ !angleLocked &&+ !app.state.gridModeEnabled,},);// Set the suggested binding from the updates if available@@ -427,7 +431,9 @@ export class LinearElementEditor {"start",elementsMap,app.state.zoom,- app.state.isMidpointSnappingEnabled,+ app.state.isMidpointSnappingEnabled &&+ !angleLocked &&+ !app.state.gridModeEnabled,): linearElementEditor.initialState.altFocusPoint,},@@ -554,6 +560,8 @@ export class LinearElementEditor {linearElementEditor,);+ const angleLocked =+ shouldRotateWithDiscreteAngle(event) && singlePointDragged;LinearElementEditor.movePoints(element,app.scene,@@ -565,7 +573,10 @@ export class LinearElementEditor {},{isBindingEnabled: app.state.isBindingEnabled,- isMidpointSnappingEnabled: app.state.isMidpointSnappingEnabled,+ isMidpointSnappingEnabled:+ app.state.isMidpointSnappingEnabled &&+ !angleLocked &&+ !app.state.gridModeEnabled,},);@@ -661,7 +672,9 @@ export class LinearElementEditor {"start",elementsMap,app.state.zoom,- app.state.isMidpointSnappingEnabled,+ app.state.isMidpointSnappingEnabled &&+ !angleLocked &&+ !app.state.gridModeEnabled,): linearElementEditor.initialState.altFocusPoint,},@@ -2176,6 +2189,7 @@ const pointDraggingUpdates = (newArrow: !!app.state.newElement,angleLocked,altKey,+ gridSize: app.getEffectiveGridSize(),},);diff --git a/packages/excalidraw/actions/actionFinalize.tsx b/packages/excalidraw/actions/actionFinalize.tsxindex c5dc9f3d72..eaa0c9201b 100644--- a/packages/excalidraw/actions/actionFinalize.tsx+++ b/packages/excalidraw/actions/actionFinalize.tsx@@ -27,7 +27,7 @@ import { isInvisiblySmallElement } from "@excalidraw/element";import { CaptureUpdateAction } from "@excalidraw/element";-import type { GlobalPoint, LocalPoint } from "@excalidraw/math";+import type { LocalPoint } from "@excalidraw/math";import type {ExcalidrawElement,ExcalidrawLinearElement,@@ -94,32 +94,40 @@ export const actionFinalize = register<FormData>({? [element.points.length - 1] // New arrow creation: appState.selectedLinearElement.selectedPointsIndices;+ const angleLocked = shouldRotateWithDiscreteAngle(event);+ const effectiveGridSize = event[KEYS.CTRL_OR_CMD]+ ? null+ : app.getEffectiveGridSize();+const draggedPoints: PointsPositionUpdates =selectedPointsIndices.reduce((map, index) => {map.set(index, {- point: LinearElementEditor.pointFromAbsoluteCoords(- element,- pointFrom<GlobalPoint>(- sceneCoords.x - linearElementEditor.pointerOffset.x,- sceneCoords.y - linearElementEditor.pointerOffset.y,- ),- elementsMap,- ),+ point: angleLocked+ ? element.points[index]+ : LinearElementEditor.createPointAt(+ element,+ elementsMap,+ sceneCoords.x - linearElementEditor.pointerOffset.x,+ sceneCoords.y - linearElementEditor.pointerOffset.y,+ effectiveGridSize,+ ),});return map;}, new Map()) ?? new Map();+bindOrUnbindBindingElement(element,draggedPoints,- sceneCoords.x - linearElementEditor.pointerOffset.x,- sceneCoords.y - linearElementEditor.pointerOffset.y,+ sceneCoords.x,+ sceneCoords.y,scene,appState,{newArrow,altKey: event.altKey,- angleLocked: shouldRotateWithDiscreteAngle(event),+ angleLocked,+ gridSize: app.getEffectiveGridSize(),},);} else if (isLineElement(element)) {diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex ae202a3a6f..cfb93a3100 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -7574,14 +7574,16 @@ class App extends React.Component<AppProps, AppState> {return;}- if (this.state.activeTool.type === "arrow") {+ // Set suggested binding if we're hovering with an arrow tool+ // and not dragging out a new element+ if (this.state.activeTool.type === "arrow" && !this.state.newElement) {+ const scenePointer = pointFrom<GlobalPoint>(scenePointerX, scenePointerY);const hit = getHoveredElementForBinding(- pointFrom<GlobalPoint>(scenePointerX, scenePointerY),+ scenePointer,this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap(),maxBindingDistance_simple(this.state.zoom),);- const scenePointer = pointFrom<GlobalPoint>(scenePointerX, scenePointerY);const elementsMap = this.scene.getNonDeletedElementsMap();if (hit && !isPointInElement(scenePointer, hit, elementsMap)) {this.setState({diff --git a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx b/packages/excalidraw/components/canvases/InteractiveCanvas.tsxindex dc7dcd9f9b..29ac8999ca 100644--- a/packages/excalidraw/components/canvases/InteractiveCanvas.tsx+++ b/packages/excalidraw/components/canvases/InteractiveCanvas.tsx@@ -253,6 +253,7 @@ const getRelevantAppStateProps = (newElement: appState.newElement,isBindingEnabled: appState.isBindingEnabled,isMidpointSnappingEnabled: appState.isMidpointSnappingEnabled,+ gridModeEnabled: appState.gridModeEnabled,suggestedBinding: appState.suggestedBinding,isRotating: appState.isRotating,elementsToHighlight: appState.elementsToHighlight,diff --git a/packages/excalidraw/renderer/interactiveScene.ts b/packages/excalidraw/renderer/interactiveScene.tsindex bd0dc8d8ca..31a6ca8886 100644--- a/packages/excalidraw/renderer/interactiveScene.ts+++ b/packages/excalidraw/renderer/interactiveScene.ts@@ -17,6 +17,7 @@ import {FRAME_STYLE,getFeatureFlag,invariant,+ shouldRotateWithDiscreteAngle,THEME,} from "@excalidraw/common";@@ -227,6 +228,7 @@ const renderBindingHighlightForBindableElement_simple = (elementsMap: ElementsMap,appState: InteractiveCanvasAppState,pointerCoords: GlobalPoint | null,+ angleLocked = false,) => {const enclosingFrame =suggestedBinding.element.frameId &&@@ -413,6 +415,8 @@ const renderBindingHighlightForBindableElement_simple = (if (appState.isMidpointSnappingEnabled &&+ !appState.gridModeEnabled &&+ !angleLocked &&(isFrameLikeElement(suggestedBinding.element) ||isBindableElement(suggestedBinding.element))) {@@ -805,7 +809,12 @@ const renderBindingHighlightForBindableElement_complex = (context.restore();- if (appState.isMidpointSnappingEnabled) {+ if (+ appState.isMidpointSnappingEnabled &&+ !appState.gridModeEnabled &&+ (!app.lastPointerMoveEvent ||+ !shouldRotateWithDiscreteAngle(app.lastPointerMoveEvent))+ ) {// Draw midpoint indicatorscontext.save();context.translate(@@ -918,12 +927,16 @@ const renderBindingHighlightForBindableElement = (app.lastPointerMoveCoords.y,): null;+ const angleLocked =+ !!app.lastPointerMoveEvent &&+ shouldRotateWithDiscreteAngle(app.lastPointerMoveEvent);renderBindingHighlightForBindableElement_simple(context,suggestedBinding,allElementsMap,appState,pointerCoords,+ angleLocked,);context.restore();};diff --git a/packages/excalidraw/tests/arrowBinding.test.tsx b/packages/excalidraw/tests/arrowBinding.test.tsxindex 879b4b67eb..a092b5af0e 100644--- a/packages/excalidraw/tests/arrowBinding.test.tsx+++ b/packages/excalidraw/tests/arrowBinding.test.tsx@@ -18,7 +18,7 @@ import { actionToggleArrowBinding } from "../actions/actionToggleArrowBinding";import { Excalidraw, sceneCoordsToViewportCoords } from "../index";import { API } from "./helpers/api";-import { Pointer, UI } from "./helpers/ui";+import { Keyboard, Pointer, UI } from "./helpers/ui";import {render,fireEvent,@@ -329,7 +329,7 @@ describe("Arrow binding – non-default case (bindingPreference: disabled)", ()// -------------------------------------------------------------------------// Arrow does snap to midpoint when isMidpointSnappingEnabled is true// -------------------------------------------------------------------------- describe("Arrow doesn't snap to midpoint when midpoint snapping is disabled", () => {+ describe("Midpoint snapping", () => {it("does not snap to midpoint when midpoint snapping is turned off", () => {const rect = API.createElement({type: "rectangle",@@ -375,6 +375,133 @@ describe("Arrow binding – non-default case (bindingPreference: disabled)", ()expect(snappedWithMidpoint).toEqual([500, 200]);expect(snappedWithoutMidpoint).not.toEqual([500, 200]);});++ it("does not snap an angle-locked elbow binding to midpoint on finalize", async () => {+ const rect = API.createElement({+ type: "rectangle",+ id: "rect-elbow-angle-lock",+ x: 600,+ y: 300,+ width: 200,+ height: 200,+ }) as ExcalidrawBindableElement;+ API.setElements([rect]);+ API.setAppState({+ currentItemArrowType: "elbow",+ gridModeEnabled: false,+ isMidpointSnappingEnabled: true,+ });++ const start = sceneCoordsToViewportCoords(+ { sceneX: 480, sceneY: 392 },+ h.state,+ );+ const target = sceneCoordsToViewportCoords(+ { sceneX: 596, sceneY: 397 },+ h.state,+ );++ UI.clickTool("arrow");+ mouse.downAt(start.x, start.y);+ Keyboard.withModifierKeys({ shift: true }, () => {+ mouse.moveTo(target.x, target.y);+ mouse.upAt();+ });++ await waitFor(() => {+ const arrow = h.elements.find(isElbowArrow);+ expect(arrow).toBeDefined();+ expect(arrow!.endBinding?.elementId).toBe(rect.id);++ const endY = arrow!.y + arrow!.points.at(-1)![1];+ expect(endY).toBeCloseTo(397, 1);+ });+ });+ });++ describe("Grid binding interactions", () => {+ it("does not snap angle-locked binding to grid when grid mode is disabled", async () => {+ const rect = API.createElement({+ type: "rectangle",+ id: "rect-angle-lock-no-grid",+ x: 600,+ y: 300,+ width: 200,+ height: 200,+ }) as ExcalidrawBindableElement;+ API.setElements([rect]);+ API.setAppState({ gridModeEnabled: false, gridSize: 20 });++ const start = sceneCoordsToViewportCoords(+ { sceneX: 300, sceneY: 333 },+ h.state,+ );+ const target = sceneCoordsToViewportCoords(+ { sceneX: 596, sceneY: 347 },+ h.state,+ );++ UI.clickTool("arrow");+ mouse.downAt(start.x, start.y);+ Keyboard.withModifierKeys({ shift: true }, () => {+ mouse.moveTo(target.x, target.y);+ mouse.upAt();+ });++ await waitFor(() => {+ const arrow = h.elements.find(+ (element): element is ExcalidrawArrowElement =>+ element.type === "arrow",+ );+ expect(arrow).toBeDefined();+ expect(arrow!.endBinding?.elementId).toBe(rect.id);++ const startY = arrow!.y + arrow!.points[0][1];+ const endY = arrow!.y + arrow!.points.at(-1)![1];+ expect(endY).toBeCloseTo(startY);+ });+ });++ it("uses the incoming direction to choose the grid axis for rotated bindables", async () => {+ const ellipse = API.createElement({+ type: "ellipse",+ id: "ellipse-rotated-grid-binding",+ x: 610,+ y: 300,+ width: 240,+ height: 120,+ angle: Math.PI / 3,+ }) as ExcalidrawBindableElement;+ API.setElements([ellipse]);+ API.setAppState({ gridModeEnabled: true, gridSize: 20 });++ const start = sceneCoordsToViewportCoords(+ { sceneX: 400, sceneY: 360 },+ h.state,+ );+ const target = sceneCoordsToViewportCoords(+ { sceneX: 658, sceneY: 360 },+ h.state,+ );++ UI.clickTool("arrow");+ mouse.downAt(start.x, start.y);+ mouse.moveTo(target.x, target.y);+ mouse.upAt();++ await waitFor(() => {+ const arrow = h.elements.find(+ (element): element is ExcalidrawArrowElement =>+ element.type === "arrow",+ );+ expect(arrow).toBeDefined();+ expect(arrow!.endBinding?.elementId).toBe(ellipse.id);++ const startY = arrow!.y + arrow!.points[0][1];+ const endY = arrow!.y + arrow!.points.at(-1)![1];+ expect(endY).toBeCloseTo(startY, 1);+ });+ });});// -------------------------------------------------------------------------diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.tsindex 75624d2c74..700f0698c1 100644--- a/packages/excalidraw/types.ts+++ b/packages/excalidraw/types.ts@@ -227,6 +227,7 @@ export type InteractiveCanvasAppState = Readonly<newElement: AppState["newElement"];isBindingEnabled: AppState["isBindingEnabled"];isMidpointSnappingEnabled: AppState["isMidpointSnappingEnabled"];+ gridModeEnabled: AppState["gridModeEnabled"];suggestedBinding: AppState["suggestedBinding"];isRotating: AppState["isRotating"];elementsToHighlight: AppState["elementsToHighlight"];@@ -914,6 +915,7 @@ export type AppClassProperties = {onStateChange: App["onStateChange"];lastPointerMoveCoords: App["lastPointerMoveCoords"];+ lastPointerMoveEvent: App["lastPointerMoveEvent"];bindModeHandler: App["bindModeHandler"];setAppState: App["setAppState"];