Virtual whiteboard for sketching hand-drawn like diagrams
fix(editor): Binding follow-ups to #10753 (#12156)
David Luzardc2c16d9e207
diff --git a/packages/common/src/constants.ts b/packages/common/src/constants.tsindex 4d407c988f..d3927b4d52 100644--- a/packages/common/src/constants.ts+++ b/packages/common/src/constants.ts@@ -2,7 +2,11 @@ import type {ExcalidrawElement,FontFamilyValues,} from "@excalidraw/element/types";-import type { AppProps, AppState } from "@excalidraw/excalidraw/types";+import type {+ AppProps,+ AppState,+ NormalizedZoomValue,+} from "@excalidraw/excalidraw/types";import { COLOR_PALETTE } from "./colors";@@ -349,6 +353,10 @@ export const SCROLL_TIMEOUT = 100;export const ZOOM_STEP = 0.1;export const MIN_ZOOM = 0.1;export const MAX_ZOOM = 30;+/** 100% zoom, for computations that have no editor zoom to go by */+export const DEFAULT_ZOOM: AppState["zoom"] = Object.freeze({+ value: 1 as NormalizedZoomValue,+});export const HYPERLINK_TOOLTIP_DELAY = 300;// Report a user inactive after IDLE_THRESHOLD millisecondsdiff --git a/packages/element/src/collision.ts b/packages/element/src/collision.tsindex 809d26ea9b..c548080bf0 100644--- a/packages/element/src/collision.ts+++ b/packages/element/src/collision.ts@@ -339,10 +339,19 @@ type BindingCandidate = {distance: number;};+/**+ * Whether the element hides what is behind it from binding. Images count as+ * opaque, and frames once they support a background.+ */+const isOpaqueForBinding = (element: ExcalidrawElement) =>+ isImageElement(element) ||+ (hasBackground(element.type) && !isTransparent(element.backgroundColor));+/*** Bindable elements within binding distance of the point, front to back.* Stops at the first opaque element containing the point, since it hides- * everything behind it.+ * everything behind it. Locked elements can't be bound to, but still hide+ * what is behind them.*/const getBindingCandidates = (point: Readonly<GlobalPoint>,@@ -352,6 +361,9 @@ const getBindingCandidates = (): BindingCandidate[] => {const maxDistance = maxBindingDistance_simple(zoom);const candidates: BindingCandidate[] = [];+ // A frame's children sit just below it in z-order, so a frame's background+ // can't end the search: it only hides the non-children behind it+ let occludingFrameId: ExcalidrawElement["id"] | null = null;// We need to do hit testing from front (end of the array) to back (beginning of the array)// because array is ordered from lower z-index to highest and we want element z-index// with higher z-index@@ -363,10 +375,23 @@ const getBindingCandidates = ("Elements passed to binding hit tests should not contain deleted elements",);- if (!isBindableElement(element, false)) {+ if (occludingFrameId && element.frameId !== occludingFrameId) {continue;}+ if (!isBindableElement(element)) {+ continue;+ }++ if (isFrameLikeElement(element)) {+ if (+ isOpaqueForBinding(element) &&+ isPointInElement(point, element, elementsMap)+ ) {+ occludingFrameId = element.id;+ }+ }+const distance = bindableElementBorderDistanceIfClose(element,point,@@ -375,13 +400,11 @@ const getBindingCandidates = ();if (distance > -maxDistance) {- candidates.push({ element, distance });+ if (!element.locked) {+ candidates.push({ element, distance });+ }- if (- hasBackground(element.type) &&- !isTransparent(element.backgroundColor) &&- distance >= 0- ) {+ if (distance >= 0 && isOpaqueForBinding(element)) {break;}}diff --git a/packages/element/src/elbowArrow.ts b/packages/element/src/elbowArrow.tsindex 18eb986848..239d8ffdea 100644--- a/packages/element/src/elbowArrow.ts+++ b/packages/element/src/elbowArrow.ts@@ -21,6 +21,7 @@ import {getSizeFromPoints,isDevEnv,arrayToMap,+ DEFAULT_ZOOM,} from "@excalidraw/common";import type { AppState } from "@excalidraw/excalidraw/types";@@ -1218,7 +1219,7 @@ const getElbowArrowData = (// NOTE: updates coming through `mutateElement` don't carry the zoom, so// those fall back to the zoom=1 binding distance- const zoom = options?.zoom ?? ({ value: 1 } as AppState["zoom"]);+ const zoom = options?.zoom ?? DEFAULT_ZOOM;let hoveredStartElement = null;let hoveredEndElement = null;diff --git a/packages/element/src/renderElement.ts b/packages/element/src/renderElement.tsindex 2edc0989b6..0aa74b0b06 100644--- a/packages/element/src/renderElement.ts+++ b/packages/element/src/renderElement.ts@@ -29,6 +29,7 @@ import {STICKY_NOTE_EDGE_SHADOW_WIDTH,STICKY_NOTE_FOOTER,STICKY_NOTE_SHADOW_OPACITY,+ DEFAULT_ZOOM,} from "@excalidraw/common";import type {@@ -36,7 +37,6 @@ import type {StaticCanvasAppState,Zoom,InteractiveCanvasAppState,- NormalizedZoomValue,ElementRenderOverrides,} from "@excalidraw/excalidraw/types";@@ -690,11 +690,7 @@ const generateElementWithCanvas = (renderConfig: StaticCanvasRenderConfig,appState: StaticCanvasAppState | InteractiveCanvasAppState,) => {- const zoom: Zoom = renderConfig- ? appState.zoom- : {- value: 1 as NormalizedZoomValue,- };+ const zoom: Zoom = renderConfig ? appState.zoom : DEFAULT_ZOOM;const prevElementWithCanvas = elementWithCanvasCache.get(element);const shouldRegenerateBecauseZoom =prevElementWithCanvas &&diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.tsindex fe3130e200..2e5f401963 100644--- a/packages/element/src/transform.ts+++ b/packages/element/src/transform.ts@@ -17,6 +17,7 @@ import {getLineHeight,DEFAULT_STICKY_NOTE_SIZE,isTransparent,+ DEFAULT_ZOOM,} from "@excalidraw/common";import type { MarkOptional } from "@excalidraw/common/utility-types";@@ -786,7 +787,7 @@ export const convertToExcalidrawElements = (originalEnd,elementStore,scene,- { value: 1 } as Zoom,+ DEFAULT_ZOOM,);container = linearElement;elementStore.add(linearElement);@@ -812,7 +813,7 @@ export const convertToExcalidrawElements = (end,elementStore,scene,- { value: 1 } as Zoom,+ DEFAULT_ZOOM,);elementStore.add(linearElement);diff --git a/packages/element/tests/binding.test.tsx b/packages/element/tests/binding.test.tsxindex e7de9e7c42..4d2bd617af 100644--- a/packages/element/tests/binding.test.tsx+++ b/packages/element/tests/binding.test.tsx@@ -1,4 +1,4 @@-import { KEYS, ROUNDNESS, arrayToMap } from "@excalidraw/common";+import { KEYS, ROUNDNESS, arrayToMap, DEFAULT_ZOOM } from "@excalidraw/common";import { pointFrom } from "@excalidraw/math";@@ -18,8 +18,6 @@ import { defaultLang, setLanguage } from "@excalidraw/excalidraw/i18n";import type { Radians } from "@excalidraw/math";-import type { Zoom } from "@excalidraw/excalidraw/types";-import {bindBindingElement,getBindingGap,@@ -1085,9 +1083,7 @@ describe("binding to a point-like (sub-pixel) element", () => {}) as NonDeleted<ExcalidrawArrowElement>;API.setElements([rect, arrow]);- bindBindingElement(arrow, rect, "orbit", "end", h.scene, {- value: 1,- } as Zoom);+ bindBindingElement(arrow, rect, "orbit", "end", h.scene, DEFAULT_ZOOM);const endBinding = arrow.endBinding as FixedPointBinding;expect(endBinding.elementId).toBe(rect.id);diff --git a/packages/element/tests/collision.test.tsx b/packages/element/tests/collision.test.tsxindex a58b90e006..744fd11ab9 100644--- a/packages/element/tests/collision.test.tsx+++ b/packages/element/tests/collision.test.tsx@@ -723,6 +723,56 @@ describe("binding hit tests", () => {expect(transparent.all).toEqual(["cover", "hidden"]);});+ it("an image, and a locked opaque element, hide what's behind them", () => {+ const hidden = API.createElement({+ id: "hidden",+ type: "rectangle",+ x: 30,+ y: 30,+ width: 40,+ height: 40,+ index: "a0" as SceneElement["index"],+ }) as SceneElement;+ const point = pointFrom<GlobalPoint>(50, 50);++ const image = API.createElement({+ id: "image",+ type: "image",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ index: "a1" as SceneElement["index"],+ }) as SceneElement;+ expect(hitTest([hidden, image], point)).toEqual({+ hovered: "image",+ all: ["image"],+ });++ const locked = (backgroundColor: string) =>+ API.createElement({+ id: "locked",+ type: "rectangle",+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ backgroundColor,+ locked: true,+ index: "a1" as SceneElement["index"],+ }) as SceneElement;+ // can't bind to the locked element, nor through it+ expect(hitTest([hidden, locked("#ffc9c9")], point)).toEqual({+ hovered: undefined,+ all: [],+ });+ // a transparent locked element hides nothing+ expect(hitTest([hidden, locked("transparent")], point)).toEqual({+ hovered: "hidden",+ all: ["hidden"],+ });+ });+describe("overlapping elements", () => {const rect = (id: string, x: number, y: number, w: number, h: number) =>API.createElement({diff --git a/packages/element/tests/elbowArrow.test.tsx b/packages/element/tests/elbowArrow.test.tsxindex 444386ad1c..ec0603dea3 100644--- a/packages/element/tests/elbowArrow.test.tsx+++ b/packages/element/tests/elbowArrow.test.tsx@@ -1,4 +1,4 @@-import { ARROW_TYPE } from "@excalidraw/common";+import { ARROW_TYPE, DEFAULT_ZOOM } from "@excalidraw/common";import { pointFrom } from "@excalidraw/math";import { Excalidraw } from "@excalidraw/excalidraw";import { actionSelectAll } from "@excalidraw/excalidraw/actions";@@ -16,7 +16,6 @@ import "@excalidraw/utils/test-utils";import { bindBindingElement } from "@excalidraw/element";import type { LocalPoint } from "@excalidraw/math";-import type { Zoom } from "@excalidraw/excalidraw/types";import { Scene } from "../src/Scene";@@ -189,12 +188,22 @@ describe("elbow arrow routing", () => {}) as NonDeleted<ExcalidrawElbowArrowElement>;API.setElements([rectangle1, rectangle2, arrow]);- bindBindingElement(arrow, rectangle1, "orbit", "start", h.scene, {- value: 1,- } as Zoom);- bindBindingElement(arrow, rectangle2, "orbit", "end", h.scene, {- value: 1,- } as Zoom);+ bindBindingElement(+ arrow,+ rectangle1,+ "orbit",+ "start",+ h.scene,+ DEFAULT_ZOOM,+ );+ bindBindingElement(+ arrow,+ rectangle2,+ "orbit",+ "end",+ h.scene,+ DEFAULT_ZOOM,+ );expect(arrow.startBinding).not.toBe(null);expect(arrow.endBinding).not.toBe(null);diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.tsindex cc52b29f8e..821ba20f52 100644--- a/packages/excalidraw/data/restore.ts+++ b/packages/excalidraw/data/restore.ts@@ -31,6 +31,7 @@ import {STROKE_WIDTH_KEYS,type StrokeWidthKey,isTransparent,+ DEFAULT_ZOOM,} from "@excalidraw/common";import {calculateFixedPointForNonElbowArrowBinding,@@ -112,12 +113,7 @@ import {getNormalizedZoom,} from "../scene";-import type {- AppState,- BinaryFiles,- LibraryItem,- NormalizedZoomValue,-} from "../types";+import type { AppState, BinaryFiles, LibraryItem } from "../types";import type { ImportedDataState, LegacyAppState } from "./types";type RestoredAppState = Omit<@@ -402,7 +398,7 @@ const repairBinding = <T extends ExcalidrawArrowElement>(boundElement,startOrEnd,elementsMap,- { value: 1 as NormalizedZoomValue },+ DEFAULT_ZOOM,) || p;const { fixedPoint } = calculateFixedPointForNonElbowArrowBinding(safeElement as NonDeleted<ExcalidrawArrowElement>,diff --git a/packages/excalidraw/renderer/interactiveScene.ts b/packages/excalidraw/renderer/interactiveScene.tsindex 5a4b479c2b..f9d088db67 100644--- a/packages/excalidraw/renderer/interactiveScene.ts+++ b/packages/excalidraw/renderer/interactiveScene.ts@@ -1,5 +1,6 @@import {clamp,+ pointDistance,pointFrom,pointsEqual,type GlobalPoint,@@ -31,6 +32,7 @@ import {getTransformHandles,getTransformHandlesFromCoords,hasBoundingBox,+ hitElementItself,isArrowElement,isBindableElement,isElbowArrow,@@ -40,6 +42,7 @@ import {isLineElement,isTextElement,LinearElementEditor,+ maxBindingDistance_simple,getActiveTextElement,getElementsInGroup,getSelectedGroupIds,@@ -479,33 +482,77 @@ const renderBindingHighlightForBindableElement_simple = ((isFrameLikeElement(suggestedBinding.element) ||isBindableElement(suggestedBinding.element))) {- context.save();+ const linearElement = appState.selectedLinearElement;+ const arrow =+ linearElement?.elementId &&+ LinearElementEditor.getElement(linearElement.elementId, elementsMap);+ const isElbow =+ (arrow && isElbowArrow(arrow)) ||+ (appState.activeTool.type === "arrow" &&+ appState.currentItemArrowType === "elbow");+ const cursorIsInsideBindable =+ pointerCoords &&+ hitElementItself({+ point: pointerCoords,+ element: suggestedBinding.element,+ elementsMap,+ threshold: 0,+ overrideShouldTestInside: true,+ });- const midpointRadius = 4 / appState.zoom.value;+ // Simple arrows only snap to midpoints from outside the element+ if (!cursorIsInsideBindable || isElbow) {+ context.save();++ const midpointRadius = 4 / appState.zoom.value;+ const highlightedMidpoint = suggestedBinding.midPoint;+ const midpoints = getAllMidpoints(suggestedBinding.element, elementsMap);++ // Elbow arrows show all midpoints, simple arrows only the one closest to+ // the pointer, once the pointer gets near it+ let shownMidpoints = midpoints;+ if (!isElbow) {+ const threshold =+ maxBindingDistance_simple(appState.zoom) ++ suggestedBinding.element.strokeWidth / 2;+ const closest =+ pointerCoords &&+ midpoints.reduce((a, b) =>+ pointDistance(a, pointerCoords) <= pointDistance(b, pointerCoords)+ ? a+ : b,+ );+ shownMidpoints =+ closest && pointDistance(closest, pointerCoords) <= threshold * 2+ ? [closest]+ : [];+ }- // Render base midpoints- const midpoints = getAllMidpoints(suggestedBinding.element, elementsMap);- for (const midpoint of midpoints) {context.fillStyle = BINDING_MIDPOINT_COLOR[appState.theme];- context.beginPath();- context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);- context.fill();- }+ for (const midpoint of shownMidpoints) {+ if (highlightedMidpoint && pointsEqual(midpoint, highlightedMidpoint)) {+ continue;+ }+ context.beginPath();+ context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);+ context.fill();+ }- // Render the highlighted midpoint if any- const midpoint = appState.suggestedBinding?.midPoint;- if (midpoint) {- context.fillStyle =- appState.theme === THEME.DARK- ? `rgba(3, 93, 161, 1)`- : `rgba(106, 189, 252, 1)`;+ if (highlightedMidpoint) {+ context.fillStyle = `rgba(${BINDING_HIGHLIGHT_RGB[appState.theme]}, 1)`;+ context.beginPath();+ context.arc(+ highlightedMidpoint[0],+ highlightedMidpoint[1],+ midpointRadius,+ 0,+ 2 * Math.PI,+ );+ context.fill();+ }- context.beginPath();- context.arc(midpoint[0], midpoint[1], midpointRadius, 0, 2 * Math.PI);- context.fill();+ context.restore();}-- context.restore();}};diff --git a/packages/excalidraw/tests/move.test.tsx b/packages/excalidraw/tests/move.test.tsxindex 0dd0b1bdc3..0178c70a9f 100644--- a/packages/excalidraw/tests/move.test.tsx+++ b/packages/excalidraw/tests/move.test.tsx@@ -1,6 +1,6 @@import React from "react";import { vi } from "vitest";-import { KEYS, reseed } from "@excalidraw/common";+import { KEYS, reseed, DEFAULT_ZOOM } from "@excalidraw/common";import { bindBindingElement } from "@excalidraw/element";import "@excalidraw/utils/test-utils";@@ -17,8 +17,6 @@ import * as StaticScene from "../renderer/staticScene";import { UI, Pointer, Keyboard } from "./helpers/ui";import { render, fireEvent, act, unmountComponent } from "./test-utils";-import type { Zoom } from "../types";-unmountComponent();const renderInteractiveScene = vi.spyOn(@@ -91,7 +89,7 @@ describe("move element", () => {"orbit","start",h.app.scene,- { value: 1 } as Zoom,+ DEFAULT_ZOOM,);bindBindingElement(arrow.get() as NonDeleted<ExcalidrawArrowElement>,@@ -99,7 +97,7 @@ describe("move element", () => {"orbit","end",h.app.scene,- { value: 1 } as Zoom,+ DEFAULT_ZOOM,);});