Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

feat(editor): fit arrowheads to short last segments & fill them along their outline (#12439)

David Luzarb7de45e88111
diff --git a/packages/element/src/bounds.ts b/packages/element/src/bounds.ts
index 9c1af8c702..566035e12d 100644
--- a/packages/element/src/bounds.ts
+++ b/packages/element/src/bounds.ts
@@ -7,11 +7,15 @@ import {
sizeOf,
} from "@excalidraw/common";
import {
+ clamp,
degreesToRadians,
lineSegment,
pointFrom,
+ pointDistance,
pointFromArray,
pointRotateRads,
+ vectorDot,
+ vectorFromPoint,
} from "@excalidraw/math";
import { getCurvePathOps } from "@excalidraw/utils/shape";
import { pointsOnBezierCurves } from "points-on-curve";
@@ -27,13 +31,14 @@ import type {
import type { AppState } from "@excalidraw/excalidraw/types";
import type { Mutable } from "@excalidraw/common/utility-types";
-import { generateRoughOptions } from "./shape";
+import { ELBOW_ARROW_CORNER_RADIUS, generateRoughOptions } from "./shape";
import { ShapeCache } from "./shape";
import { LinearElementEditor } from "./linearElementEditor";
import { getBoundTextElement, getContainerElement } from "./textElement";
import {
isArrowElement,
isBoundToContainer,
+ isElbowArrow,
isFrameLikeElement,
isFreeDrawElement,
isLinearElement,
@@ -53,6 +58,7 @@ import type { Drawable, Op } from "roughjs/bin/core";
import type { Point as RoughPoint } from "roughjs/bin/geometry";
import type {
Arrowhead,
+ CardinalityArrowhead,
ElementsMap,
ElementsMapOrArray,
ExcalidrawElement,
@@ -710,6 +716,13 @@ const getFreeDrawElementAbsoluteCoords = (
const CARDINALITY_MARKER_SIZE = 20;
const CROWFOOT_ARROWHEAD_SIZE = 15;
+// layout of the parts of composite cardinality markers, in multiples of
+// the part's size (negative offsets move a part toward the tip)
+export const CARDINALITY_ONE_OR_MANY_BAR_OFFSET = -0.25;
+export const CARDINALITY_INNER_BAR_OFFSET = -0.5;
+export const CARDINALITY_ZERO_CIRCLE_OFFSET = 1.5;
+export const CARDINALITY_ZERO_CIRCLE_SCALE = 0.8;
+
/** @returns number in pixels */
export const getArrowheadSize = (arrowhead: Arrowhead): number => {
switch (arrowhead) {
@@ -731,18 +744,251 @@ export const getArrowheadSize = (arrowhead: Arrowhead): number => {
}
};
+const ARROW_ARROWHEAD_ANGLE = 20;
+// scaled down `arrow` arrowheads open up to this angle so that they don't
+// collapse into the line, reaching it at ARROW_ARROWHEAD_WIDEST_SIZE
+const ARROW_ARROWHEAD_WIDEST_ANGLE = 30;
+const ARROW_ARROWHEAD_WIDEST_SIZE = 10;
+
/** @returns number in degrees */
-export const getArrowheadAngle = (arrowhead: Arrowhead): Degrees => {
+export const getArrowheadAngle = (
+ arrowhead: Arrowhead,
+ /** size the arrowhead is drawn at, if scaled down */
+ size = getArrowheadSize(arrowhead),
+): Degrees => {
switch (arrowhead) {
case "bar":
return 90 as Degrees;
- case "arrow":
- return 20 as Degrees;
+ case "arrow": {
+ const fullSize = getArrowheadSize(arrowhead);
+ const shrinkage = clamp(
+ (fullSize - size) / (fullSize - ARROW_ARROWHEAD_WIDEST_SIZE),
+ 0,
+ 1,
+ );
+ return (ARROW_ARROWHEAD_ANGLE +
+ (ARROW_ARROWHEAD_WIDEST_ANGLE - ARROW_ARROWHEAD_ANGLE) *
+ shrinkage) as Degrees;
+ }
default:
return 25 as Degrees;
}
};
+/**
+ * The arrow's last segment at the arrowhead's end, and how much the arrow
+ * turns into it from the previous segment (0 if it continues straight).
+ *
+ * @returns null if there's no previous segment
+ */
+const getArrowheadCorner = (
+ element: ExcalidrawLinearElement,
+ position: "start" | "end",
+) => {
+ const { points } = element;
+ const [tip, corner, prev] =
+ position === "end"
+ ? [points.at(-1), points.at(-2), points.at(-3)]
+ : [points[0], points[1], points[2]];
+
+ if (!tip || !corner || !prev) {
+ return null;
+ }
+
+ let length = pointDistance(tip, corner);
+ let prevLength = pointDistance(corner, prev);
+
+ if (length === 0 || prevLength === 0) {
+ return null;
+ }
+
+ // elbow arrows round their corners off, the arrow effectively turns
+ // halfway into the rounding
+ if (isElbowArrow(element)) {
+ const rounding =
+ Math.min(ELBOW_ARROW_CORNER_RADIUS, length / 2, prevLength / 2) / 2;
+ length -= rounding;
+ prevLength -= rounding;
+ }
+
+ const turn = Math.acos(
+ clamp(
+ vectorDot(vectorFromPoint(tip, corner), vectorFromPoint(corner, prev)) /
+ (length * prevLength),
+ -1,
+ 1,
+ ),
+ );
+
+ return { length, prevLength, turn };
+};
+
+type ArrowheadCorner = NonNullable<ReturnType<typeof getArrowheadCorner>>;
+
+/**
+ * Size up to which an arrowhead extending past the last segment's start
+ * keeps its sides (at `sideAngle` to the last segment) `clearance` away
+ * from the previous segment.
+ */
+const getSidesClearSize = (
+ { length, turn }: ArrowheadCorner,
+ sideAngle: Degrees,
+ clearance: number,
+) => {
+ const angle = degreesToRadians(sideAngle);
+
+ // the previous segment stays between the sides
+ if (turn <= angle) {
+ return Infinity;
+ }
+
+ // in the tip-corner-side-end triangle, the side end is
+ // `length * sin(turn)` away from the previous segment at size 0,
+ // and every unit of size takes it `sin(turn - angle)` closer
+ return (length * Math.sin(turn) - clearance) / Math.sin(turn - angle);
+};
+
+const isCardinalityArrowhead = (
+ arrowhead: Arrowhead,
+): arrowhead is CardinalityArrowhead => arrowhead.startsWith("cardinality_");
+
+/**
+ * Scale (at most 1) at which all parts of a cardinality marker fit on the
+ * last segment: the crow's foot reaches back at most to the corner, the
+ * circle stays clear of it, and the bars' ends stay closer to the arrow than
+ * to the previous segment.
+ */
+const getCardinalityMarkerScale = (
+ marker: CardinalityArrowhead,
+ { length, turn }: ArrowheadCorner,
+ strokeWidth: number,
+) => {
+ // scales at which each part reaches back from the tip at most to the corner
+ const bar = (offset: number) => {
+ const angle = degreesToRadians(getArrowheadAngle("cardinality_one"));
+ return (
+ length /
+ (getArrowheadSize("cardinality_one") *
+ (offset +
+ Math.cos(angle) +
+ // the bar's ends stay closer to the arrow than to the previous
+ // segment, which (other than when going straight) is at an angle
+ Math.sin(angle) * Math.tan(turn / 2)))
+ );
+ };
+ const crowsFoot = () => length / getArrowheadSize("cardinality_many");
+ // see generateArrowheadOutlineCircle() for the diameter
+ const circle = () =>
+ (length -
+ ((strokeWidth - 2) * CARDINALITY_ZERO_CIRCLE_SCALE) / 2 -
+ strokeWidth) /
+ (getArrowheadSize("circle_outline") *
+ (CARDINALITY_ZERO_CIRCLE_OFFSET + CARDINALITY_ZERO_CIRCLE_SCALE / 2));
+
+ switch (marker) {
+ case "cardinality_one":
+ return Math.min(1, bar(0));
+ case "cardinality_many":
+ return Math.min(1, crowsFoot());
+ case "cardinality_one_or_many":
+ return Math.min(1, crowsFoot(), bar(CARDINALITY_ONE_OR_MANY_BAR_OFFSET));
+ case "cardinality_exactly_one":
+ return Math.min(1, bar(CARDINALITY_INNER_BAR_OFFSET), bar(0));
+ case "cardinality_zero_or_one":
+ return Math.min(1, circle(), bar(CARDINALITY_INNER_BAR_OFFSET));
+ case "cardinality_zero_or_many":
+ return Math.min(1, crowsFoot(), circle());
+ }
+};
+
+/**
+ * Size an arrowhead may grow to when the last segment of an arrow is too
+ * short to fit it, by using up the whole segment or extending past its start.
+ *
+ * @param arrowhead the arrowhead, or the part of a composite marker, to size
+ * @returns 0 if the arrowhead shouldn't grow
+ */
+const getArrowheadSizeBeyondLastSegment = (
+ element: ExcalidrawLinearElement,
+ position: "start" | "end",
+ arrowhead: Arrowhead,
+): number => {
+ const corner = getArrowheadCorner(element, position);
+
+ if (!corner) {
+ return 0;
+ }
+
+ const { length, prevLength, turn } = corner;
+ // don't take up more than half of the last two segments
+ const maxSize = (length + prevLength) / 2;
+ // the end of curved arrows bends away from a longer arrowhead, and its
+ // direction is too unreliable for a wider one
+ const isCurved = !!element.roundness && !isElbowArrow(element);
+ const marker =
+ position === "start" ? element.startArrowhead : element.endArrowhead;
+
+ // all parts of cardinality markers scale together, and the marker has to
+ // stay on the last segment to be read along it
+ if (marker && isCardinalityArrowhead(marker)) {
+ return isCurved
+ ? 0
+ : getArrowheadSize(arrowhead) *
+ getCardinalityMarkerScale(marker, corner, element.strokeWidth);
+ }
+
+ // circles have no direction, the previous segment can run into them
+ if (arrowhead === "circle" || arrowhead === "circle_outline") {
+ return maxSize;
+ }
+
+ if (isCurved) {
+ return 0;
+ }
+
+ switch (arrowhead) {
+ case "bar":
+ // keep the bar's ends closer to the tip than to the previous segment,
+ // which (other than when going straight) runs at an angle to the bar
+ return Math.min(maxSize, length / Math.tan(turn / 2));
+ case "diamond":
+ case "diamond_outline":
+ // the diamond can reach back to the corner (at twice its size), past
+ // it the previous segment would cut through the diamond
+ return length / 2;
+ case "triangle":
+ case "triangle_outline":
+ // the triangle's base may sit on the previous segment
+ return Math.min(
+ maxSize,
+ getSidesClearSize(corner, getArrowheadAngle(arrowhead), 0),
+ );
+ case "arrow": {
+ // only grow as much as legibility needs, a full-size arrowhead past
+ // a sharp turn looks like an outline triangle
+ const legibleSize = getArrowheadSize(arrowhead) / 2;
+ // keep the open sides' strokes off the previous segment's. Smaller
+ // arrowheads are wider, so check the angles at both ends of the range.
+ return Math.min(
+ legibleSize,
+ maxSize,
+ getSidesClearSize(
+ corner,
+ getArrowheadAngle(arrowhead, legibleSize),
+ element.strokeWidth,
+ ),
+ getSidesClearSize(
+ corner,
+ getArrowheadAngle(arrowhead, 0),
+ element.strokeWidth,
+ ),
+ );
+ }
+ default:
+ return 0;
+ }
+};
+
export const getArrowheadPoints = (
element: ExcalidrawLinearElement,
shape: Drawable[],
@@ -833,7 +1079,16 @@ export const getArrowheadPoints = (
// This value is selected by minimizing a minimum size with the last segment of the arrowhead
const lengthMultiplier =
arrowhead === "diamond" || arrowhead === "diamond_outline" ? 0.25 : 0.5;
- const minSize = Math.min(size, length * lengthMultiplier);
+ let minSize = Math.min(size, length * lengthMultiplier);
+ if (minSize < size) {
+ minSize = Math.min(
+ size,
+ Math.max(
+ minSize,
+ getArrowheadSizeBeyondLastSegment(element, position, arrowhead),
+ ),
+ );
+ }
const tx = x2 - nx * minSize * offsetMultiplier;
const ty = y2 - ny * minSize * offsetMultiplier;
const xs = tx - nx * minSize;
@@ -844,7 +1099,7 @@ export const getArrowheadPoints = (
return [tx, ty, diameter];
}
- const angle = getArrowheadAngle(arrowhead);
+ const angle = getArrowheadAngle(arrowhead, minSize);
if (
arrowhead === "cardinality_many" ||
diff --git a/packages/element/src/shape.ts b/packages/element/src/shape.ts
index bf699b5b3c..e69715f954 100644
--- a/packages/element/src/shape.ts
+++ b/packages/element/src/shape.ts
@@ -60,6 +60,10 @@ import { headingForPointIsHorizontal } from "./heading";
import { canChangeRoundness } from "./comparisons";
import {
+ CARDINALITY_INNER_BAR_OFFSET,
+ CARDINALITY_ONE_OR_MANY_BAR_OFFSET,
+ CARDINALITY_ZERO_CIRCLE_OFFSET,
+ CARDINALITY_ZERO_CIRCLE_SCALE,
elementCenterPoint,
getArrowheadPoints,
getDiamondPoints,
@@ -357,15 +361,41 @@ const generateArrowheadOutlineCircle = (
const [x, y, diameter] = arrowheadPoints;
const circleOptions = {
...options,
- fill,
- fillStyle: "solid" as const,
stroke: strokeColor,
roughness: Math.min(0.5, options.roughness || 0),
+ // a second stroke would stray from the fill
+ disableMultiStroke: true,
};
delete circleOptions.strokeLineDash;
- return [generator.circle(x, y, diameter * diameterScale, circleOptions)];
+ return [
+ fillArrowheadOutline(
+ generator.circle(x, y, diameter * diameterScale, circleOptions),
+ fill,
+ ),
+ ];
+};
+
+/**
+ * Fills an arrowhead's outline (a polygon or circle drawn as a single rough
+ * stroke) along that stroke. rough.js' own solid fill is jittered separately
+ * from the outline, by up to 2px, which shows on shapes as small as
+ * arrowheads.
+ */
+const fillArrowheadOutline = (outline: Drawable, fill: string): Drawable => {
+ // polygons are drawn edge by edge, each starting with a move
+ const ops = outline.sets
+ .flatMap((set) => set.ops)
+ .map((op, index) =>
+ index > 0 && op.op === "move" ? { ...op, op: "lineTo" as const } : op,
+ );
+
+ return {
+ ...outline,
+ options: { ...outline.options, fill },
+ sets: [{ type: "fillPath", ops }, ...outline.sets],
+ };
};
const getArrowheadShapes = (
@@ -387,9 +417,6 @@ const getArrowheadShapes = (
canvasBackgroundColor,
isDarkMode,
);
- const cardinalityOneOrManyOffset = -0.25;
- const cardinalityZeroCircleScale = 0.8;
-
switch (arrowhead) {
case "circle":
case "circle_outline": {
@@ -417,24 +444,27 @@ const getArrowheadShapes = (
const [x, y, x2, y2, x3, y3] = arrowheadPoints;
const triangleOptions = {
...options,
- fill:
- arrowhead === "triangle_outline" ? backgroundFillColor : strokeColor,
- fillStyle: "solid" as const,
roughness: Math.min(1, options.roughness || 0),
+ // a second stroke would stray from the fill
+ disableMultiStroke: true,
+ // keep the corners of the small polygon in place, only bow the edges
+ preserveVertices: true,
};
// always use solid stroke for arrowhead
delete triangleOptions.strokeLineDash;
return [
- generator.polygon(
- [
- [x, y],
- [x2, y2],
- [x3, y3],
- [x, y],
- ],
- triangleOptions,
+ fillArrowheadOutline(
+ generator.polygon(
+ [
+ [x, y],
+ [x2, y2],
+ [x3, y3],
+ ],
+ triangleOptions,
+ ),
+ arrowhead === "triangle_outline" ? backgroundFillColor : strokeColor,
),
];
}
@@ -454,25 +484,28 @@ const getArrowheadShapes = (
const [x, y, x2, y2, x3, y3, x4, y4] = arrowheadPoints;
const diamondOptions = {
...options,
- fill:
- arrowhead === "diamond_outline" ? backgroundFillColor : strokeColor,
- fillStyle: "solid" as const,
roughness: Math.min(1, options.roughness || 0),
+ // a second stroke would stray from the fill
+ disableMultiStroke: true,
+ // keep the corners of the small polygon in place, only bow the edges
+ preserveVertices: true,
};
// always use solid stroke for arrowhead
delete diamondOptions.strokeLineDash;
return [
- generator.polygon(
- [
- [x, y],
- [x2, y2],
- [x3, y3],
- [x4, y4],
- [x, y],
- ],
- diamondOptions,
+ fillArrowheadOutline(
+ generator.polygon(
+ [
+ [x, y],
+ [x2, y2],
+ [x3, y3],
+ [x4, y4],
+ ],
+ diamondOptions,
+ ),
+ arrowhead === "diamond_outline" ? backgroundFillColor : strokeColor,
),
];
}
@@ -504,7 +537,7 @@ const getArrowheadShapes = (
shape,
position,
"cardinality_one",
- cardinalityOneOrManyOffset,
+ CARDINALITY_ONE_OR_MANY_BAR_OFFSET,
),
lineOptions,
),
@@ -516,7 +549,13 @@ const getArrowheadShapes = (
return [
...generateArrowheadCardinalityOne(
generator,
- getArrowheadPoints(element, shape, position, "cardinality_one", -0.5),
+ getArrowheadPoints(
+ element,
+ shape,
+ position,
+ "cardinality_one",
+ CARDINALITY_INNER_BAR_OFFSET,
+ ),
lineOptions,
),
...generateArrowheadCardinalityOne(
@@ -534,13 +573,25 @@ const getArrowheadShapes = (
generator,
options,
strokeColor,
- getArrowheadPoints(element, shape, position, "circle_outline", 1.5),
+ getArrowheadPoints(
+ element,
+ shape,
+ position,
+ "circle_outline",
+ CARDINALITY_ZERO_CIRCLE_OFFSET,
+ ),
backgroundFillColor,
- cardinalityZeroCircleScale,
+ CARDINALITY_ZERO_CIRCLE_SCALE,
),
...generateArrowheadCardinalityOne(
generator,
- getArrowheadPoints(element, shape, position, "cardinality_one", -0.5),
+ getArrowheadPoints(
+ element,
+ shape,
+ position,
+ "cardinality_one",
+ CARDINALITY_INNER_BAR_OFFSET,
+ ),
lineOptions,
),
];
@@ -558,9 +609,15 @@ const getArrowheadShapes = (
generator,
options,
strokeColor,
- getArrowheadPoints(element, shape, position, "circle_outline", 1.5),
+ getArrowheadPoints(
+ element,
+ shape,
+ position,
+ "circle_outline",
+ CARDINALITY_ZERO_CIRCLE_OFFSET,
+ ),
backgroundFillColor,
- cardinalityZeroCircleScale,
+ CARDINALITY_ZERO_CIRCLE_SCALE,
),
];
}
@@ -645,8 +702,10 @@ export const generateLinearCollisionShape = (
: [pointFrom<LocalPoint>(0, 0)];
if (isElbowArrow(element)) {
- return generator.path(generateElbowArrowShape(points, 16), options)
- .sets[0].ops;
+ return generator.path(
+ generateElbowArrowShape(points, ELBOW_ARROW_CORNER_RADIUS),
+ options,
+ ).sets[0].ops;
} else if (!element.roundness) {
return points.map((point, idx) => {
const p = pointRotateRads(
@@ -914,7 +973,7 @@ const _generateElementShape = (
} else {
shape = [
generator.path(
- generateElbowArrowShape(points, 16),
+ generateElbowArrowShape(points, ELBOW_ARROW_CORNER_RADIUS),
generateRoughOptions(element, true, isDarkMode),
),
];
@@ -1015,6 +1074,8 @@ const _generateElementShape = (
}
};
+export const ELBOW_ARROW_CORNER_RADIUS = 16;
+
const generateElbowArrowShape = (
points: readonly LocalPoint[],
radius: number,
diff --git a/packages/element/tests/bounds.test.ts b/packages/element/tests/bounds.test.ts
index 635bc47376..26c97deda4 100644
--- a/packages/element/tests/bounds.test.ts
+++ b/packages/element/tests/bounds.test.ts
@@ -1,16 +1,31 @@
-import { pointFrom } from "@excalidraw/math";
+import {
+ degreesToRadians,
+ distanceToLineSegment,
+ lineSegment,
+ pointDistance,
+ pointFrom,
+} from "@excalidraw/math";
import { arrayToMap, type Bounds, ROUNDNESS } from "@excalidraw/common";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import type { LocalPoint } from "@excalidraw/math";
import {
+ CARDINALITY_ONE_OR_MANY_BAR_OFFSET,
elementsOverlappingBBox,
+ getArrowheadAngle,
+ getArrowheadPoints,
+ getArrowheadSize,
getElementAbsoluteCoords,
getElementBounds,
} from "../src/bounds";
+import { ShapeCache } from "../src/shape";
-import type { ExcalidrawElement, ExcalidrawLinearElement } from "../src/types";
+import type {
+ Arrowhead,
+ ExcalidrawElement,
+ ExcalidrawLinearElement,
+} from "../src/types";
const _ce = ({
x,
@@ -207,3 +222,157 @@ describe("elementsOverlappingBBox()", () => {
).toEqual([rectInside]);
});
});
+
+describe("getArrowheadPoints()", () => {
+ // the last segment is 7px long, the previous one turns into it by ~67°
+ const prevSegment = lineSegment(
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(24, 10),
+ );
+ const lastSegmentLength = 7;
+
+ const tip = pointFrom<LocalPoint>(24, 10 + lastSegmentLength);
+
+ const getEndArrowheadPoints = (
+ endArrowhead: Arrowhead,
+ {
+ roundness = null,
+ part = endArrowhead,
+ offsetMultiplier,
+ }: {
+ roundness?: ExcalidrawLinearElement["roundness"];
+ /** the part of a composite marker to get */
+ part?: Arrowhead;
+ offsetMultiplier?: number;
+ } = {},
+ ) => {
+ const arrow = API.createElement({
+ type: "arrow",
+ points: [prevSegment[0], prevSegment[1], tip],
+ endArrowhead,
+ roundness,
+ roughness: 0,
+ strokeWidth: 2,
+ });
+
+ return getArrowheadPoints(
+ arrow,
+ ShapeCache.generateElementShape(arrow, null),
+ "end",
+ part,
+ offsetMultiplier,
+ )!;
+ };
+
+ it("lets triangle arrowheads cover a short last segment", () => {
+ const [, tipY, , y1, , y2] = getEndArrowheadPoints("triangle");
+
+ // the last segment points down
+ expect(tipY - (y1 + y2) / 2).toBeGreaterThan(lastSegmentLength);
+ });
+
+ it("grows arrow arrowheads on a short last segment clear of the previous one", () => {
+ const [, tipY, x1, y1, x2, y2] = getEndArrowheadPoints("arrow");
+
+ expect(tipY - (y1 + y2) / 2).toBeGreaterThan(lastSegmentLength * 0.75);
+ for (const sideEnd of [pointFrom(x1, y1), pointFrom(x2, y2)]) {
+ // stroke width
+ expect(distanceToLineSegment(sideEnd, prevSegment)).toBeGreaterThan(2);
+ }
+ });
+
+ it("doesn't grow arrowheads of curved arrows past the last segment", () => {
+ const [, tipY, , y1, , y2] = getEndArrowheadPoints("triangle", {
+ roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },
+ });
+
+ expect(tipY - (y1 + y2) / 2).toBeLessThanOrEqual(lastSegmentLength / 2);
+ });
+
+ it("grows circle arrowheads past a short last segment, also on curved arrows", () => {
+ for (const roundness of [null, { type: ROUNDNESS.PROPORTIONAL_RADIUS }]) {
+ const [, , diameter] = getEndArrowheadPoints("circle", { roundness });
+
+ expect(diameter).toBeGreaterThan(lastSegmentLength);
+ }
+ });
+
+ it("fits cardinality markers to a short last segment, scaling their parts together", () => {
+ const [apexX, apexY] = getEndArrowheadPoints("cardinality_one_or_many", {
+ part: "cardinality_many",
+ });
+ const [, , x1, y1, x2, y2] = getEndArrowheadPoints(
+ "cardinality_one_or_many",
+ {
+ part: "cardinality_one",
+ offsetMultiplier: CARDINALITY_ONE_OR_MANY_BAR_OFFSET,
+ },
+ );
+ const crowsFootLength = pointDistance(pointFrom(apexX, apexY), tip);
+ const barLength = pointDistance(pointFrom(x1, y1), pointFrom(x2, y2));
+
+ expect(crowsFootLength).toBeGreaterThan(lastSegmentLength / 2);
+ expect(crowsFootLength).toBeLessThanOrEqual(lastSegmentLength);
+ // same proportions as at full size
+ expect(barLength / crowsFootLength).toBeCloseTo(
+ (2 *
+ getArrowheadSize("cardinality_one") *
+ Math.sin(degreesToRadians(getArrowheadAngle("cardinality_one")))) /
+ getArrowheadSize("cardinality_many"),
+ );
+ });
+
+ it("fits cardinality markers before the rounded corner of elbow arrows", () => {
+ const lastSegmentLength = 19;
+ const arrow = API.createElement({
+ type: "arrow",
+ elbowed: true,
+ points: [
+ pointFrom<LocalPoint>(0, 0),
+ pointFrom<LocalPoint>(40, 0),
+ pointFrom<LocalPoint>(40, 30),
+ pointFrom<LocalPoint>(70, 30),
+ pointFrom<LocalPoint>(70, 30 + lastSegmentLength),
+ ],
+ endArrowhead: "cardinality_many",
+ roughness: 0,
+ });
+ const [, apexY] = getArrowheadPoints(
+ arrow,
+ ShapeCache.generateElementShape(arrow, null),
+ "end",
+ "cardinality_many",
+ )!;
+ const crowsFootLength = 30 + lastSegmentLength - apexY;
+ const cornerRadius = lastSegmentLength / 2;
+
+ expect(crowsFootLength).toBeGreaterThan(lastSegmentLength / 2);
+ // at most halfway into the corner's rounding
+ expect(crowsFootLength).toBeCloseTo(lastSegmentLength - cornerRadius / 2);
+ });
+
+ it("grows bar arrowheads with their ends closer to the tip than to the previous segment", () => {
+ const [tipX, tipY, x1, y1, x2, y2] = getEndArrowheadPoints("bar");
+ const arrowTip = pointFrom<LocalPoint>(tipX, tipY);
+
+ for (const barEnd of [
+ pointFrom<LocalPoint>(x1, y1),
+ pointFrom<LocalPoint>(x2, y2),
+ ]) {
+ const length = pointDistance(barEnd, arrowTip);
+
+ expect(length).toBeGreaterThan(lastSegmentLength);
+ expect(distanceToLineSegment(barEnd, prevSegment)).toBeGreaterThan(
+ length - 0.01,
+ );
+ }
+ });
+
+ it("lets diamond arrowheads reach back to the last segment's start", () => {
+ const [tipX, tipY, , , backX, backY] = getEndArrowheadPoints("diamond");
+
+ expect(
+ pointDistance(pointFrom(tipX, tipY), pointFrom(backX, backY)),
+ ).toBeCloseTo(lastSegmentLength);
+ });
+});
diff --git a/packages/element/tests/shape.test.ts b/packages/element/tests/shape.test.ts
new file mode 100644
index 0000000000..ff706e50ef
--- /dev/null
+++ b/packages/element/tests/shape.test.ts
@@ -0,0 +1,31 @@
+import { API } from "@excalidraw/excalidraw/tests/helpers/api";
+import { pointFrom } from "@excalidraw/math";
+
+import type { LocalPoint } from "@excalidraw/math";
+
+import { ShapeCache } from "../src/shape";
+
+import type { Op } from "roughjs/bin/core";
+
+describe("arrowhead shapes", () => {
+ it.each(["triangle", "diamond_outline", "circle"] as const)(
+ "fills %s arrowheads along their outline",
+ (arrowhead) => {
+ const arrow = API.createElement({
+ type: "arrow",
+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
+ endArrowhead: arrowhead,
+ roughness: 2,
+ });
+ const [, head] = ShapeCache.generateElementShape(arrow, null);
+ const [fill, outline] = head.sets;
+ const getCurves = (ops: Op[]) =>
+ ops.filter((op) => op.op === "bcurveTo").map((op) => op.data);
+
+ expect(fill.type).toBe("fillPath");
+ expect(outline.type).toBe("path");
+ // the fill only joins up the outline's curves
+ expect(getCurves(fill.ops)).toEqual(getCurves(outline.ops));
+ },
+ );
+});