Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): allow for dragging bound text along an arrow's path (#10947)

Christopher Tangonan214cd6e6e8ac
diff --git a/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap b/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap
index afef25eeff..ad93aeadfb 100644
--- a/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap
+++ b/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap
@@ -259,6 +259,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -305,6 +306,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -412,6 +414,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a3",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -519,6 +522,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"id": Any<String>,
"index": "a1",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -700,6 +704,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a1",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -746,6 +751,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a2",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -792,6 +798,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a3",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1245,6 +1252,7 @@ exports[`Test Transform > should transform text element 1`] = `
"id": Any<String>,
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1286,6 +1294,7 @@ exports[`Test Transform > should transform text element 2`] = `
"id": Any<String>,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1633,6 +1642,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a6",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1676,6 +1686,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a7",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1719,6 +1730,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a8",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1762,6 +1774,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a9",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1803,6 +1816,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "aA",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1844,6 +1858,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "aB",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1859,12 +1874,12 @@ exports[`Test Transform > should transform the elements correctly when linear el
"textAlign": "center",
"type": "text",
"updated": 1,
- "version": 3,
+ "version": 2,
"versionNonce": Any<Number>,
"verticalAlign": "middle",
"width": 100,
- "x": 27.016999999999996,
- "y": 66.5,
+ "x": -50,
+ "y": -12.5,
}
`;
@@ -2093,6 +2108,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a4",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2134,6 +2150,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a5",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2175,6 +2192,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a6",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2217,6 +2235,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a7",
"isDeleted": false,
+ "labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2481,6 +2500,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a6",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2522,6 +2542,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a7",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2564,6 +2585,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a8",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2608,6 +2630,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a9",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2650,6 +2673,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "aA",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2693,6 +2717,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "aB",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
diff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.ts
index a090305490..cfc4a06ff7 100644
--- a/packages/element/src/linearElementEditor.ts
+++ b/packages/element/src/linearElementEditor.ts
@@ -8,7 +8,14 @@ import {
pointDistance,
vectorFromPoint,
curveLength,
+ curveLengthAtParameter,
curvePointAtLength,
+ lineSegmentClosestParameter,
+ lineSegmentPointAt,
+ curveClosestParameter,
+ clamp,
+ bezierEquation,
+ isCurve,
} from "@excalidraw/math";
import { getCurvePathOps } from "@excalidraw/utils/shape";
@@ -30,8 +37,11 @@ import {
moveArrowAboveBindable,
projectFixedPointOntoDiagonal,
type Store,
+ getLinearElementPathSegments,
} from "@excalidraw/element";
+import type { LinearPathSegment } from "@excalidraw/element";
+
import type { Radians } from "@excalidraw/math";
import type {
@@ -122,6 +132,15 @@ type PointMoveOtherUpdates = {
suggestedBinding?: AppState["suggestedBinding"] | null;
};
+const BoundTextPositionCache = new WeakMap<
+ ExcalidrawTextElementWithContainer,
+ {
+ containerVersion: ExcalidrawElement["version"];
+ textVersion: ExcalidrawElement["version"];
+ position: { x: number; y: number };
+ }
+>();
+
export class LinearElementEditor {
public readonly elementId: ExcalidrawElement["id"] & {
_brand: "excalidrawLinearElementId";
@@ -1031,6 +1050,8 @@ export class LinearElementEditor {
): {
didAddPoint: boolean;
hitElement: NonDeleted<ExcalidrawElement> | null;
+ /** the pointer went down on the arrow's label, grabbing it for a drag */
+ hitBoundText: boolean;
linearElementEditor: LinearElementEditor | null;
} {
const appState = app.state;
@@ -1039,6 +1060,7 @@ export class LinearElementEditor {
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
+ hitBoundText: false,
linearElementEditor: null,
};
@@ -1112,16 +1134,51 @@ export class LinearElementEditor {
return ret;
}
- const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
+ const pointIndexUnderCursor = LinearElementEditor.getPointIndexUnderCursor(
element,
elementsMap,
appState.zoom,
scenePointer.x,
scenePointer.y,
);
- // if we clicked on a point, set the element as hitElement otherwise
- // it would get deselected if the point is outside the hitbox area
- if (clickedPointIndex >= 0 || segmentMidpoint) {
+ const clickedPointIsHandle = LinearElementEditor.isPointHandle(
+ element,
+ pointIndexUnderCursor,
+ );
+
+ const boundTextElement = getBoundTextElement(element, elementsMap);
+ let boundTextGrabOffset: { x: number; y: number } | null = null;
+ if (
+ !clickedPointIsHandle &&
+ // the segment midpoint knob keeps precedence over the label sitting
+ // on top of it, so a labeled arrow can still be bent at its middle
+ !segmentMidpoint &&
+ boundTextElement &&
+ isArrowElement(element) &&
+ app.arrowText.isBoundTextGrabbable(
+ element,
+ scenePointer.x,
+ scenePointer.y,
+ )
+ ) {
+ const { x: textX, y: textY } =
+ LinearElementEditor.getBoundTextElementPosition(
+ element,
+ boundTextElement,
+ elementsMap,
+ );
+ boundTextGrabOffset = {
+ x: scenePointer.x - (textX + boundTextElement.width / 2),
+ y: scenePointer.y - (textY + boundTextElement.height / 2),
+ };
+ }
+
+ // when the label grab wins (possible over a non-interactive elbow route
+ // point), the click must not double as a point click
+ const clickedPointIndex = boundTextGrabOffset ? -1 : pointIndexUnderCursor;
+ ret.hitBoundText = !!boundTextGrabOffset;
+
+ if (clickedPointIndex >= 0 || segmentMidpoint || boundTextGrabOffset) {
ret.hitElement = element;
}
@@ -1174,7 +1231,7 @@ export class LinearElementEditor {
x: scenePointer.x - targetPoint[0],
y: scenePointer.y - targetPoint[1],
}
- : { x: 0, y: 0 },
+ : boundTextGrabOffset ?? { x: 0, y: 0 },
};
return ret;
@@ -1355,6 +1412,19 @@ export class LinearElementEditor {
return pointFrom(x - element.x, y - element.y);
}
+ /**
+ * Whether the point at `index` is an interactive handle. Elbow arrows only
+ * expose their endpoints; their intermediate route points are not draggable.
+ */
+ static isPointHandle(element: ExcalidrawLinearElement, index: number) {
+ return (
+ index >= 0 &&
+ (!isElbowArrow(element) ||
+ index === 0 ||
+ index === element.points.length - 1)
+ );
+ }
+
static getPointIndexUnderCursor(
element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
@@ -1885,17 +1955,163 @@ export class LinearElementEditor {
);
};
+ static handleBoundTextDragging(
+ linearElementEditor: LinearElementEditor,
+ scene: Scene,
+ pointerX: number,
+ pointerY: number,
+ ): LinearElementEditor | null {
+ const elementsMap = scene.getNonDeletedElementsMap();
+ const element = LinearElementEditor.getElement(
+ linearElementEditor.elementId,
+ elementsMap,
+ );
+ const boundTextElement = getBoundTextElement(element, elementsMap);
+ if (!element || !isArrowElement(element) || !boundTextElement) {
+ return null;
+ }
+ const pointerGlobalPoint = pointFrom<GlobalPoint>(
+ pointerX - linearElementEditor.pointerOffset.x,
+ pointerY - linearElementEditor.pointerOffset.y,
+ );
+ const { segments, lengths, prefixSums, totalLength } =
+ getLinearElementPathMetrics(element, elementsMap);
+ if (segments.length === 0 || totalLength === 0) {
+ return null;
+ }
+
+ let bestDistance = Infinity;
+ let bestSegmentIndex = 0;
+ let bestParameter = 0;
+
+ for (let i = 0; i < segments.length; i++) {
+ const { t, distance } = pathSegmentClosestParameter(
+ segments[i],
+ pointerGlobalPoint,
+ );
+
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ bestSegmentIndex = i;
+ bestParameter = t;
+ }
+ }
+
+ const lengthWithinSegment = pathSegmentLengthAtParameter(
+ segments[bestSegmentIndex],
+ bestParameter,
+ lengths[bestSegmentIndex],
+ );
+
+ const labelPosition = clamp(
+ (prefixSums[bestSegmentIndex] + lengthWithinSegment) / totalLength,
+ 0,
+ 1,
+ );
+ const pathPoint = LinearElementEditor.getPointAtPathParameter(
+ element,
+ labelPosition,
+ elementsMap,
+ );
+ if (!pathPoint) {
+ return null;
+ }
+
+ scene.mutateElement(boundTextElement, {
+ labelPosition,
+ x: pathPoint[0] - boundTextElement.width / 2,
+ y: pathPoint[1] - boundTextElement.height / 2,
+ });
+
+ return {
+ ...linearElementEditor,
+ isDragging: true,
+ };
+ }
+
+ static getPointAtPathParameter(
+ container: ExcalidrawLinearElement,
+ pathParameter: number,
+ elementsMap: ElementsMap,
+ ): GlobalPoint | null {
+ if (!Number.isFinite(pathParameter)) {
+ return null;
+ }
+
+ const { segments, lengths, prefixSums, totalLength } =
+ getLinearElementPathMetrics(container, elementsMap);
+ if (segments.length === 0) {
+ return null;
+ }
+
+ const targetLength = clamp(pathParameter, 0, 1) * totalLength;
+
+ // the first segment whose end lies at or beyond the target; the last one
+ // catches a target that floating point pushed past the total length
+ const found = segments.findIndex(
+ (_, i) => targetLength <= prefixSums[i + 1],
+ );
+ const i = found === -1 ? segments.length - 1 : found;
+ const lengthFraction =
+ lengths[i] === 0
+ ? 0
+ : clamp((targetLength - prefixSums[i]) / lengths[i], 0, 1);
+
+ return pathSegmentPointAtLength(segments[i], lengthFraction, lengths[i]);
+ }
+
static getBoundTextElementPosition = (
element: ExcalidrawLinearElement,
boundTextElement: ExcalidrawTextElementWithContainer,
elementsMap: ElementsMap,
): { x: number; y: number } => {
- const points = LinearElementEditor.getPointsGlobalCoordinates(
+ // derived on every hit test, bounds query and render of the label, so
+ // memoize on the pair of versions the result depends on
+ const cached = BoundTextPositionCache.get(boundTextElement);
+ if (
+ cached &&
+ cached.containerVersion === element.version &&
+ cached.textVersion === boundTextElement.version
+ ) {
+ return cached.position;
+ }
+
+ const position = LinearElementEditor.computeBoundTextElementPosition(
element,
+ boundTextElement,
elementsMap,
);
- if (points.length < 2) {
- mutateElement(boundTextElement, elementsMap, { isDeleted: true });
+
+ BoundTextPositionCache.set(boundTextElement, {
+ containerVersion: element.version,
+ textVersion: boundTextElement.version,
+ position,
+ });
+
+ return position;
+ };
+
+ private static computeBoundTextElementPosition = (
+ element: ExcalidrawLinearElement,
+ boundTextElement: ExcalidrawTextElementWithContainer,
+ elementsMap: ElementsMap,
+ ): { x: number; y: number } => {
+ if (element.points.length < 2) {
+ return { x: boundTextElement.x, y: boundTextElement.y };
+ }
+ if (isArrowElement(element) && boundTextElement.labelPosition != null) {
+ const pathPoint = LinearElementEditor.getPointAtPathParameter(
+ element,
+ boundTextElement.labelPosition,
+ elementsMap,
+ );
+
+ if (pathPoint) {
+ return {
+ x: pathPoint[0] - boundTextElement.width / 2,
+ y: pathPoint[1] - boundTextElement.height / 2,
+ };
+ }
}
const center = LinearElementEditor.getBoundTextElementCenter(
@@ -2536,3 +2752,93 @@ const determineCustomLinearAngle = (
draggedPoint: LocalPoint,
) =>
Math.atan2(draggedPoint[1] - pivotPoint[1], draggedPoint[0] - pivotPoint[0]);
+
+type LinearElementPathMetrics = {
+ segments: LinearPathSegment[];
+ lengths: number[];
+ prefixSums: number[];
+ totalLength: number;
+};
+
+const LinearElementPathMetricsCache = new WeakMap<
+ ExcalidrawElement,
+ { version: ExcalidrawElement["version"]; metrics: LinearElementPathMetrics }
+>();
+
+function getLinearElementPathMetrics(
+ element: ExcalidrawLinearElement,
+ elementsMap: ElementsMap,
+): LinearElementPathMetrics {
+ const cached = LinearElementPathMetricsCache.get(element);
+
+ if (cached) {
+ if (cached.version === element.version) {
+ return cached.metrics;
+ }
+
+ LinearElementPathMetricsCache.delete(element);
+ }
+
+ const segments = getLinearElementPathSegments(element, elementsMap);
+ const lengths = segments.map(pathSegmentLength);
+ const prefixSums = new Array<number>(lengths.length + 1);
+
+ prefixSums[0] = 0;
+ for (let i = 0; i < lengths.length; i++) {
+ prefixSums[i + 1] = prefixSums[i] + lengths[i];
+ }
+
+ const metrics: LinearElementPathMetrics = {
+ segments,
+ lengths,
+ prefixSums,
+ totalLength: prefixSums[lengths.length],
+ };
+
+ LinearElementPathMetricsCache.set(element, {
+ version: element.version,
+ metrics,
+ });
+
+ return metrics;
+}
+
+const pathSegmentLength = (segment: LinearPathSegment): number =>
+ isCurve(segment)
+ ? curveLength(segment)
+ : pointDistance(segment[0], segment[1]);
+
+/**
+ * The segment's parameter `t` (`0..1`) at the point closest to `point`, and
+ * how far that point is from `point`.
+ */
+const pathSegmentClosestParameter = (
+ segment: LinearPathSegment,
+ point: GlobalPoint,
+): { t: number; distance: number } => {
+ if (isCurve(segment)) {
+ const t = curveClosestParameter(segment, point);
+ return { t, distance: pointDistance(point, bezierEquation(segment, t)) };
+ }
+
+ const t = lineSegmentClosestParameter(point, segment);
+ return { t, distance: pointDistance(point, lineSegmentPointAt(segment, t)) };
+};
+
+/** arc length from the segment's start to its parameter `t` */
+const pathSegmentLengthAtParameter = (
+ segment: LinearPathSegment,
+ t: number,
+ segmentLength: number,
+): number =>
+ isCurve(segment) ? curveLengthAtParameter(segment, t) : t * segmentLength;
+
+/** point at `fraction` (`0..1`) of the segment's arc length */
+const pathSegmentPointAtLength = (
+ segment: LinearPathSegment,
+ fraction: number,
+ segmentLength: number,
+): GlobalPoint =>
+ isCurve(segment)
+ ? curvePointAtLength(segment, fraction, segmentLength)
+ : lineSegmentPointAt(segment, fraction);
diff --git a/packages/element/src/newElement.ts b/packages/element/src/newElement.ts
index 4400313c73..76c1b8b323 100644
--- a/packages/element/src/newElement.ts
+++ b/packages/element/src/newElement.ts
@@ -267,6 +267,7 @@ export const newTextElement = (
containerId?: ExcalidrawTextContainer["id"] | null;
lineHeight?: ExcalidrawTextElement["lineHeight"];
autoResize?: ExcalidrawTextElement["autoResize"];
+ labelPosition?: ExcalidrawTextElement["labelPosition"];
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawTextElement> => {
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
@@ -300,6 +301,7 @@ export const newTextElement = (
originalText: opts.originalText ?? text,
autoResize: opts.autoResize ?? true,
lineHeight,
+ labelPosition: opts.labelPosition ?? null,
};
const textElement: NonDeleted<ExcalidrawTextElement> = newElementWith(
diff --git a/packages/element/src/textElement.ts b/packages/element/src/textElement.ts
index cd529e84bb..f91d6a6396 100644
--- a/packages/element/src/textElement.ts
+++ b/packages/element/src/textElement.ts
@@ -531,3 +531,5 @@ export const getTextFromElements = (
.join(separator);
return text;
};
+
+export const DEFAULT_BOUND_TEXT_LABEL_POSITION = 0.5;
diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.ts
index dd71cb30ec..21287abaa9 100644
--- a/packages/element/src/transform.ts
+++ b/packages/element/src/transform.ts
@@ -34,7 +34,10 @@ import { isArrowElement } from "./typeChecks";
import { syncInvalidIndices } from "./fractionalIndex";
-import { redrawTextBoundingBox } from "./textElement";
+import {
+ DEFAULT_BOUND_TEXT_LABEL_POSITION,
+ redrawTextBoundingBox,
+} from "./textElement";
import { LinearElementEditor } from "./linearElementEditor";
@@ -231,6 +234,9 @@ const bindTextToContainer = (
...textProps,
containerId: container.id,
strokeColor: textProps.strokeColor || container.strokeColor,
+ labelPosition: isArrowElement(container)
+ ? DEFAULT_BOUND_TEXT_LABEL_POSITION
+ : null,
});
Object.assign(container, {
diff --git a/packages/element/src/types.ts b/packages/element/src/types.ts
index 100b13db5b..f91b2c6ea1 100644
--- a/packages/element/src/types.ts
+++ b/packages/element/src/types.ts
@@ -254,6 +254,13 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
* with font size (using `getLineHeightInPx` helper).
*/
lineHeight: number & { _brand: "unitlessLineHeight" };
+ /**
+ * Position of text bound to a linear element (such as an arrow),
+ * expressed as a normalized arc-length parameter (0–1) along the
+ * container's whole path. Independent of how the path is segmented,
+ * so it survives midpoint insertion and other geometry changes.
+ * */
+ labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement =
diff --git a/packages/element/src/utils.ts b/packages/element/src/utils.ts
index d3a3831700..3421b8b20d 100644
--- a/packages/element/src/utils.ts
+++ b/packages/element/src/utils.ts
@@ -40,7 +40,7 @@ import { generateLinearCollisionShape } from "./shape";
import { hitElementItself, isPointInElement } from "./collision";
import { LinearElementEditor } from "./linearElementEditor";
-import { isRectangularElement } from "./typeChecks";
+import { isElbowArrow, isRectangularElement } from "./typeChecks";
import { maxBindingDistance_simple } from "./binding";
import {
@@ -59,6 +59,8 @@ import type {
ExcalidrawRectanguloidElement,
} from "./types";
+export type LinearPathSegment = LineSegment<GlobalPoint> | Curve<GlobalPoint>;
+
type ElementShape = [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]];
const ElementShapesCache = new WeakMap<
@@ -125,7 +127,7 @@ const setElementShapesCacheEntry = <T extends ExcalidrawElement>(
export function deconstructLinearOrFreeDrawElement(
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
-): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
+): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, 0);
if (cachedShape) {
@@ -133,8 +135,8 @@ export function deconstructLinearOrFreeDrawElement(
}
const ops = generateLinearCollisionShape(element, elementsMap);
- const lines = [];
- const curves = [];
+ const lines: LineSegment<GlobalPoint>[] = [];
+ const curves: Curve<GlobalPoint>[] = [];
for (let idx = 0; idx < ops.length; idx += 1) {
const op = ops[idx];
@@ -193,12 +195,43 @@ export function deconstructLinearOrFreeDrawElement(
}
}
- const shape = [lines, curves] as ElementShape;
+ const shape: ElementShape = [lines, curves];
setElementShapesCacheEntry(element, shape, 0);
return shape;
}
+export function getLinearElementPathSegments(
+ element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
+ elementsMap: ElementsMap,
+): LinearPathSegment[] {
+ // For now, model elbow arrows as their unrounded logical path. Rounded
+ // joints can be incorporated once the path model supports mixed straight
+ // and curved segments.
+ if (isElbowArrow(element)) {
+ return element.points
+ .slice(1)
+ .map((point, index) =>
+ lineSegment<GlobalPoint>(
+ pointFrom<GlobalPoint>(
+ element.x + element.points[index][0],
+ element.y + element.points[index][1],
+ ),
+ pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
+ ),
+ );
+ }
+
+ const [lines, curves] = deconstructLinearOrFreeDrawElement(
+ element,
+ elementsMap,
+ );
+
+ // Non-elbow paths currently contain only one segment type. Mixed paths
+ // should consume an ordered operation stream instead of these type buckets.
+ return curves.length > 0 ? curves : lines;
+}
+
/**
* Get the building components of a rectanguloid element in the form of
* line segments and curves **unrotated**.
@@ -210,7 +243,7 @@ export function deconstructLinearOrFreeDrawElement(
export function deconstructRectanguloidElement(
element: ExcalidrawRectanguloidElement,
offset: number = 0,
-): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
+): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, offset);
if (cachedShape) {
@@ -422,7 +455,7 @@ export function getDiamondBaseCorners(
export function deconstructDiamondElement(
element: ExcalidrawDiamondElement,
offset: number = 0,
-): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
+): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, offset);
if (cachedShape) {
diff --git a/packages/element/tests/binding.test.tsx b/packages/element/tests/binding.test.tsx
index ccff660407..7f03e8fe1f 100644
--- a/packages/element/tests/binding.test.tsx
+++ b/packages/element/tests/binding.test.tsx
@@ -480,6 +480,9 @@ describe("binding for simple arrows", () => {
const elX = handles[0] + handles[2] / 2;
const elY = handles[1] + handles[3] / 2;
+ // move first, as a real pointer would — the hover state from the spot
+ // where arrow creation finished must clear before the pointerdown
+ mouse.moveTo(elX, elY);
mouse.downAt(elX, elY);
mouse.moveTo(300, 400);
mouse.up();
diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsx
index 7c79d7fab9..468f6f8a5f 100644
--- a/packages/element/tests/linearElementEditor.test.tsx
+++ b/packages/element/tests/linearElementEditor.test.tsx
@@ -3,6 +3,7 @@ import { act, queryByTestId, queryByText } from "@testing-library/react";
import { vi } from "vitest";
import {
+ CURSOR_TYPE,
ROUNDNESS,
VERTICAL_ALIGN,
KEYS,
@@ -31,6 +32,7 @@ import * as textElementUtils from "../src/textElement";
import { getBoundTextElementPosition, getBoundTextMaxWidth } from "../src";
import { LinearElementEditor } from "../src";
import { newArrowElement } from "../src";
+import { getLinearElementPathSegments } from "../src/utils";
import {
getTextEditor,
@@ -213,13 +215,15 @@ describe("Test Linear Elements", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
- expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`5`);
+ expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`6`);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`5`);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toEqual(2);
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
- expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`8`);
+ expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
+ `10`,
+ );
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
expect(line.points.length).toEqual(3);
expect(line.points).toMatchInlineSnapshot(`
@@ -502,7 +506,7 @@ describe("Test Linear Elements", () => {
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `12`,
+ `14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -543,7 +547,7 @@ describe("Test Linear Elements", () => {
fireEvent.click(screen.getByTitle("Round"));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `10`,
+ `11`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`6`);
@@ -604,7 +608,7 @@ describe("Test Linear Elements", () => {
drag(startPoint, endPoint);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `12`,
+ `13`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -672,7 +676,7 @@ describe("Test Linear Elements", () => {
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `15`,
+ `18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
@@ -723,7 +727,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] - delta, hitCoords[1] - delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `12`,
+ `14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -764,7 +768,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `12`,
+ `14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -812,7 +816,7 @@ describe("Test Linear Elements", () => {
deletePoint(points[2]);
expect(line.points.length).toEqual(3);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `18`,
+ `22`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`10`);
@@ -870,7 +874,7 @@ describe("Test Linear Elements", () => {
),
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `15`,
+ `18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(line.points.length).toEqual(5);
@@ -968,7 +972,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
- `12`,
+ `14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -1202,6 +1206,93 @@ describe("Test Linear Elements", () => {
});
});
+ describe("Test getPointAtPathParameter", () => {
+ it("should survive midpoint insertion", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
+ roundness: null,
+ });
+ API.setElements([arrow]);
+
+ const before = LinearElementEditor.getPointAtPathParameter(
+ arrow,
+ 0.25,
+ arrayToMap(h.elements),
+ )!;
+ expect(before[0]).toBeCloseTo(25);
+ expect(before[1]).toBeCloseTo(0);
+
+ // inserting a midpoint re-segments the path but must not move the
+ // point at the same normalized arc-length parameter
+ act(() => {
+ h.app.scene.mutateElement(arrow, {
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(50, 0),
+ pointFrom<LocalPoint>(100, 0),
+ ],
+ });
+ });
+
+ const after = LinearElementEditor.getPointAtPathParameter(
+ arrow,
+ 0.25,
+ arrayToMap(h.elements),
+ )!;
+ expect(after[0]).toBeCloseTo(before[0]);
+ expect(after[1]).toBeCloseTo(before[1]);
+ });
+
+ it("should use the unrounded logical path of elbow arrows", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(100, 0),
+ pointFrom<LocalPoint>(100, 100),
+ ],
+ elbowed: true,
+ });
+ API.setElements([arrow]);
+ const elementsMap = arrayToMap(h.elements);
+
+ // Until mixed paths are supported, elbow arrows are treated as the
+ // straight segments between their logical points.
+ const segments = getLinearElementPathSegments(arrow, elementsMap);
+ expect(segments).toHaveLength(2);
+ for (let i = 1; i < segments.length; i++) {
+ const prevEnd = segments[i - 1][segments[i - 1].length - 1];
+ expect(segments[i][0][0]).toBeCloseTo(prevEnd[0]);
+ expect(segments[i][0][1]).toBeCloseTo(prevEnd[1]);
+ }
+
+ const expectedPoints = [
+ pointFrom<GlobalPoint>(0, 0),
+ pointFrom<GlobalPoint>(50, 0),
+ pointFrom<GlobalPoint>(100, 0),
+ pointFrom<GlobalPoint>(100, 50),
+ pointFrom<GlobalPoint>(100, 100),
+ ];
+ for (const [index, parameter] of [0, 0.25, 0.5, 0.75, 1].entries()) {
+ const point = LinearElementEditor.getPointAtPathParameter(
+ arrow,
+ parameter,
+ elementsMap,
+ );
+ expect(point).toEqual(expectedPoints[index]);
+ }
+ });
+ });
+
it("should match styles for text editor", async () => {
createTwoPointerLinearElement("arrow");
Keyboard.keyPress(KEYS.ENTER);
@@ -1577,6 +1668,270 @@ describe("Test Linear Elements", () => {
expect(label.x).toBe(0);
expect(label.y).toBe(0);
});
+
+ describe("dragging the label along the arrow", () => {
+ // a tall label, so its lower half is beyond the arrow's hit threshold:
+ // there the pointer is over the label but not over the arrow's path
+ const createArrowWithTallLabel = () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: p1[0],
+ y: p1[1],
+ width: p2[0] - p1[0],
+ height: 0,
+ points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
+ });
+ const label = {
+ ...API.createElement({
+ type: "text",
+ text: "label",
+ containerId: arrow.id,
+ width: 30,
+ height: 60,
+ }),
+ labelPosition: 0.5,
+ } as ExcalidrawTextElementWithContainer;
+
+ return {
+ label,
+ arrow: {
+ ...arrow,
+ boundElements: [{ type: "text", id: label.id } as const],
+ },
+ };
+ };
+
+ // covers the label and the arrow's segment midpoint handle, but not the
+ // arrow's start point, so the arrow can still be selected by clicking it
+ const createOccluder = () =>
+ API.createElement({
+ type: "rectangle",
+ x: 30,
+ y: 5,
+ width: 30,
+ height: 50,
+ backgroundColor: "#ff0000",
+ fillStyle: "solid",
+ });
+
+ // inside the label, off the arrow's path
+ const labelOnlyPoint = pointFrom<GlobalPoint>(40, 45);
+
+ it("treats a point handle under the label as the handle, on hover and on pointer down", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: p1[0],
+ y: p1[1],
+ width: p2[0] - p1[0],
+ height: 0,
+ points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
+ });
+ const label = {
+ ...API.createElement({
+ type: "text",
+ text: "label",
+ containerId: arrow.id,
+ width: 30,
+ height: 30,
+ }),
+ // centered on the end point
+ labelPosition: 1,
+ } as ExcalidrawTextElementWithContainer;
+ API.setElements([
+ {
+ ...arrow,
+ boundElements: [{ type: "text", id: label.id } as const],
+ },
+ label,
+ ]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ // inside the label and within the end point's handle radius, but
+ // farther from the arrow's path than the arrow's own hit threshold
+ const point = pointFrom<GlobalPoint>(p2[0], p2[1] + 9);
+
+ mouse.moveTo(point[0], point[1]);
+ expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
+ expect(GlobalTestState.interactiveCanvas.style.cursor).toBe(
+ CURSOR_TYPE.POINTER,
+ );
+
+ drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
+
+ expect(
+ (h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).toBe(1);
+ expect(
+ (h.elements[0] as ExcalidrawLinearElement).points[1][0],
+ ).toBeCloseTo(p2[0] - p1[0] + 40);
+ });
+
+ it("keeps the arrow selected when a point handle is grabbed beyond the arrow's tip", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: p1[0],
+ y: p1[1],
+ width: p2[0] - p1[0],
+ height: 0,
+ points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
+ });
+ API.setElements([arrow]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ // past the end point along the arrow: inside the handle radius, but
+ // outside the arrow's own hit area
+ const point = pointFrom<GlobalPoint>(p2[0] + 9, p2[1]);
+
+ mouse.moveTo(point[0], point[1]);
+ expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
+
+ drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
+
+ expect(h.state.selectionElement).toBeNull();
+ expect(h.state.selectedElementIds[arrow.id]).toBe(true);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+ expect(
+ (h.elements[0] as ExcalidrawLinearElement).points[1][0],
+ ).toBeCloseTo(p2[0] - p1[0] + 40);
+ });
+
+ it("grabs the label when the covering element is below the arrow", () => {
+ const { arrow, label } = createArrowWithTallLabel();
+ API.setElements([createOccluder(), arrow, label]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
+
+ expect(
+ (h.elements[2] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).toBeCloseTo(0.75);
+ });
+
+ it("does not grab the label when it is covered by an element above the arrow", () => {
+ const { arrow, label } = createArrowWithTallLabel();
+ API.setElements([arrow, label, createOccluder()]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
+
+ expect(
+ (h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).toBe(0.5);
+ });
+
+ it("grabs an elbow arrow's label lying over an intermediate route point", () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(100, 0),
+ pointFrom<LocalPoint>(100, 100),
+ ],
+ elbowed: true,
+ });
+ const label = {
+ ...API.createElement({
+ type: "text",
+ text: "label",
+ containerId: arrow.id,
+ width: 30,
+ height: 30,
+ }),
+ // the arc-length middle of this symmetric elbow sits on the
+ // rounded corner, right next to the route point at (100, 0)
+ labelPosition: 0.5,
+ } as ExcalidrawTextElementWithContainer;
+ API.setElements([
+ {
+ ...arrow,
+ boundElements: [{ type: "text", id: label.id } as const],
+ },
+ label,
+ ]);
+
+ mouse.reset();
+ mouse.clickAt(0, 0);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+
+ // inside the label AND within the hit radius of the route point at
+ // (100, 0) — pre-fix the route point swallowed this pointerdown and
+ // the label never moved
+ const grabPoint = pointFrom<GlobalPoint>(97, 3);
+
+ drag(
+ grabPoint,
+ pointFrom<GlobalPoint>(grabPoint[0] - 40, grabPoint[1]),
+ );
+
+ expect(
+ (h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).not.toBe(0.5);
+ });
+
+ it("gives the segment midpoint handle precedence over the label on top of it", () => {
+ const { arrow, label } = createArrowWithTallLabel();
+ API.setElements([arrow, label]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+ expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
+ 2,
+ );
+
+ // the label sits centered on the midpoint knob; dragging there must
+ // bend the arrow, not slide the label
+ drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
+
+ expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
+ 3,
+ );
+ expect(
+ (h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).toBe(0.5);
+ });
+
+ it("leaves the segment midpoint handle grabbable under a covered label", () => {
+ const { arrow, label } = createArrowWithTallLabel();
+ API.setElements([arrow, label, createOccluder()]);
+
+ mouse.reset();
+ mouse.clickAt(p1[0], p1[1]);
+ expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
+ expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
+ 2,
+ );
+
+ // the midpoint handle sits under the label, which is itself covered
+ drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
+
+ expect(
+ h.state.selectedLinearElement?.initialState.segmentMidpoint.value,
+ ).not.toBeNull();
+ expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
+ 3,
+ );
+ expect(
+ (h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
+ ).toBe(0.5);
+ });
+ });
});
describe("Test moving linear element points", () => {
diff --git a/packages/element/tests/resize.test.tsx b/packages/element/tests/resize.test.tsx
index d353a84565..1f16326448 100644
--- a/packages/element/tests/resize.test.tsx
+++ b/packages/element/tests/resize.test.tsx
@@ -1,4 +1,9 @@
-import { pointFrom } from "@excalidraw/math";
+import {
+ bezierEquation,
+ isCurve,
+ pointDistance,
+ pointFrom,
+} from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw";
import {
@@ -16,10 +21,14 @@ import {
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
+import type { GlobalPoint } from "@excalidraw/math";
+
import type { LocalPoint } from "@excalidraw/math";
import { isLinearElement } from "../src/typeChecks";
import { resizeSingleElement } from "../src/resizeElements";
+import { distanceToElement } from "../src/distance";
+import { getLinearElementPathSegments } from "../src/utils";
import { LinearElementEditor } from "../src/linearElementEditor";
import { getElementPointsCoords } from "../src/bounds";
import { computeContainerDimensionForBoundText } from "../src/textElement";
@@ -490,35 +499,64 @@ describe("arrow element", () => {
});
const label = await UI.editText(arrow, "Hello");
const elementsMap = arrayToMap(h.elements);
- UI.resize(arrow, "se", [50, 30]);
- let labelPos = LinearElementEditor.getBoundTextElementPosition(
- arrow,
- label,
- elementsMap,
- );
- expect(labelPos.x + label.width / 2).toBeCloseTo(
- arrow.x + arrow.points[2][0],
- );
- expect(labelPos.y + label.height / 2).toBeCloseTo(
- arrow.y + arrow.points[2][1],
- );
+ // independently locate the arc-length midpoint by densely sampling the
+ // path, so a regression in the arc-length inversion the production code
+ // uses cannot cancel out of the comparison
+ const sampledPathMidpoint = (): GlobalPoint => {
+ const samples: GlobalPoint[] = [];
+ for (const segment of getLinearElementPathSegments(arrow, elementsMap)) {
+ for (let i = 0; i <= 1000; i++) {
+ const t = i / 1000;
+ samples.push(
+ isCurve(segment)
+ ? bezierEquation(segment, t)
+ : pointFrom<GlobalPoint>(
+ segment[0][0] + t * (segment[1][0] - segment[0][0]),
+ segment[0][1] + t * (segment[1][1] - segment[0][1]),
+ ),
+ );
+ }
+ }
+ const cumulative = [0];
+ for (let i = 1; i < samples.length; i++) {
+ cumulative.push(
+ cumulative[i - 1] + pointDistance(samples[i - 1], samples[i]),
+ );
+ }
+ const half = cumulative[cumulative.length - 1] / 2;
+ return samples[cumulative.findIndex((length) => length >= half)];
+ };
+
+ // the label defaults to the arc-length midpoint of the arrow's path and
+ // keeps that normalized position through resizes
+ const expectLabelAtPathMidpoint = () => {
+ const labelPos = LinearElementEditor.getBoundTextElementPosition(
+ arrow,
+ label,
+ elementsMap,
+ );
+ const centerX = labelPos.x + label.width / 2;
+ const centerY = labelPos.y + label.height / 2;
+ const pathMidpoint = sampledPathMidpoint();
+
+ expect(label.labelPosition).toBe(0.5);
+ expect(centerX).toBeCloseTo(pathMidpoint[0], 0);
+ expect(centerY).toBeCloseTo(pathMidpoint[1], 0);
+ expect(
+ distanceToElement(arrow, elementsMap, pointFrom(centerX, centerY)),
+ ).toBeLessThan(0.5);
+ };
+
+ expectLabelAtPathMidpoint();
+
+ UI.resize(arrow, "se", [50, 30]);
+ expectLabelAtPathMidpoint();
expect(label.angle).toBeCloseTo(0);
expect(label.fontSize).toEqual(20);
UI.resize(arrow, "w", [20, 0]);
- labelPos = LinearElementEditor.getBoundTextElementPosition(
- arrow,
- label,
- elementsMap,
- );
-
- expect(labelPos.x + label.width / 2).toBeCloseTo(
- arrow.x + arrow.points[2][0],
- );
- expect(labelPos.y + label.height / 2).toBeCloseTo(
- arrow.y + arrow.points[2][1],
- );
+ expectLabelAtPathMidpoint();
expect(label.angle).toBeCloseTo(0);
expect(label.fontSize).toEqual(20);
});
diff --git a/packages/excalidraw/actions/actionBoundText.tsx b/packages/excalidraw/actions/actionBoundText.tsx
index 1d19c412d8..806f6eed59 100644
--- a/packages/excalidraw/actions/actionBoundText.tsx
+++ b/packages/excalidraw/actions/actionBoundText.tsx
@@ -15,6 +15,7 @@ import {
} from "@excalidraw/element";
import {
+ DEFAULT_BOUND_TEXT_LABEL_POSITION,
computeBoundTextPosition,
computeContainerDimensionForBoundText,
getBoundTextElement,
@@ -88,6 +89,7 @@ export const actionUnbindText = register({
text: boundTextElement.originalText,
x,
y,
+ labelPosition: null,
});
app.scene.mutateElement(element, {
boundElements: element.boundElements?.filter(
@@ -160,6 +162,9 @@ export const actionBindText = register({
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,
+ labelPosition: isArrowElement(container)
+ ? DEFAULT_BOUND_TEXT_LABEL_POSITION
+ : null,
});
app.scene.mutateElement(container, {
boundElements: (container.boundElements || []).concat({
diff --git a/packages/excalidraw/actions/actionFinalize.tsx b/packages/excalidraw/actions/actionFinalize.tsx
index a0ee6aa82e..ae554d69b3 100644
--- a/packages/excalidraw/actions/actionFinalize.tsx
+++ b/packages/excalidraw/actions/actionFinalize.tsx
@@ -47,6 +47,7 @@ import type { AppState } from "../types";
type FormData = {
event: PointerEvent;
sceneCoords: { x: number; y: number };
+ hitBoundText?: boolean;
};
export const actionFinalize = register<FormData>({
@@ -86,7 +87,10 @@ export const actionFinalize = register<FormData>({
if (
isBindingElement(element) &&
- !appState.selectedLinearElement.segmentMidPointHoveredCoords
+ !appState.selectedLinearElement.segmentMidPointHoveredCoords &&
+ // a label drag along the arrow moves no endpoint, so it must not
+ // rebind either of them
+ !data.hitBoundText
) {
const newArrow = !!appState.newElement;
diff --git a/packages/excalidraw/components/App.arrowText.ts b/packages/excalidraw/components/App.arrowText.ts
index 05ea573158..9ca3307307 100644
--- a/packages/excalidraw/components/App.arrowText.ts
+++ b/packages/excalidraw/components/App.arrowText.ts
@@ -1,3 +1,5 @@
+import { CURSOR_TYPE, DRAGGING_THRESHOLD } from "@excalidraw/common";
+
import {
bindBindingElementToFixedPoint,
dragNewTextElement,
@@ -5,13 +7,15 @@ import {
getEndpointBoundTextDragAnchor,
getTextBindingForArrowEndpoint,
getUnboundArrowEndpointAtPoint,
+ hitElementBoundText,
isArrowElement,
isBindingEnabled,
isEndpointBoundText,
isTextElement,
+ LinearElementEditor,
} from "@excalidraw/element";
-import { pointFrom } from "@excalidraw/math";
+import { pointDistance, pointFrom } from "@excalidraw/math";
import type { ArrowEndpoint } from "@excalidraw/element";
import type {
@@ -19,19 +23,27 @@ import type {
ExcalidrawTextElement,
FixedPoint,
NonDeleted,
+ NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type App from "./App";
-import type { AppState } from "../types";
+import type { AppState, PointerDownState } from "../types";
/**
- * The text tool's interaction with arrows: the hover affordance showing where
- * a click would attach text to an arrow — a free endpoint (binds the arrow to
- * a new text element positioned against that endpoint) or the arrow's midpoint
- * (adds a label bound to the arrow) — and the endpoint-bound flavor of
- * drag-sizing a new text.
+ * Text ↔ arrow interactions.
+ *
+ * With the text tool: the hover affordance showing where a click would attach
+ * text to an arrow — a free endpoint (binds the arrow to a new text element
+ * positioned against that endpoint) or the arrow's midpoint (adds a label
+ * bound to the arrow) — and the endpoint-bound flavor of drag-sizing a new
+ * text.
+ *
+ * With the selection tool: dragging an arrow's existing label along the arrow
+ * — the grab affordance, the drag itself, and where a double-click starts
+ * editing a label the drag has moved.
*
- * The scene-level logic lives in `@excalidraw/element`'s `arrowEndpointText.ts`.
+ * The scene-level logic lives in `@excalidraw/element`'s
+ * `arrowEndpointText.ts` and `linearElementEditor.ts`.
*/
export class AppArrowText {
constructor(private app: App) {}
@@ -234,4 +246,107 @@ export class AppArrowText {
return true;
}
+
+ /**
+ * Whether the arrow's label is what a grab at this position would pick up:
+ * the pointer is over the label, and no element stacked above the arrow
+ * owns the hit instead.
+ */
+ isBoundTextGrabbable(
+ element: NonDeletedExcalidrawElement,
+ x: number,
+ y: number,
+ ): boolean {
+ if (
+ !isArrowElement(element) ||
+ !hitElementBoundText(
+ pointFrom(x, y),
+ element,
+ this.app.scene.getNonDeletedElementsMap(),
+ )
+ ) {
+ return false;
+ }
+
+ const hitElements = this.app.getElementsAtPosition(x, y);
+ const arrowIndex = hitElements.findIndex((el) => el.id === element.id);
+
+ return (
+ arrowIndex !== -1 &&
+ !hitElements
+ .slice(arrowIndex + 1)
+ .some((el) => this.app.hitElement(x, y, el, false))
+ );
+ }
+
+ /**
+ * The pointer-move half of dragging a label along its arrow. Owns the move
+ * whenever the gesture started on the label (`pointerDownState.hit.arrowLabel`),
+ * dragging only once past the threshold. Returns whether it owned it.
+ */
+ maybeDragLabel(
+ linearElementEditor: LinearElementEditor,
+ pointerDownState: PointerDownState,
+ pointerCoords: { x: number; y: number },
+ ): boolean {
+ if (!pointerDownState.hit.arrowLabel) {
+ return false;
+ }
+
+ this.app.cursor.set(CURSOR_TYPE.GRABBING);
+
+ if (
+ linearElementEditor.isDragging ||
+ pointDistance(
+ pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
+ pointFrom(pointerCoords.x, pointerCoords.y),
+ ) >=
+ DRAGGING_THRESHOLD / this.app.state.zoom.value
+ ) {
+ const updatedEditor = LinearElementEditor.handleBoundTextDragging(
+ linearElementEditor,
+ this.app.scene,
+ pointerCoords.x,
+ pointerCoords.y,
+ );
+ if (updatedEditor) {
+ pointerDownState.drag.hasOccurred = true;
+ this.app.setState({
+ selectedLinearElement: updatedEditor,
+ });
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Where a double-click on a labeled arrow should start text editing: the
+ * center of the label itself, which a label drag may have moved away from
+ * the arrow's midpoint. Null when the element is not a labeled arrow.
+ */
+ getLabelCenter(element: ExcalidrawElement): { x: number; y: number } | null {
+ const elementsMap = this.app.scene.getNonDeletedElementsMap();
+
+ if (!isArrowElement(element)) {
+ return null;
+ }
+
+ const boundTextElement = getBoundTextElement(element, elementsMap);
+
+ if (!boundTextElement) {
+ return null;
+ }
+
+ const { x, y } = LinearElementEditor.getBoundTextElementPosition(
+ element,
+ boundTextElement,
+ elementsMap,
+ );
+
+ return {
+ x: x + boundTextElement.width / 2,
+ y: y + boundTextElement.height / 2,
+ };
+ }
}
diff --git a/packages/excalidraw/components/App.cursor.ts b/packages/excalidraw/components/App.cursor.ts
index 812a30985f..dcab3ff10f 100644
--- a/packages/excalidraw/components/App.cursor.ts
+++ b/packages/excalidraw/components/App.cursor.ts
@@ -160,6 +160,41 @@ export class AppCursor {
};
};
+ /**
+ * Re-runs the hover cursor logic at the last known pointer position by
+ * re-dispatching a synthetic pointermove — for state changes that alter
+ * what hovering means without the pointer moving (e.g. the tool reverting
+ * to selection after an element is created). Mouse only: touch and pen
+ * have no resting hover to restore.
+ */
+ refreshHover = () => {
+ const lastEvent =
+ this.app.lastPointerMoveEvent ?? this.app.lastPointerUpEvent;
+
+ if (!lastEvent || !this.canvas) {
+ return;
+ }
+
+ const pointerType = (lastEvent as PointerEvent).pointerType;
+ if (pointerType && pointerType !== "mouse") {
+ return;
+ }
+
+ // jsdom has no PointerEvent; a MouseEvent of type "pointermove" walks
+ // the identical dispatch path
+ const EventConstructor =
+ typeof PointerEvent !== "undefined" ? PointerEvent : MouseEvent;
+
+ this.canvas.dispatchEvent(
+ new EventConstructor("pointermove", {
+ bubbles: true,
+ cancelable: true,
+ clientX: lastEvent.clientX,
+ clientY: lastEvent.clientY,
+ }),
+ );
+ };
+
/** clears the inline cursor so the environment default (CSS) applies */
private clear = () => {
this.set("");
diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsx
index b6b1eb0a4f..da64b07c15 100644
--- a/packages/excalidraw/components/App.tsx
+++ b/packages/excalidraw/components/App.tsx
@@ -257,6 +257,7 @@ import {
isEligibleFrameChildType,
getBindingStrategyForDraggingBindingElementEndpoints,
isNonDeletedElement,
+ DEFAULT_BOUND_TEXT_LABEL_POSITION,
} from "@excalidraw/element";
import type { GlobalPoint, LocalPoint, Radians } from "@excalidraw/math";
@@ -6580,7 +6581,7 @@ class App extends React.Component<AppProps, AppState> {
}
// NOTE: Hot path for hit testing, so avoid unnecessary computations
- private getElementsAtPosition(
+ getElementsAtPosition(
x: number,
y: number,
opts?: {
@@ -6650,7 +6651,7 @@ class App extends React.Component<AppProps, AppState> {
);
}
- private hitElement(
+ hitElement(
x: number,
y: number,
element: NonDeletedExcalidrawElement,
@@ -6822,13 +6823,15 @@ class App extends React.Component<AppProps, AppState> {
shouldBindToContainer = true;
}
}
- // The endpoint flow always creates a fresh text: the lookups below would
- // otherwise adopt a currently selected text (wherever it sits on canvas)
- // or one that happens to lie around the anchor — even a container-bound
- // one — and bind the arrow to that instead.
const existingTextElement = arrowEndpointBinding
? null
: this.getSelectedTextElement(container) ||
+ (container && isArrowElement(container)
+ ? getBoundTextElement(
+ container,
+ this.scene.getNonDeletedElementsMap(),
+ )
+ : null) ||
this.getTextElementAtPosition(sceneX, sceneY);
const fontFamily =
@@ -6934,6 +6937,10 @@ class App extends React.Component<AppProps, AppState> {
? VERTICAL_ALIGN.MIDDLE
: DEFAULT_VERTICAL_ALIGN),
containerId: shouldBindToContainer ? container?.id : undefined,
+ labelPosition:
+ shouldBindToContainer && container && isArrowElement(container)
+ ? DEFAULT_BOUND_TEXT_LABEL_POSITION
+ : null,
groupIds: container?.groupIds ?? [],
lineHeight,
angle: container
@@ -8234,6 +8241,10 @@ class App extends React.Component<AppProps, AppState> {
invalidateContextMenu = true;
};
+ /**
+ * Applies the hover affordances of a selected linear element: the cursor,
+ * plus the hovered-handle state that renders them highlighted.
+ */
handleHoverSelectedLinearElement(
linearElementEditor: LinearElementEditor,
scenePointerX: number,
@@ -8250,63 +8261,55 @@ class App extends React.Component<AppProps, AppState> {
return;
}
if (this.state.selectedLinearElement) {
- let hoverPointIndex = -1;
- let segmentMidPointHoveredCoords = null;
- if (
- hitElementItself({
- point: pointFrom(scenePointerX, scenePointerY),
- element,
- elementsMap,
- threshold: this.getElementHitThreshold(element),
- })
- ) {
- hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
- element,
- elementsMap,
- this.state.zoom,
- scenePointerX,
- scenePointerY,
- );
- segmentMidPointHoveredCoords =
- LinearElementEditor.getSegmentMidpointHitCoords(
+ // the same hit tests, in the same precedence, as
+ // `LinearElementEditor.handlePointerDown`, so the cursor never promises
+ // an interaction (e.g. grabbing the label) that pointer down won't
+ // deliver. Both handle radii exceed the element's own hit threshold,
+ // so these must not be gated on hitting the element itself.
+ const hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
+ element,
+ elementsMap,
+ this.state.zoom,
+ scenePointerX,
+ scenePointerY,
+ );
+ const isHoveringAPointHandle = LinearElementEditor.isPointHandle(
+ element,
+ hoverPointIndex,
+ );
+ const segmentMidPointHoveredCoords = isHoveringAPointHandle
+ ? null
+ : LinearElementEditor.getSegmentMidpointHitCoords(
linearElementEditor,
{ x: scenePointerX, y: scenePointerY },
this.state,
- this.scene.getNonDeletedElementsMap(),
+ elementsMap,
);
- const isHoveringAPointHandle = isElbowArrow(element)
- ? hoverPointIndex === 0 ||
- hoverPointIndex === element.points.length - 1
- : hoverPointIndex >= 0;
- if (isHoveringAPointHandle || segmentMidPointHoveredCoords) {
- this.cursor.set(CURSOR_TYPE.POINTER);
- } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
- if (
- // Elbow arrows can only be moved when unconnected
- !isElbowArrow(element) ||
- !(element.startBinding || element.endBinding)
- ) {
- if (
- this.state.activeTool.type !== "lasso" ||
- Object.keys(this.state.selectedElementIds).length > 0
- ) {
- this.cursor.set(CURSOR_TYPE.MOVE);
- }
- }
- }
- } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
- if (
- // Elbow arrow can only be moved when unconnected
- !isElbowArrow(element) ||
- !(element.startBinding || element.endBinding)
- ) {
- if (
- this.state.activeTool.type !== "lasso" ||
- Object.keys(this.state.selectedElementIds).length > 0
- ) {
- this.cursor.set(CURSOR_TYPE.MOVE);
- }
- }
+
+ if (isHoveringAPointHandle || segmentMidPointHoveredCoords) {
+ this.cursor.set(CURSOR_TYPE.POINTER);
+ } else if (
+ // an arrow's bound text is draggable along the arrow. The handles
+ // and the midpoint knob sitting under the label keep precedence so a
+ // labeled arrow can still be bent at its middle, while the label
+ // itself is grabbable even where it extends beyond the arrow's own
+ // hit area.
+ this.arrowText.isBoundTextGrabbable(
+ element,
+ scenePointerX,
+ scenePointerY,
+ )
+ ) {
+ this.cursor.set(CURSOR_TYPE.GRAB);
+ } else if (
+ this.hitElement(scenePointerX, scenePointerY, element) &&
+ // Elbow arrows can only be moved when unconnected
+ (!isElbowArrow(element) ||
+ !(element.startBinding || element.endBinding)) &&
+ (this.state.activeTool.type !== "lasso" ||
+ Object.keys(this.state.selectedElementIds).length > 0)
+ ) {
+ this.cursor.set(CURSOR_TYPE.MOVE);
}
if (
@@ -9230,6 +9233,7 @@ class App extends React.Component<AppProps, AppState> {
allHitElements: [],
wasAddedToSelection: false,
hasBeenDuplicated: false,
+ arrowLabel: false,
hasHitCommonBoundingBoxOfSelectedElements:
this.isHittingCommonBoundingBoxOfSelectedElements(
origin,
@@ -9405,9 +9409,11 @@ class App extends React.Component<AppProps, AppState> {
linearElementEditor,
this.scene,
);
+
if (ret.hitElement) {
pointerDownState.hit.element = ret.hitElement;
}
+ pointerDownState.hit.arrowLabel = ret.hitBoundText;
if (ret.linearElementEditor) {
this.setState({ selectedLinearElement: ret.linearElementEditor });
}
@@ -9539,7 +9545,12 @@ class App extends React.Component<AppProps, AppState> {
const someHitElementIsSelected =
pointerDownState.hit.allHitElements.some((element) =>
this.isASelectedElement(element),
- );
+ ) ||
+ // the selected linear element's point handles, midpoint knob and
+ // label extend beyond its own hit area, so a hit reported by
+ // `LinearElementEditor.handlePointerDown` counts even when the
+ // position-based hit test above missed the element
+ (hitElement !== null && this.isASelectedElement(hitElement));
if (
(hitElement === null || !someHitElementIsSelected) &&
!event.shiftKey &&
@@ -9819,8 +9830,14 @@ class App extends React.Component<AppProps, AppState> {
if (hasBoundTextElement(element)) {
container = element as NonDeleted<ExcalidrawTextContainer>;
- sceneX = element.x + element.width / 2;
- sceneY = element.y + element.height / 2;
+ const labelCenter = this.arrowText.getLabelCenter(element);
+ if (labelCenter) {
+ sceneX = labelCenter.x;
+ sceneY = labelCenter.y;
+ } else {
+ sceneX = element.x + element.width / 2;
+ sceneY = element.y + element.height / 2;
+ }
}
this.startTextEditing({
sceneX,
@@ -10706,6 +10723,16 @@ class App extends React.Component<AppProps, AppState> {
return;
}
+ if (
+ this.arrowText.maybeDragLabel(
+ linearElementEditor,
+ pointerDownState,
+ pointerCoords,
+ )
+ ) {
+ return;
+ }
+
if (
LinearElementEditor.shouldAddMidpoint(
this.state.selectedLinearElement,
@@ -11637,6 +11664,7 @@ class App extends React.Component<AppProps, AppState> {
this.actionManager.executeAction(actionFinalize, "ui", {
event: childEvent,
sceneCoords,
+ hitBoundText: pointerDownState.hit.arrowLabel,
});
if (editingLinearElement !== this.state.selectedLinearElement) {
this.setState({
@@ -11694,6 +11722,7 @@ class App extends React.Component<AppProps, AppState> {
this.actionManager.executeAction(actionFinalize, "ui", {
event: childEvent,
sceneCoords,
+ hitBoundText: pointerDownState.hit.arrowLabel,
});
}
@@ -12494,13 +12523,19 @@ class App extends React.Component<AppProps, AppState> {
}),
},
// reset once the tool revert has settled
- () => this.cursor.reset(),
+ () => {
+ this.cursor.reset();
+ this.cursor.refreshHover();
+ },
);
} else {
- this.setState({
- newElement: null,
- suggestedBinding: null,
- });
+ this.setState(
+ {
+ newElement: null,
+ suggestedBinding: null,
+ },
+ () => this.cursor.refreshHover(),
+ );
}
});
}
diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.ts
index b8567aa5cd..d3d570fce9 100644
--- a/packages/excalidraw/data/restore.ts
+++ b/packages/excalidraw/data/restore.ts
@@ -1,4 +1,9 @@
-import { isFiniteNumber, isValidPoint, pointFrom } from "@excalidraw/math";
+import {
+ clamp,
+ isFiniteNumber,
+ isValidPoint,
+ pointFrom,
+} from "@excalidraw/math";
import {
colorToHex,
@@ -551,6 +556,9 @@ export const restoreElement = (
originalText: element.originalText || text,
autoResize: element.autoResize ?? true,
lineHeight,
+ labelPosition: isFiniteNumber(element.labelPosition)
+ ? clamp(element.labelPosition, 0, 1)
+ : null,
});
// if empty text, mark as deleted. We keep in array
diff --git a/packages/excalidraw/renderer/staticSvgScene.ts b/packages/excalidraw/renderer/staticSvgScene.ts
index 5f6d36daad..488fbaa475 100644
--- a/packages/excalidraw/renderer/staticSvgScene.ts
+++ b/packages/excalidraw/renderer/staticSvgScene.ts
@@ -1,4 +1,5 @@
import {
+ BOUND_TEXT_PADDING,
FRAME_STYLE,
MAX_DECIMALS_FOR_SVG_EXPORT,
SVG_NS,
@@ -321,14 +322,23 @@ const renderElementToSvg = (
elementsMap,
);
- const maskX = offsetX + boundTextCoords.x - element.x;
- const maskY = offsetY + boundTextCoords.y - element.y;
+ // the same padded hole the canvas renderers cut around the label
+ const maskX =
+ offsetX + boundTextCoords.x - element.x - BOUND_TEXT_PADDING;
+ const maskY =
+ offsetY + boundTextCoords.y - element.y - BOUND_TEXT_PADDING;
maskRectInvisible.setAttribute("x", maskX.toString());
maskRectInvisible.setAttribute("y", maskY.toString());
maskRectInvisible.setAttribute("fill", "#000");
- maskRectInvisible.setAttribute("width", `${boundText.width}`);
- maskRectInvisible.setAttribute("height", `${boundText.height}`);
+ maskRectInvisible.setAttribute(
+ "width",
+ `${boundText.width + BOUND_TEXT_PADDING * 2}`,
+ );
+ maskRectInvisible.setAttribute(
+ "height",
+ `${boundText.height + BOUND_TEXT_PADDING * 2}`,
+ );
maskRectInvisible.setAttribute("opacity", "1");
maskPath.appendChild(maskRectInvisible);
}
diff --git a/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap
index 48cc148196..663311b6e1 100644
--- a/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap
+++ b/packages/excalidraw/tests/__snapshots__/export.test.tsx.snap
@@ -1,7 +1,7 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`export > export svg-embedded scene > svg-embdedded scene export output 1`] = `
-"<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36"><!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nHVTS27bMFx1MDAxMN33XHUwMDE0grItXHUwMDEy2UW68C7NXHUwMDA3zVwiXdRcdTAwMDW6KLpgxLE0ME1cdTAwMTLkKLZrXHUwMDE4yDG661x1MDAxNXOEXGZpVTTlRFx1MDAwMlxi8M3vzZvh7kNRlLS1UM6KXHUwMDEyNrVQKJ1Yl1x1MDAxZlx1MDAwM/5cdTAwMDTOo9Fsmsa7N52ro2dLZGdcdTAwMTdcdTAwMTfKcEBrPM0+VVV1XGJcdTAwMDJcdTAwMDUr0OTZ7Vx1MDAxN9+LYlx1MDAxN0+2oFxmoVfRLVx1MDAwMv/rXHUwMDEybCihXHUwMDFihqrhts1ua5TUMjL5PEAtYNNSjlx03SjIXHUwMDAyPTmzhGujjFx1MDAwYlx1MDAxNc8mXHUwMDEw/lT0UdTLxplOy8GHnNDeXG7HzSS/XHUwMDA1KjWnbczOerBa5ajGz57idIS/XHUwMDE3xUWbVoNcdTAwMGaCTVx1MDAwNtRYUSOF5idV6lwiMLT3Mmr7O3FyYlx1MDAwNfdBXFzdKTXAqCVsxmBssa+WXHUwMDE5PIDMXHUwMDE4pOGfYN+MrnN50d/w3CmmWFxi5SFcdFx1MDAxYlxu3qadyIp2VlxuXHUwMDFh1VWol2M/3rPlXHUwMDFiuePesKIv//4+XHUwMDFmjchomuOfQHBaZeidWKFcbppeZimuXHUwMDE0NqHPUsHiaNTcLCHv92AmY5O15nxcdTAwMDI1uFPhjcNcdTAwMDa1UD/epCc6Mt/BXHUwMDFmXGKS6+C4c/g6bPP59DJcdTAwMWH2fMZZl8LaObFebD28Kd5cdTAwMDeUo1ZcdTAwMGZcdTAwMTiBTW1G6MFIuNXiUY11LJ9cdTAwMTDWX07X/2xcdTAwMTG/nng/godOXHUwMDExznnUNfFcdTAwMWWEee5cdTAwMDK/feTHb1x1MDAwM3po/1xua2IoWiJ9<!-- payload-end --></metadata><defs><style class="style-fonts">
+"<svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 36 36" width="36" height="36"><!-- svg-source:excalidraw --><metadata><!-- payload-type:application/vnd.excalidraw+json --><!-- payload-version:2 --><!-- payload-start -->eyJ2ZXJzaW9uIjoiMSIsImVuY29kaW5nIjoiYnN0cmluZyIsImNvbXByZXNzZWQiOnRydWUsImVuY29kZWQiOiJ4nHVTwY7TMFx1MDAxML3zXHUwMDE1UfaK2LRcYlx1MDAwZb0tsCv2sFxiUSRcdTAwMGWIg1x1MDAxYk+TUV3bsifblqpcdTAwMTKfwY1f5Fx1MDAxM1x1MDAxODshrtPdVorkNzN+b96Mjy+KoqSDhXJRlLCvhULpxK58XHUwMDE58EdwXHUwMDFljebQPJ696VxcXHUwMDFkM1tcIru4vlaGXHUwMDBiWuNp8bqqqr5cYlx1MDAxNGxBk+e073wuimP8clx1MDAwNGUovYlpXHUwMDEx+M9LsKeE7lx1MDAxOarG0yE77VBSy8js7VxitYBNSzkmdKMgK/TkzFx1MDAwNt5cdTAwMWJlXFxgvJpB+CfSlag3jTOdlmNcdTAwMGU5ob1cdTAwMTWOm0l5a1RqSYd4O/vBbpVcdTAwMTOOb4PE+Vx1MDAwNH+uikmbVoNcdTAwMGaGzUbUWFEjheZnVepcIii09zJ6+yNpcmJcdTAwMGL3wVxc3Sk1wqgl7KdgbHFgy1x1MDAwMlx1MDAxZUBmXG7S8C+wT0bXub3oP/DcKV6xXHUwMDE2ykMyNlx1MDAxMN6mnchIOytcdTAwMDVNeFx1MDAxNerNNI/3bPPE3XFv2NG/f37/Olx1MDAxYpHRtMSfQeC8ytA7sUVcdTAwMTU8fZNdcaOwXHR9llxu1mej5mZcdHm/xzBcdTAwMTmbojXfJ1CDuzTeOGxQXHUwMDBi9fVJeaIj81x1MDAwNXwvkFxcXHUwMDA3553Dx3GbX82TSiVWoD5cdTAwMWKP1E8k0MXYib9xXHUwMDExSmHtkthMjvZcdTAwMGaOl1x1MDAwNeXEh1x1MDAxZSOwyYNcYj1cdTAwMThcdLdarNTU5PJcdTAwMTFh9+7ybVxcreNv6GqYz0OnXGKXvFx1MDAwN3WQXHUwMDE5hn1cZvpOUVx1MDAxZj9cdTAwMWNcdTAwMTig0z+sMjD+In0=<!-- payload-end --></metadata><defs><style class="style-fonts">
</style></defs><rect x="0" y="0" width="36" height="36" fill="#ffffff"></rect><g transform="translate(10 10) rotate(0 8 8)" data-id="A"><text x="0" y="17.619999999999997" font-family="Excalifont, Xiaolai, sans-serif, Segoe UI Emoji" font-size="20px" fill="#1e1e1e" text-anchor="start" style="white-space: pre;" direction="ltr" dominant-baseline="alphabetic">😀</text></g></svg>"
`;
diff --git a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
index df4ce4d2ab..a17b3e9685 100644
--- a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
+++ b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap
@@ -2841,6 +2841,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -2880,6 +2881,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id5",
"index": "a2",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3150,6 +3152,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a0",
"isDeleted": true,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3189,6 +3192,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id5",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3247,6 +3251,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"height": 100,
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3475,6 +3480,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id5",
"index": "a0V",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3514,6 +3520,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -3805,6 +3812,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -4062,6 +4070,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -4308,6 +4317,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -4571,6 +4581,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -4627,6 +4638,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"height": 25,
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -4848,6 +4860,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -5083,6 +5096,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -5313,6 +5327,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a1",
"isDeleted": true,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -5571,6 +5586,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"id": "id1",
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -5627,6 +5643,7 @@ exports[`history > multiplayer undo/redo > conflicts in bound text elements and
"height": 100,
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -16977,6 +16994,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -17271,6 +17289,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"height": 100,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -17731,6 +17750,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -17915,6 +17935,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"height": 100,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -18383,6 +18404,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -18567,6 +18589,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"height": 100,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -19033,6 +19056,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -19303,6 +19327,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"height": 100,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -19791,6 +19816,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"id": "id1",
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -20057,6 +20083,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding
"height": 100,
"index": "a1",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
diff --git a/packages/excalidraw/tests/data/__snapshots__/restore.test.ts.snap b/packages/excalidraw/tests/data/__snapshots__/restore.test.ts.snap
index 0854e48d36..6eeaaa4928 100644
--- a/packages/excalidraw/tests/data/__snapshots__/restore.test.ts.snap
+++ b/packages/excalidraw/tests/data/__snapshots__/restore.test.ts.snap
@@ -367,6 +367,7 @@ exports[`restoreElements > should restore text element correctly passing value f
"id": "id-text01",
"index": "a0",
"isDeleted": false,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
@@ -409,6 +410,7 @@ exports[`restoreElements > should restore text element correctly with unknown fo
"id": "id-text01",
"index": "a0",
"isDeleted": true,
+ "labelPosition": null,
"lineHeight": "1.25000",
"link": null,
"locked": false,
diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.ts
index 4da68316d5..5ce8b1fc84 100644
--- a/packages/excalidraw/tests/scene/export.test.ts
+++ b/packages/excalidraw/tests/scene/export.test.ts
@@ -237,6 +237,60 @@ describe("exportToSvg", () => {
// the masked arrow group still renders its line (not clipped away)
expect(svgElement.querySelector("g[mask] path")).not.toBeNull();
});
+
+ it("cuts the same padded hole around an arrow label as the canvas", async () => {
+ const arrow = API.createElement({
+ type: "arrow",
+ id: "arrow-hole",
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 0,
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],
+ boundElements: [{ type: "text", id: "label-hole" }],
+ });
+ const label = API.createElement({
+ type: "text",
+ id: "label-hole",
+ text: "label",
+ width: 50,
+ height: 20,
+ containerId: "arrow-hole",
+ });
+
+ const svgElement = await exportUtils.exportToSvg(
+ [arrow, label] as NonDeletedExcalidrawElement[],
+ { ...DEFAULT_OPTIONS, exportPadding: 0 },
+ null,
+ );
+
+ // the mask's first rect is the visible region, sized to the arrow plus
+ // its offset within the export; the second is the hole cut for the label
+ const [visible, hole] = Array.from(
+ svgElement.querySelectorAll("mask rect"),
+ );
+ expect(hole).toBeDefined();
+ const offsetX = Number(visible.getAttribute("width")) - 100 - arrow.width;
+ const offsetY = Number(visible.getAttribute("height")) - 100 - arrow.height;
+
+ // the label sits centered on the arrow's midpoint; the hole is its box
+ // grown by the padding on every side, in the mask's (arrow-relative)
+ // coordinates
+ const labelLeft = arrow.x + arrow.width / 2 - label.width / 2;
+ const labelTop = arrow.y - label.height / 2;
+ expect(Number(hole.getAttribute("x"))).toBe(
+ offsetX + labelLeft - arrow.x - BOUND_TEXT_PADDING,
+ );
+ expect(Number(hole.getAttribute("y"))).toBe(
+ offsetY + labelTop - arrow.y - BOUND_TEXT_PADDING,
+ );
+ expect(Number(hole.getAttribute("width"))).toBe(
+ label.width + BOUND_TEXT_PADDING * 2,
+ );
+ expect(Number(hole.getAttribute("height"))).toBe(
+ label.height + BOUND_TEXT_PADDING * 2,
+ );
+ });
});
describe("exportToCanvas", () => {
diff --git a/packages/excalidraw/tests/selection.test.tsx b/packages/excalidraw/tests/selection.test.tsx
index e3b6b34f93..64ec933d90 100644
--- a/packages/excalidraw/tests/selection.test.tsx
+++ b/packages/excalidraw/tests/selection.test.tsx
@@ -1280,7 +1280,7 @@ describe("select single element on the scene", () => {
fireEvent.pointerDown(canvas, { clientX: 40, clientY: 40 });
fireEvent.pointerUp(canvas);
- expect(renderInteractiveScene).toHaveBeenCalledTimes(10);
+ expect(renderInteractiveScene).toHaveBeenCalledTimes(11);
expect(renderStaticScene).toHaveBeenCalledTimes(9);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
@@ -1325,7 +1325,7 @@ describe("select single element on the scene", () => {
fireEvent.pointerDown(canvas, { clientX: 40, clientY: 40 });
fireEvent.pointerUp(canvas);
- expect(renderInteractiveScene).toHaveBeenCalledTimes(10);
+ expect(renderInteractiveScene).toHaveBeenCalledTimes(11);
expect(renderStaticScene).toHaveBeenCalledTimes(9);
expect(h.state.selectionElement).toBeNull();
expect(h.elements.length).toEqual(1);
diff --git a/packages/excalidraw/types.ts b/packages/excalidraw/types.ts
index 9bd45b1e02..289314cc2f 100644
--- a/packages/excalidraw/types.ts
+++ b/packages/excalidraw/types.ts
@@ -1141,6 +1141,7 @@ export type AppClassProperties = {
dismissLinearEditor: App["dismissLinearEditor"];
flowchart: App["flowchart"];
drawShape: App["drawShape"];
+ arrowText: App["arrowText"];
cursor: App["cursor"];
bucketFill: App["bucketFill"];
isToolLocked: App["isToolLocked"];
@@ -1209,6 +1210,9 @@ export type PointerDownState = Readonly<{
// elements, which is useful for discriminating between selecitng
// the entire selection vs a specific element
hasHitCommonBoundingBoxOfSelectedElements: boolean;
+ // Whether the pointer went down on the selected arrow's label, which
+ // makes the gesture a label drag along the arrow rather than a point drag
+ arrowLabel: boolean;
};
// This is determined on the initial pointer down event to
// set various interaction modalities
diff --git a/packages/math/src/curve.ts b/packages/math/src/curve.ts
index 5d17ab79a9..ffa4971270 100644
--- a/packages/math/src/curve.ts
+++ b/packages/math/src/curve.ts
@@ -212,23 +212,19 @@ export function curveIntersectLineSegment<
}
/**
- * Finds the closest point on the Bezier curve from another point
+ * Finds the parameter on the Bezier curve whose point is closest to another
+ * point
*
- * @param x
- * @param y
- * @param P0
- * @param P1
- * @param P2
- * @param P3
- * @param tolerance
- * @param maxLevel
- * @returns
+ * @param c The curve to test
+ * @param p The point to measure from
+ * @param tolerance The width of the search window under which the bisection
+ * stops refining the parameter
*/
-export function curveClosestPoint<Point extends GlobalPoint | LocalPoint>(
+export function curveClosestParameter<Point extends GlobalPoint | LocalPoint>(
c: Curve<Point>,
p: Point,
tolerance: number = 1e-3,
-): Point | null {
+): number {
const localMinimum = (
min: number,
max: number,
@@ -253,7 +249,7 @@ export function curveClosestPoint<Point extends GlobalPoint | LocalPoint>(
const maxSteps = 30;
let closestStep = 0;
- for (let min = Infinity, step = 0; step < maxSteps; step++) {
+ for (let min = Infinity, step = 0; step <= maxSteps; step++) {
const d = pointDistance(p, bezierEquation(c, step / maxSteps));
if (d < min) {
min = d;
@@ -263,18 +259,27 @@ export function curveClosestPoint<Point extends GlobalPoint | LocalPoint>(
const t0 = Math.max((closestStep - 1) / maxSteps, 0);
const t1 = Math.min((closestStep + 1) / maxSteps, 1);
- const solution = localMinimum(t0, t1, (t) =>
+ const param = localMinimum(t0, t1, (t) =>
pointDistance(p, bezierEquation(c, t)),
);
- // `solution` is only nullish when the search window is narrower than the
- // tolerance (e.g. a caller-supplied tolerance larger than the window). A
- // legitimate solution of `t = 0` must not be treated as a failure.
- if (solution == null) {
- return null;
- }
+ return param ?? closestStep / maxSteps;
+}
- return bezierEquation(c, solution);
+/**
+ * Finds the closest point on the Bezier curve from another point
+ *
+ * @param c The curve to test
+ * @param p The point to measure from
+ * @param tolerance The width of the search window under which the bisection
+ * stops refining the parameter
+ */
+export function curveClosestPoint<Point extends GlobalPoint | LocalPoint>(
+ c: Curve<Point>,
+ p: Point,
+ tolerance: number = 1e-3,
+): Point {
+ return bezierEquation(c, curveClosestParameter(c, p, tolerance));
}
/**
@@ -287,16 +292,9 @@ export function curveClosestPoint<Point extends GlobalPoint | LocalPoint>(
export function curvePointDistance<Point extends GlobalPoint | LocalPoint>(
c: Curve<Point>,
p: Point,
+ tolerance: number = 1e-3,
) {
- const closest = curveClosestPoint(c, p);
-
- // No closest point found: report an "infinitely far" distance so this curve
- // is never mistaken for the nearest component when fed into `Math.min`.
- if (!closest) {
- return Infinity;
- }
-
- return pointDistance(p, closest);
+ return pointDistance(p, curveClosestPoint(c, p, tolerance));
}
/**
@@ -518,6 +516,8 @@ export function curveLengthAtParameter<P extends GlobalPoint | LocalPoint>(
export function curvePointAtLength<P extends GlobalPoint | LocalPoint>(
c: Curve<P>,
percent: number,
+ /** pass the curve's total length when already known to skip recomputing it */
+ totalLength: number = curveLength(c),
): P {
if (percent <= 0) {
return bezierEquation(c, 0);
@@ -527,7 +527,6 @@ export function curvePointAtLength<P extends GlobalPoint | LocalPoint>(
return bezierEquation(c, 1);
}
- const totalLength = curveLength(c);
const targetLength = totalLength * percent;
// Binary search to find parameter t where length at t equals target length
diff --git a/packages/math/src/segment.ts b/packages/math/src/segment.ts
index 7523ef3f2f..514abc801f 100644
--- a/packages/math/src/segment.ts
+++ b/packages/math/src/segment.ts
@@ -1,7 +1,10 @@
import { line, linesIntersectAt } from "./line";
+
import {
isPoint,
pointCenter,
+ pointDistance,
+ pointFrom,
pointFromVector,
pointRotateRads,
} from "./point";
@@ -117,39 +120,24 @@ export const distanceToLineSegment = <Point extends LocalPoint | GlobalPoint>(
point: Point,
line: LineSegment<Point>,
) => {
- const [x, y] = point;
- const [[x1, y1], [x2, y2]] = line;
-
- const A = x - x1;
- const B = y - y1;
- const C = x2 - x1;
- const D = y2 - y1;
-
- const dot = A * C + B * D;
- const len_sq = C * C + D * D;
- let param = -1;
- if (len_sq !== 0) {
- param = dot / len_sq;
- }
+ return pointDistance(
+ point,
+ lineSegmentPointAt(line, lineSegmentClosestParameter(point, line)),
+ );
+};
- let xx;
- let yy;
-
- if (param < 0) {
- xx = x1;
- yy = y1;
- } else if (param > 1) {
- xx = x2;
- yy = y2;
- } else {
- xx = x1 + param * C;
- yy = y1 + param * D;
- }
+/**
+ * Returns the point at parameter `t` along the segment, where `t = 0` is the
+ * segment's start and `t = 1` its end. Not clamped.
+ */
+export function lineSegmentPointAt<Point extends GlobalPoint | LocalPoint>(
+ line: LineSegment<Point>,
+ t: number,
+): Point {
+ const [[x1, y1], [x2, y2]] = line;
- const dx = x - xx;
- const dy = y - yy;
- return Math.sqrt(dx * dx + dy * dy);
-};
+ return pointFrom<Point>(x1 + t * (x2 - x1), y1 + t * (y2 - y1));
+}
/**
* Returns the intersection point of a segment and a line
@@ -193,3 +181,24 @@ export function lineSegmentsDistance<Point extends GlobalPoint | LocalPoint>(
distanceToLineSegment(s2[1], s1),
);
}
+
+export function lineSegmentClosestParameter<
+ Point extends GlobalPoint | LocalPoint,
+>(point: Point, line: LineSegment<Point>): number {
+ const [x, y] = point;
+ const [[x1, y1], [x2, y2]] = line;
+
+ const A = x - x1;
+ const B = y - y1;
+ const C = x2 - x1;
+ const D = y2 - y1;
+
+ const dot = A * C + B * D;
+ const len_sq = C * C + D * D;
+ let param = 0;
+ if (len_sq !== 0) {
+ param = dot / len_sq;
+ }
+
+ return Math.max(0, Math.min(1, param));
+}
diff --git a/packages/math/tests/curve.test.ts b/packages/math/tests/curve.test.ts
index 0d1f3001de..5ca0626d17 100644
--- a/packages/math/tests/curve.test.ts
+++ b/packages/math/tests/curve.test.ts
@@ -1,8 +1,9 @@
import "@excalidraw/utils/test-utils";
import {
+ bezierEquation,
curve,
- curveClosestPoint,
+ curveClosestParameter,
curveIntersectLineSegment,
curvePointDistance,
} from "../src/curve";
@@ -82,9 +83,9 @@ describe("Math curve", () => {
);
const p = pointFrom(0, 0);
- expect([curveClosestPoint(c, p)]).toCloselyEqualPoints([
- [5.965462100367372, -3.04104878946646],
- ]);
+ expect([
+ bezierEquation(c, curveClosestParameter(c, p, 1e-3)),
+ ]).toCloselyEqualPoints([[5.965462100367372, -3.04104878946646]]);
});
});