Compare commits

..

10 Commits

Author SHA1 Message Date
Mark Tolmacs a7a3f9d82b Merge branch 'master' into mtolmacs/fix/grid-binding
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-06-04 15:54:48 +00:00
Mark Tolmacs 895c2b23c7 fix: Elbow midpoint
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-19 19:46:56 +00:00
Mark Tolmacs 50099012c6 fix Suggested binding flicker
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-19 16:47:43 +00:00
Mark Tolmacs de2ad7cd3f fix: Inside binding grid respect
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-19 14:55:56 +00:00
Mark Tolmacs d7abb6a309 fix: Diamonds and ellipses
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-18 20:25:19 +00:00
Mark Tolmacs 9fd91d9a59 fix: False binding
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-18 16:29:09 +00:00
Mark Tolmacs ba087233cb fix: Grid is secondary to snap distance
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-18 12:04:23 +00:00
Mark Tolmacs 7c58d1f6f4 chore: Remove more non-needed grid snapping
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-17 20:28:29 +00:00
Mark Tolmacs d9ab298526 fix: Remove duplicated grid snapping
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-17 20:21:45 +00:00
Mark Tolmacs 7b2496bfd7 fix: Dragged arrow endpoint ignore grid and angle locks
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-03-17 19:59:33 +00:00
15 changed files with 339 additions and 433 deletions
+5 -4
View File
@@ -1,4 +1,5 @@
import {
pointFrom,
pointFromPair,
type GlobalPoint,
type LocalPoint,
@@ -69,12 +70,12 @@ export const getGridPoint = (
x: number,
y: number,
gridSize: NullableGridSize,
): [number, number] => {
): GlobalPoint => {
if (gridSize) {
return [
return pointFrom<GlobalPoint>(
Math.round(x / gridSize) * gridSize,
Math.round(y / gridSize) * gridSize,
];
);
}
return [x, y];
return pointFrom<GlobalPoint>(x, y);
};
@@ -1822,7 +1822,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"versionNonce": Any<Number>,
"verticalAlign": "middle",
"width": 120,
"x": 187.7545,
"x": 187.75450000000004,
"y": 44.5,
}
`;
+126 -6
View File
@@ -1,6 +1,7 @@
import {
arrayToMap,
getFeatureFlag,
getGridPoint,
invariant,
isTransparent,
} from "@excalidraw/common";
@@ -22,7 +23,7 @@ import {
} from "@excalidraw/math";
import type { LineSegment, LocalPoint, Radians } from "@excalidraw/math";
import type { AppState } from "@excalidraw/excalidraw/types";
import type { AppState, NullableGridSize } from "@excalidraw/excalidraw/types";
import type { MapEntry, Mutable } from "@excalidraw/common/utility-types";
import type { Bounds } from "@excalidraw/common";
@@ -154,6 +155,7 @@ export const bindOrUnbindBindingElement = (
altKey?: boolean;
angleLocked?: boolean;
initialBinding?: boolean;
gridSize?: NullableGridSize;
},
) => {
const { start, end } = getBindingStrategyForDraggingBindingElementEndpoints(
@@ -170,12 +172,16 @@ export const bindOrUnbindBindingElement = (
},
);
const isMidpointSnappingEnabled =
appState.isMidpointSnappingEnabled && !appState.gridModeEnabled;
bindOrUnbindBindingElementEdge(
arrow,
start,
"start",
scene,
appState.isBindingEnabled,
isMidpointSnappingEnabled,
);
bindOrUnbindBindingElementEdge(
arrow,
@@ -183,6 +189,7 @@ export const bindOrUnbindBindingElement = (
"end",
scene,
appState.isBindingEnabled,
isMidpointSnappingEnabled,
);
if (start.focusPoint || end.focusPoint) {
// If the strategy dictates a focus point override, then
@@ -227,6 +234,7 @@ const bindOrUnbindBindingElementEdge = (
startOrEnd: "start" | "end",
scene: Scene,
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
): void => {
if (mode === null) {
// null means break the binding
@@ -240,6 +248,7 @@ const bindOrUnbindBindingElementEdge = (
scene,
focusPoint,
shouldSnapToOutline,
isMidpointSnappingEnabled,
);
}
};
@@ -593,6 +602,7 @@ export const getBindingStrategyForDraggingBindingElementEndpoints = (
finalize?: boolean;
initialBinding?: boolean;
zoom?: AppState["zoom"];
gridSize?: NullableGridSize;
},
): { start: BindingStrategy; end: BindingStrategy } => {
if (getFeatureFlag("COMPLEX_BINDINGS")) {
@@ -633,6 +643,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
finalize?: boolean;
initialBinding?: boolean;
zoom?: AppState["zoom"];
gridSize?: NullableGridSize;
},
): { start: BindingStrategy; end: BindingStrategy } => {
const startIdx = 0;
@@ -695,7 +706,9 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
elementsMap,
);
const hit = getHoveredElementForBinding(
globalPoint,
opts?.angleLocked || appState.gridModeEnabled
? pointFrom<GlobalPoint>(scenePointerX, scenePointerY)
: globalPoint,
elements,
elementsMap,
maxBindingDistance_simple(appState.zoom),
@@ -747,7 +760,11 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
? globalPoint
: // NOTE: Can only affect the start point because new arrows always drag the end point
opts?.newArrow
? appState.selectedLinearElement!.initialState.origin!
? getGridPoint(
appState.selectedLinearElement!.initialState.origin![0],
appState.selectedLinearElement!.initialState.origin![1],
opts.gridSize as NullableGridSize,
)
: LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
0,
@@ -806,12 +823,27 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
focusPoint:
projectFixedPointOntoDiagonal(
arrow,
globalPoint,
opts?.angleLocked || appState.gridModeEnabled
? snapBoundPointToGrid(
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
hit,
elementsMap,
appState.gridSize as NullableGridSize,
arrow,
LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
startDragged ? 1 : -2,
elementsMap,
),
)
: globalPoint,
hit,
startDragged ? "start" : "end",
elementsMap,
appState.zoom,
appState.isMidpointSnappingEnabled,
appState.isMidpointSnappingEnabled &&
!opts?.angleLocked &&
!appState.gridModeEnabled,
) || globalPoint,
}
: { mode: null };
@@ -856,7 +888,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
startDragged ? "end" : "start",
elementsMap,
appState.zoom,
appState.isMidpointSnappingEnabled,
false,
) || otherEndpoint,
}
: { mode: undefined }
@@ -1021,6 +1053,7 @@ export const bindBindingElement = (
scene: Scene,
focusPoint?: GlobalPoint,
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
): void => {
const elementsMap = scene.getNonDeletedElementsMap();
@@ -1036,6 +1069,7 @@ export const bindBindingElement = (
startOrEnd,
elementsMap,
shouldSnapToOutline,
isMidpointSnappingEnabled,
),
};
} else {
@@ -1740,6 +1774,92 @@ const extractBinding = (
};
};
/**
* Snaps a bound arrow endpoint to the grid on the axis parallel to the
* bindable element's side, while preserving the binding gap distance on the
* perpendicular axis. In other words, the grid axis closest to the side's
* perpendicular (normal) is used as the snap axis and the other axis is kept at
* the binding gap distance.
*/
const snapBoundPointToGrid = (
outlinePoint: GlobalPoint,
bindableElement: ExcalidrawBindableElement,
elementsMap: ElementsMap,
gridSize: NullableGridSize,
arrowElement: ExcalidrawArrowElement,
adjacentPoint?: GlobalPoint,
): GlobalPoint => {
if (!gridSize) {
return outlinePoint;
}
const aabb = aabbForElement(bindableElement, elementsMap);
// For ellipses and diamonds use the arrow's incoming direction instead of
// the position-based heading, which can give the wrong axis when the
// outline point is near a cardinal zone or an angled diamond face.
const heading =
adjacentPoint &&
(bindableElement.type === "ellipse" || bindableElement.type === "diamond")
? vectorToHeading(vectorFromPoint(adjacentPoint, outlinePoint))
: headingForPointFromElement(bindableElement, aabb, outlinePoint);
const normalLocal = pointFrom<GlobalPoint>(heading[0], heading[1]);
const normalGlobal = pointRotateRads(
normalLocal,
pointFrom<GlobalPoint>(0, 0),
bindableElement.angle,
);
const bindingGap = getBindingGap(bindableElement, arrowElement);
const extent =
Math.max(bindableElement.width, bindableElement.height) + bindingGap * 2;
const center = getCenterForBounds(aabb);
const absNX = Math.abs(normalGlobal[0]);
const absNY = Math.abs(normalGlobal[1]);
if (absNX >= absNY) {
// Global X is closest to the perpendicular so snap Y, intersect horizontal line
const [, snappedY] = getGridPoint(
outlinePoint[0],
outlinePoint[1],
gridSize,
);
const intersector = lineSegment<GlobalPoint>(
pointFrom<GlobalPoint>(center[0] - extent, snappedY),
pointFrom<GlobalPoint>(center[0] + extent, snappedY),
);
const intersection = intersectElementWithLineSegment(
bindableElement,
elementsMap,
intersector,
bindingGap,
).sort(
(a, b) =>
pointDistanceSq(a, outlinePoint) - pointDistanceSq(b, outlinePoint),
)[0];
return intersection ?? pointFrom<GlobalPoint>(outlinePoint[0], snappedY);
}
// Global Y is closest to the perpendicular so snap X, intersect vertical line
const [snappedX] = getGridPoint(outlinePoint[0], outlinePoint[1], gridSize);
const intersector = lineSegment<GlobalPoint>(
pointFrom<GlobalPoint>(snappedX, center[1] - extent),
pointFrom<GlobalPoint>(snappedX, center[1] + extent),
);
const intersection = intersectElementWithLineSegment(
bindableElement,
elementsMap,
intersector,
bindingGap,
).sort(
(a, b) =>
pointDistanceSq(a, outlinePoint) - pointDistanceSq(b, outlinePoint),
)[0];
return intersection ?? pointFrom<GlobalPoint>(snappedX, outlinePoint[1]);
};
const elementArea = (element: ExcalidrawBindableElement) =>
element.width * element.height;
+43 -37
View File
@@ -790,41 +790,27 @@ export const getArrowheadPoints = (
p0 = pointFrom(prevOp.data[4], prevOp.data[5]);
}
// We know the last point of the arrow (or the first, if start arrowhead).
// B(t) = p0 * (1-t)^3 + 3p1 * t * (1-t)^2 + 3p2 * t^2 * (1-t) + p3 * t^3
const equation = (t: number, idx: number) =>
Math.pow(1 - t, 3) * p3[idx] +
3 * t * Math.pow(1 - t, 2) * p2[idx] +
3 * Math.pow(t, 2) * (1 - t) * p1[idx] +
p0[idx] * Math.pow(t, 3);
// Ee know the last point of the arrow (or the first, if start arrowhead).
const [x2, y2] = position === "start" ? p0 : p3;
// Use the analytic tangent at the Bézier endpoint for a precise arrowhead
// direction. For a cubic Bézier B(t) with control points p0p3:
// B'(1): (p3 p2) tangent at the end
// B'(0): (p1 p0) for start arrowhead, arrow points away: (p0 p1)
let dx: number;
let dy: number;
if (position === "end") {
dx = p3[0] - p2[0];
dy = p3[1] - p2[1];
if (Math.hypot(dx, dy) < 1e-6) {
dx = p3[0] - p1[0];
dy = p3[1] - p1[1];
}
if (Math.hypot(dx, dy) < 1e-6) {
dx = p3[0] - p0[0];
dy = p3[1] - p0[1];
}
} else {
dx = p0[0] - p1[0];
dy = p0[1] - p1[1];
if (Math.hypot(dx, dy) < 1e-6) {
dx = p0[0] - p2[0];
dy = p0[1] - p2[1];
}
if (Math.hypot(dx, dy) < 1e-6) {
dx = p0[0] - p3[0];
dy = p0[1] - p3[1];
}
}
const distance = Math.hypot(dx, dy);
const nx = dx / distance;
const ny = dy / distance;
// By using cubic bezier equation (B(t)) and the given parameters,
// we calculate a point that is closer to the last point.
// The value 0.3 is chosen arbitrarily and it works best for all
// the tested cases.
const [x1, y1] = [equation(0.3, 0), equation(0.3, 1)];
// Find the normalized direction vector based on the
// previously calculated points.
const distance = Math.hypot(x2 - x1, y2 - y1);
const nx = (x2 - x1) / distance;
const ny = (y2 - y1) / distance;
const size = getArrowheadSize(arrowhead);
@@ -894,10 +880,30 @@ export const getArrowheadPoints = (
);
if (arrowhead === "diamond" || arrowhead === "diamond_outline") {
// point opposite to the arrowhead point, just mirrored across the (tx, ty)
// point
const ox = tx - nx * minSize * 2;
const oy = ty - ny * minSize * 2;
// point opposite to the arrowhead point
let ox;
let oy;
if (position === "start") {
const [px, py] = element.points.length > 1 ? element.points[1] : [0, 0];
[ox, oy] = pointRotateRads(
pointFrom(tx + minSize * 2, ty),
pointFrom(tx, ty),
Math.atan2(py - ty, px - tx) as Radians,
);
} else {
const [px, py] =
element.points.length > 1
? element.points[element.points.length - 2]
: [0, 0];
[ox, oy] = pointRotateRads(
pointFrom(tx - minSize * 2, ty),
pointFrom(tx, ty),
Math.atan2(ty - py, tx - px) as Radians,
);
}
return [tx, ty, x3, y3, ox, oy, x4, y4];
}
+18 -15
View File
@@ -359,6 +359,7 @@ export class LinearElementEditor {
linearElementEditor,
);
const angleLocked = shouldRotateWithDiscreteAngle(event);
LinearElementEditor.movePoints(
element,
app.scene,
@@ -370,7 +371,10 @@ export class LinearElementEditor {
},
{
isBindingEnabled: app.state.isBindingEnabled,
isMidpointSnappingEnabled: app.state.isMidpointSnappingEnabled,
isMidpointSnappingEnabled:
app.state.isMidpointSnappingEnabled &&
!angleLocked &&
!app.state.gridModeEnabled,
},
);
// Set the suggested binding from the updates if available
@@ -427,7 +431,9 @@ export class LinearElementEditor {
"start",
elementsMap,
app.state.zoom,
app.state.isMidpointSnappingEnabled,
app.state.isMidpointSnappingEnabled &&
!angleLocked &&
!app.state.gridModeEnabled,
)
: linearElementEditor.initialState.altFocusPoint,
},
@@ -554,6 +560,8 @@ export class LinearElementEditor {
linearElementEditor,
);
const angleLocked =
shouldRotateWithDiscreteAngle(event) && singlePointDragged;
LinearElementEditor.movePoints(
element,
app.scene,
@@ -565,7 +573,10 @@ export class LinearElementEditor {
},
{
isBindingEnabled: app.state.isBindingEnabled,
isMidpointSnappingEnabled: app.state.isMidpointSnappingEnabled,
isMidpointSnappingEnabled:
app.state.isMidpointSnappingEnabled &&
!angleLocked &&
!app.state.gridModeEnabled,
},
);
@@ -661,7 +672,9 @@ export class LinearElementEditor {
"start",
elementsMap,
app.state.zoom,
app.state.isMidpointSnappingEnabled,
app.state.isMidpointSnappingEnabled &&
!angleLocked &&
!app.state.gridModeEnabled,
)
: linearElementEditor.initialState.altFocusPoint,
},
@@ -790,20 +803,9 @@ export class LinearElementEditor {
elementsMap,
);
const [lines, segCurves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
const segmentCount = lines.length + segCurves.length;
let index = 0;
const midpoints: (GlobalPoint | null)[] = [];
while (index < points.length - 1) {
if (segmentCount > 0 && index >= segmentCount) {
midpoints.push(null);
index++;
continue;
}
if (
LinearElementEditor.isSegmentTooShort(
element,
@@ -2187,6 +2189,7 @@ const pointDraggingUpdates = (
newArrow: !!app.state.newElement,
angleLocked,
altKey,
gridSize: app.getEffectiveGridSize(),
},
);
+52 -305
View File
@@ -78,18 +78,6 @@ import type {
import type { Drawable, Options } from "roughjs/bin/core";
import type { Point as RoughPoint } from "roughjs/bin/geometry";
// Controls how handle distance scales with chord length.
// At 1.0 handles are exactly h/3 (standard Hermite). Values below 1 make
// short segments curvier and long segments more taut (sub-linear scaling).
const CP_CHORD_POWER = 1;
// At curved knots the C2 spline tangent can be tilted away from the
// bisector direction, making one side of the knot tight and the other taut.
// This factor [0, 1] controls how far the tangent direction is pulled toward
// the bisector (the chord-bisector normal) linearly with turn sharpness.
// 0 = pure C2 spline; 1 = tangent fully aligned with the bisector.
const CP_ANGLE_CORRECTION = 1;
export class ShapeCache {
private static rg = new RoughGenerator();
private static cache = new WeakMap<
@@ -637,144 +625,60 @@ export const generateLinearCollisionShape = (
});
}
// Generate collision ops using the same bisector-based cubic Bézier
// algorithm as generateRoundedSimpleArrowShape so hit-testing matches rendering.
const rotateLocal = (lx: number, ly: number): LocalPoint => {
const g = pointRotateRads<GlobalPoint>(
pointFrom<GlobalPoint>(element.x + lx, element.y + ly),
center,
element.angle,
);
return pointFrom<LocalPoint>(g[0] - element.x, g[1] - element.y);
};
return generator
.curve(points as unknown as RoughPoint[], options)
.sets[0].ops.slice(0, element.points.length)
.map((op, i) => {
if (i === 0) {
const p = pointRotateRads<GlobalPoint>(
pointFrom<GlobalPoint>(
element.x + op.data[0],
element.y + op.data[1],
),
center,
element.angle,
);
const collisionOps: Array<{
op: string;
data: number[] | LocalPoint;
}> = [];
collisionOps.push({
op: "move",
data: rotateLocal(points[0][0], points[0][1]),
});
if (points.length === 2) {
collisionOps.push({
op: "lineTo",
data: rotateLocal(points[1][0], points[1][1]),
});
} else {
// Chord-length C2 spline. Mirrors generateRoundedSimpleArrowShape
// exactly so hit-testing matches rendering.
const n = points.length - 1;
const h = new Float64Array(n);
for (let i = 0; i < n; i++) {
h[i] = Math.max(
1e-10,
Math.hypot(
points[i + 1][0] - points[i][0],
points[i + 1][1] - points[i][1],
),
);
}
const mx = new Float64Array(n + 1);
const my = new Float64Array(n + 1);
const diag = new Float64Array(n + 1);
const rhsX = new Float64Array(n + 1);
const rhsY = new Float64Array(n + 1);
diag[0] = 2;
rhsX[0] = (3 * (points[1][0] - points[0][0])) / h[0];
rhsY[0] = (3 * (points[1][1] - points[0][1])) / h[0];
for (let i = 1; i < n; i++) {
diag[i] = 2 * (h[i - 1] + h[i]);
rhsX[i] =
3 *
((h[i] * (points[i][0] - points[i - 1][0])) / h[i - 1] +
(h[i - 1] * (points[i + 1][0] - points[i][0])) / h[i]);
rhsY[i] =
3 *
((h[i] * (points[i][1] - points[i - 1][1])) / h[i - 1] +
(h[i - 1] * (points[i + 1][1] - points[i][1])) / h[i]);
}
diag[n] = 2;
rhsX[n] = (3 * (points[n][0] - points[n - 1][0])) / h[n - 1];
rhsY[n] = (3 * (points[n][1] - points[n - 1][1])) / h[n - 1];
for (let i = 1; i <= n; i++) {
const sub = i < n ? h[i] : 1;
const supPrev = i === 1 ? 1 : h[i - 2];
const w = sub / diag[i - 1];
diag[i] -= w * supPrev;
rhsX[i] -= w * rhsX[i - 1];
rhsY[i] -= w * rhsY[i - 1];
}
mx[n] = rhsX[n] / diag[n];
my[n] = rhsY[n] / diag[n];
for (let i = n - 1; i >= 0; i--) {
const sup = i === 0 ? 1 : h[i - 1];
mx[i] = (rhsX[i] - sup * mx[i + 1]) / diag[i];
my[i] = (rhsY[i] - sup * my[i + 1]) / diag[i];
}
// Normalised tangent directions; handle length scales sub-linearly with chord.
const mlen = new Float64Array(n + 1);
for (let i = 0; i <= n; i++) {
mlen[i] = Math.max(1e-10, Math.hypot(mx[i], my[i]));
}
// At interior knots, blend the C2 tangent direction toward the
// bisector direction by a factor proportional to turn sharpness *
// CP_ANGLE_CORRECTION
for (let k = 1; k < n; k++) {
const d1x = (points[k][0] - points[k - 1][0]) / h[k - 1];
const d1y = (points[k][1] - points[k - 1][1]) / h[k - 1];
const d2x = (points[k + 1][0] - points[k][0]) / h[k];
const d2y = (points[k + 1][1] - points[k][1]) / h[k];
const dot = d1x * d2x + d1y * d2y;
const t = ((1 - dot) / 2) * CP_ANGLE_CORRECTION;
if (t < 1e-6) {
continue;
return {
op: "move",
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
};
}
const bx = d1x + d2x;
const by = d1y + d2y;
const blen = Math.hypot(bx, by);
if (blen < 1e-10) {
continue;
}
let px = bx / blen;
let py = by / blen;
const tx = mx[k] / mlen[k];
const ty = my[k] / mlen[k];
if (tx * px + ty * py < 0) {
px = -px;
py = -py;
}
const blendX = tx + t * (px - tx);
const blendY = ty + t * (py - ty);
const blendLen = Math.max(1e-10, Math.hypot(blendX, blendY));
mx[k] = (blendX / blendLen) * mlen[k];
my[k] = (blendY / blendLen) * mlen[k];
}
for (let i = 0; i < n; i++) {
const cpDist = Math.pow(h[i], CP_CHORD_POWER) / 3;
const cp1x = points[i][0] + (mx[i] / mlen[i]) * cpDist;
const cp1y = points[i][1] + (my[i] / mlen[i]) * cpDist;
const cp2x = points[i + 1][0] - (mx[i + 1] / mlen[i + 1]) * cpDist;
const cp2y = points[i + 1][1] - (my[i + 1] / mlen[i + 1]) * cpDist;
const rcp1 = rotateLocal(cp1x, cp1y);
const rcp2 = rotateLocal(cp2x, cp2y);
const rend = rotateLocal(points[i + 1][0], points[i + 1][1]);
collisionOps.push({
return {
op: "bcurveTo",
data: [rcp1[0], rcp1[1], rcp2[0], rcp2[1], rend[0], rend[1]],
});
}
}
return collisionOps;
data: [
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[0],
element.y + op.data[1],
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[2],
element.y + op.data[3],
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[4],
element.y + op.data[5],
),
center,
element.angle,
),
]
.map((p) =>
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
)
.flat(),
};
});
}
case "freedraw": {
if (element.points.length < 2) {
@@ -1016,12 +920,7 @@ const _generateElementShape = (
];
}
} else {
shape = [
generator.path(
generateRoundedSimpleArrowShape(points),
generateRoughOptions(element, true, isDarkMode),
),
];
shape = [generator.curve(points as unknown as RoughPoint[], options)];
}
// add lines only in arrow
@@ -1105,162 +1004,10 @@ const _generateElementShape = (
}
};
const generateRoundedSimpleArrowShape = (
points: readonly LocalPoint[],
): string => {
if (points.length < 2) {
return "";
}
if (points.length === 2) {
return `M ${points[0][0]} ${points[0][1]} L ${points[1][0]} ${points[1][1]}`;
}
// Chord-length parameterised C2 natural cubic spline (Thomas's algorithm).
//
// Unknowns: tangent vectors m[0..n] at each knot (n = number of segments).
// Chord lengths h[i] = |K[i+1] K[i]| act as the parameter intervals so
// that tightly-spaced knots don't over-influence distant ones.
//
// Row 0: 2·m₀ + m₁ = 3·(K₁−K₀)/h₀
// Row i: h[i]·mᵢ₋₁ + 2·(h[i1]+h[i])·mᵢ + h[i1]·mᵢ₊₁
// = 3·(h[i]·(Kᵢ−Kᵢ₋₁)/h[i1]
// + h[i1]·(Kᵢ₊₁−Kᵢ)/h[i]) 1≤i≤n1
// Row n: mₙ₋₁ + 2·mₙ = 3·(Kₙ−Kₙ₋₁)/h[n1]
//
// Bézier control points from Hermite→Bézier identity:
// cp1ᵢ = Kᵢ + mᵢ · h[i] / 3
// cp2ᵢ = Kᵢ₊₁ mᵢ₊₁ · h[i] / 3
const n = points.length - 1; // number of segments
const h = new Float64Array(n);
for (let i = 0; i < n; i++) {
h[i] = Math.max(
1e-10,
Math.hypot(
points[i + 1][0] - points[i][0],
points[i + 1][1] - points[i][1],
),
);
}
const mx = new Float64Array(n + 1);
const my = new Float64Array(n + 1);
const diag = new Float64Array(n + 1);
const rhsX = new Float64Array(n + 1);
const rhsY = new Float64Array(n + 1);
// Row 0 natural BC (zero second derivative at start)
diag[0] = 2;
rhsX[0] = (3 * (points[1][0] - points[0][0])) / h[0];
rhsY[0] = (3 * (points[1][1] - points[0][1])) / h[0];
// Interior rows
for (let i = 1; i < n; i++) {
diag[i] = 2 * (h[i - 1] + h[i]);
rhsX[i] =
3 *
((h[i] * (points[i][0] - points[i - 1][0])) / h[i - 1] +
(h[i - 1] * (points[i + 1][0] - points[i][0])) / h[i]);
rhsY[i] =
3 *
((h[i] * (points[i][1] - points[i - 1][1])) / h[i - 1] +
(h[i - 1] * (points[i + 1][1] - points[i][1])) / h[i]);
}
// Row n natural BC (zero second derivative at end)
diag[n] = 2;
rhsX[n] = (3 * (points[n][0] - points[n - 1][0])) / h[n - 1];
rhsY[n] = (3 * (points[n][1] - points[n - 1][1])) / h[n - 1];
// Forward sweep
// sub[i] = h[i] for i=1..n1, sub[n] = 1
// sup[i] = 1 for i=0, h[i1] for i=1..n1 (never modified)
for (let i = 1; i <= n; i++) {
const sub = i < n ? h[i] : 1;
const supPrev = i === 1 ? 1 : h[i - 2];
const w = sub / diag[i - 1];
diag[i] -= w * supPrev;
rhsX[i] -= w * rhsX[i - 1];
rhsY[i] -= w * rhsY[i - 1];
}
// Back substitution
mx[n] = rhsX[n] / diag[n];
my[n] = rhsY[n] / diag[n];
for (let i = n - 1; i >= 0; i--) {
const sup = i === 0 ? 1 : h[i - 1];
mx[i] = (rhsX[i] - sup * mx[i + 1]) / diag[i];
my[i] = (rhsY[i] - sup * my[i + 1]) / diag[i];
}
// Normalised tangent directions; handle length scales sub-linearly with chord.
const mlen = new Float64Array(n + 1);
for (let i = 0; i <= n; i++) {
mlen[i] = Math.max(1e-10, Math.hypot(mx[i], my[i]));
}
// At interior knots, blend the C2 tangent direction toward the
// perpendicular-to-bisector (the perfectly symmetric tangent) by a factor
// proportional to turn sharpness × CP_ANGLE_CORRECTION.
// Both cp2 (incoming) and cp1 (outgoing) at the knot share the same adjusted
// direction, so collinear (aligned) handles are preserved.
for (let k = 1; k < n; k++) {
const d1x = (points[k][0] - points[k - 1][0]) / h[k - 1];
const d1y = (points[k][1] - points[k - 1][1]) / h[k - 1];
const d2x = (points[k + 1][0] - points[k][0]) / h[k];
const d2y = (points[k + 1][1] - points[k][1]) / h[k];
const dot = d1x * d2x + d1y * d2y;
// t: 0 = straight, 1 = hairpin
const t = ((1 - dot) / 2) * CP_ANGLE_CORRECTION;
if (t < 1e-6) {
continue;
}
// Bisector of the two chord directions as the "normal" at the knot.
// Its perpendicular is the ideal symmetric tangent direction.
const bx = d1x + d2x;
const by = d1y + d2y;
const blen = Math.hypot(bx, by);
if (blen < 1e-10) {
continue; // 180° hairpin bisector undefined, skip
}
// Blend target: bisector direction (pick sign aligning with current tangent)
let px = bx / blen;
let py = by / blen;
const tx = mx[k] / mlen[k];
const ty = my[k] / mlen[k];
if (tx * px + ty * py < 0) {
px = -px;
py = -py;
}
// Linear blend of unit directions, then renormalize to preserve magnitude.
const blendX = tx + t * (px - tx);
const blendY = ty + t * (py - ty);
const blendLen = Math.max(1e-10, Math.hypot(blendX, blendY));
mx[k] = (blendX / blendLen) * mlen[k];
my[k] = (blendY / blendLen) * mlen[k];
}
const path: string[] = [`M ${points[0][0]} ${points[0][1]}`];
for (let i = 0; i < n; i++) {
const cpDist = Math.pow(h[i], CP_CHORD_POWER) / 3;
const cp1x = points[i][0] + (mx[i] / mlen[i]) * cpDist;
const cp1y = points[i][1] + (my[i] / mlen[i]) * cpDist;
const cp2x = points[i + 1][0] - (mx[i + 1] / mlen[i + 1]) * cpDist;
const cp2y = points[i + 1][1] - (my[i + 1] / mlen[i + 1]) * cpDist;
path.push(
`C ${cp1x} ${cp1y} ${cp2x} ${cp2y} ${points[i + 1][0]} ${
points[i + 1][1]
}`,
);
}
return path.join(" ");
};
const generateElbowArrowShape = (
points: readonly LocalPoint[],
radius: number,
): string => {
) => {
const subpoints = [] as [number, number][];
for (let i = 1; i < points.length - 1; i += 1) {
const prev = points[i - 1];
+4 -4
View File
@@ -135,9 +135,9 @@ describe("getElementBounds", () => {
} as ExcalidrawLinearElement;
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
expect(x1).toEqual(366.0476290709661);
expect(y1).toEqual(186.59818534770224);
expect(x2).toEqual(494.6034220048372);
expect(y2).toEqual(324.16489799221546);
expect(x1).toEqual(360.9291017525165);
expect(y1).toEqual(185.24770129343722);
expect(x2).toEqual(481.4815539037601);
expect(y2).toEqual(319.8162855827246);
});
});
+1 -1
View File
@@ -30,7 +30,7 @@ describe("check rotated elements can be hit:", () => {
] as LocalPoint[],
});
const hit = hitElementItself({
point: pointFrom<GlobalPoint>(90, -70),
point: pointFrom<GlobalPoint>(88, -68),
element: window.h.elements[0],
threshold: 10,
elementsMap: window.h.scene.getNonDeletedElementsMap(),
@@ -434,12 +434,12 @@ describe("Test Linear Elements", () => {
expect(midPointsWithRoundEdge).toMatchInlineSnapshot(`
[
[
"51.36383",
"54.86323",
"54.27552",
"46.16120",
],
[
"81.64884",
"43.04575",
"76.95494",
"44.56052",
],
]
`);
@@ -499,12 +499,12 @@ describe("Test Linear Elements", () => {
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"101.36383",
"74.86323",
"104.27552",
"66.16120",
],
[
"131.64884",
"63.04575",
"126.95494",
"64.56052",
],
]
`);
@@ -707,8 +707,14 @@ describe("Test Linear Elements", () => {
// This is the expected midpoint for line with round edge
// hence hardcoding it so if later some bug is introduced
// this will fail and we can fix it
const firstSegmentMidpoint = pointFrom<GlobalPoint>(47.30521, 57.2734);
const lastSegmentMidpoint = pointFrom<GlobalPoint>(83.70877, 40.46424);
const firstSegmentMidpoint = pointFrom<GlobalPoint>(
55.9697848965255,
47.442326230998205,
);
const lastSegmentMidpoint = pointFrom<GlobalPoint>(
76.08587175006699,
43.294165939653226,
);
let line: ExcalidrawLinearElement;
beforeEach(() => {
@@ -753,16 +759,16 @@ describe("Test Linear Elements", () => {
0,
],
[
"77.30521",
"87.27340",
"85.96978",
"77.44233",
],
[
70,
50,
],
[
"113.70877",
"70.46424",
"106.08587",
"73.29417",
],
[
40,
@@ -809,12 +815,12 @@ describe("Test Linear Elements", () => {
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"22.32088",
"37.43003",
"29.28349",
"20.91105",
],
[
"81.55727",
"43.21091",
"78.86048",
"46.12277",
],
]
`);
@@ -898,12 +904,12 @@ describe("Test Linear Elements", () => {
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"51.36383",
"54.86323",
"54.27552",
"46.16120",
],
[
"81.64884",
"43.04575",
"76.95494",
"44.56052",
],
]
`);
@@ -1065,8 +1071,8 @@ describe("Test Linear Elements", () => {
);
expect(position).toMatchInlineSnapshot(`
{
"x": "86.53100",
"y": "72.83556",
"x": "86.17305",
"y": "76.11251",
}
`);
});
@@ -1185,8 +1191,8 @@ describe("Test Linear Elements", () => {
20,
105,
80,
"56.68277",
"47.27188",
"55.45894",
45,
]
`);
@@ -1196,7 +1202,7 @@ describe("Test Linear Elements", () => {
.toMatchInlineSnapshot(`
{
"height": 130,
"width": "368.53316",
"width": "366.11716",
}
`);
@@ -1208,7 +1214,7 @@ describe("Test Linear Elements", () => {
),
).toMatchInlineSnapshot(`
{
"x": "273.53316",
"x": "271.11716",
"y": 45,
}
`);
@@ -1225,10 +1231,10 @@ describe("Test Linear Elements", () => {
[
20,
35,
"503.53316",
"119.02540",
"204.47758",
"77.01270",
"501.11716",
95,
"205.45894",
"52.50000",
]
`);
});
+20 -12
View File
@@ -27,7 +27,7 @@ import { isInvisiblySmallElement } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import type { GlobalPoint, LocalPoint } from "@excalidraw/math";
import type { LocalPoint } from "@excalidraw/math";
import type {
ExcalidrawElement,
ExcalidrawLinearElement,
@@ -93,32 +93,40 @@ export const actionFinalize = register<FormData>({
? [element.points.length - 1] // New arrow creation
: appState.selectedLinearElement.selectedPointsIndices;
const angleLocked = shouldRotateWithDiscreteAngle(event);
const effectiveGridSize = event[KEYS.CTRL_OR_CMD]
? null
: app.getEffectiveGridSize();
const draggedPoints: PointsPositionUpdates =
selectedPointsIndices.reduce((map, index) => {
map.set(index, {
point: LinearElementEditor.pointFromAbsoluteCoords(
element,
pointFrom<GlobalPoint>(
sceneCoords.x - linearElementEditor.pointerOffset.x,
sceneCoords.y - linearElementEditor.pointerOffset.y,
),
elementsMap,
),
point: angleLocked
? element.points[index]
: LinearElementEditor.createPointAt(
element,
elementsMap,
sceneCoords.x - linearElementEditor.pointerOffset.x,
sceneCoords.y - linearElementEditor.pointerOffset.y,
effectiveGridSize,
),
});
return map;
}, new Map()) ?? new Map();
bindOrUnbindBindingElement(
element,
draggedPoints,
sceneCoords.x - linearElementEditor.pointerOffset.x,
sceneCoords.y - linearElementEditor.pointerOffset.y,
sceneCoords.x,
sceneCoords.y,
scene,
appState,
{
newArrow,
altKey: event.altKey,
angleLocked: shouldRotateWithDiscreteAngle(event),
angleLocked,
gridSize: app.getEffectiveGridSize(),
},
);
} else if (isLineElement(element)) {
+5 -3
View File
@@ -7263,14 +7263,16 @@ class App extends React.Component<AppProps, AppState> {
return;
}
if (this.state.activeTool.type === "arrow") {
// Set suggested binding if we're hovering with an arrow tool
// and not dragging out a new element
if (this.state.activeTool.type === "arrow" && !this.state.newElement) {
const scenePointer = pointFrom<GlobalPoint>(scenePointerX, scenePointerY);
const hit = getHoveredElementForBinding(
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
scenePointer,
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
maxBindingDistance_simple(this.state.zoom),
);
const scenePointer = pointFrom<GlobalPoint>(scenePointerX, scenePointerY);
const elementsMap = this.scene.getNonDeletedElementsMap();
if (hit && !isPointInElement(scenePointer, hit, elementsMap)) {
this.setState({
@@ -253,6 +253,7 @@ const getRelevantAppStateProps = (
newElement: appState.newElement,
isBindingEnabled: appState.isBindingEnabled,
isMidpointSnappingEnabled: appState.isMidpointSnappingEnabled,
gridModeEnabled: appState.gridModeEnabled,
suggestedBinding: appState.suggestedBinding,
isRotating: appState.isRotating,
elementsToHighlight: appState.elementsToHighlight,
@@ -17,6 +17,7 @@ import {
FRAME_STYLE,
getFeatureFlag,
invariant,
shouldRotateWithDiscreteAngle,
THEME,
} from "@excalidraw/common";
@@ -229,6 +230,7 @@ const renderBindingHighlightForBindableElement_simple = (
elementsMap: ElementsMap,
appState: InteractiveCanvasAppState,
pointerCoords: GlobalPoint | null,
angleLocked = false,
) => {
const enclosingFrame =
suggestedBinding.element.frameId &&
@@ -415,6 +417,8 @@ const renderBindingHighlightForBindableElement_simple = (
if (
appState.isMidpointSnappingEnabled &&
!appState.gridModeEnabled &&
!angleLocked &&
(isFrameLikeElement(suggestedBinding.element) ||
isBindableElement(suggestedBinding.element))
) {
@@ -807,7 +811,12 @@ const renderBindingHighlightForBindableElement_complex = (
context.restore();
if (appState.isMidpointSnappingEnabled) {
if (
appState.isMidpointSnappingEnabled &&
!appState.gridModeEnabled &&
(!app.lastPointerMoveEvent ||
!shouldRotateWithDiscreteAngle(app.lastPointerMoveEvent))
) {
// Draw midpoint indicators
context.save();
context.translate(
@@ -920,12 +929,16 @@ const renderBindingHighlightForBindableElement = (
app.lastPointerMoveCoords.y,
)
: null;
const angleLocked =
!!app.lastPointerMoveEvent &&
shouldRotateWithDiscreteAngle(app.lastPointerMoveEvent);
renderBindingHighlightForBindableElement_simple(
context,
suggestedBinding,
allElementsMap,
appState,
pointerCoords,
angleLocked,
);
context.restore();
};
+2
View File
@@ -224,6 +224,7 @@ export type InteractiveCanvasAppState = Readonly<
newElement: AppState["newElement"];
isBindingEnabled: AppState["isBindingEnabled"];
isMidpointSnappingEnabled: AppState["isMidpointSnappingEnabled"];
gridModeEnabled: AppState["gridModeEnabled"];
suggestedBinding: AppState["suggestedBinding"];
isRotating: AppState["isRotating"];
elementsToHighlight: AppState["elementsToHighlight"];
@@ -845,6 +846,7 @@ export type AppClassProperties = {
onStateChange: App["onStateChange"];
lastPointerMoveCoords: App["lastPointerMoveCoords"];
lastPointerMoveEvent: App["lastPointerMoveEvent"];
bindModeHandler: App["bindModeHandler"];
setAppState: App["setAppState"];
+9 -12
View File
@@ -196,7 +196,7 @@ export const getEllipseShape = <Point extends GlobalPoint | LocalPoint>(
export const getCurvePathOps = (shape: Drawable): Op[] => {
// NOTE (mtolmacs): Temporary fix for extremely large elements
if (!shape || shape.sets.length === 0) {
if (!shape) {
return [];
}
@@ -316,29 +316,26 @@ export const getClosedCurveShape = <Point extends GlobalPoint | LocalPoint>(
};
}
// Prefer the fillPath set
const fillPathSet = roughShape.sets.find((s) => s.type === "fillPath");
const ops = fillPathSet ? fillPathSet.ops : getCurvePathOps(roughShape);
const ops = getCurvePathOps(roughShape);
const points: Point[] = [];
let odd = false;
for (const operation of ops) {
if (operation.op === "move") {
if (fillPathSet) {
// fillPath is always a single run, no odd/even skipping needed
odd = !odd;
if (odd) {
points.push(pointFrom(operation.data[0], operation.data[1]));
} else {
odd = !odd;
if (odd) {
points.push(pointFrom(operation.data[0], operation.data[1]));
}
}
} else if (operation.op === "bcurveTo") {
if (fillPathSet || odd) {
if (odd) {
points.push(pointFrom(operation.data[0], operation.data[1]));
points.push(pointFrom(operation.data[2], operation.data[3]));
points.push(pointFrom(operation.data[4], operation.data[5]));
}
} else if (operation.op === "lineTo") {
if (odd) {
points.push(pointFrom(operation.data[0], operation.data[1]));
}
}
}