mirror of
https://github.com/excalidraw/excalidraw.git
synced 2026-11-20 21:23:22 +03:00
fix(element): keep skeleton arrow labels where labelPosition put them
Review finding 2.
A skeleton arrow's `label.labelPosition` is a fraction of the arrow's path
as given (the only path a caller such as a layout engine knows), but the
placement pass (updateBoundElements() on bound arrows) then shortens both
ends by their binding gaps, and the stored fraction was resolved against
the shortened path. Unless both ends were trimmed equally, the label no
longer sat where the caller put it.
Reproduction steps:
convertToExcalidrawElements() with rectangles A (0,0,100x100) and
B (400,0,100x100), and an arrow at (80,50) with points [[0,0],[250,0]]
bound from A to B, label { text: "LABEL", labelPosition: 0.25 }. The
fraction denotes x = 80 + 0.25 * 250 = 142.5 on the arrow as given.
Placement moves the start to x = 106 (off A by the gap) and keeps the end
at 330. Label center measured with
LinearElementEditor.getBoundTextElementPosition().
Failure case:
observed label center x = 162 (0.25 of the placed 106..330 path), expected
142.5: 19.5px off. Other inputs: arrow 60..440, labelPosition 0.8 rendered
at 336.4 instead of 364 (-27.6px); arrow 100..400, labelPosition 0.25 at
178 instead of 175 (+3px).
Fix:
convertToExcalidrawElements() records the point a given labelPosition
denotes on the arrow as given, and after placing bound arrows re-derives
labelPosition as the parameter of the closest point on the placed path,
so the label stays at that point. Default labels (no labelPosition given)
are re-projected as an explicit 0.5 is: a layout engine that omits it
(mermaid-to-excalidraw does, for every edge label) puts its labels at the
midpoints of its routes as given. A point on a stretch placing trimmed
off projects onto the arrow's end, so the label is kept as close to it as
it can be while clear of the arrow's ends and arrowheads
(clampLabelPositionOffEnds()). The closest-point
projection is extracted from handleBoundTextDragging() into
LinearElementEditor.getPathParameterAtPoint() and reused, unchanged.
This commit is contained in:
4 files changed
+306
-37
No files matched your search
@@ -1871,7 +1871,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
|
||||
"id": Any<String>,
|
||||
"index": "aA",
|
||||
"isDeleted": false,
|
||||
"labelPosition": 0.5,
|
||||
"labelPosition": 0.4902348518371582,
|
||||
"lineHeight": 1.25,
|
||||
"link": null,
|
||||
"locked": false,
|
||||
@@ -1887,7 +1887,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
|
||||
"textAlign": "center",
|
||||
"type": "text",
|
||||
"updated": 1,
|
||||
"version": 3,
|
||||
"version": 4,
|
||||
"versionNonce": Any<Number>,
|
||||
"verticalAlign": "middle",
|
||||
"width": 120,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
arrayToMap,
|
||||
DEFAULT_STICKY_NOTE_BG,
|
||||
DEFAULT_STICKY_NOTE_SIZE,
|
||||
STICKY_NOTE_MIN_FONT_SIZE,
|
||||
@@ -17,7 +18,9 @@ import {
|
||||
newIframeElement,
|
||||
} from "../newElement";
|
||||
|
||||
import { getCommonBounds } from "../bounds";
|
||||
import { getArrowheadSize, getCommonBounds } from "../bounds";
|
||||
import { LinearElementEditor } from "../linearElementEditor";
|
||||
import { getBoundTextElement } from "../textElement";
|
||||
import {
|
||||
convertToExcalidrawElements,
|
||||
type ExcalidrawElementSkeleton,
|
||||
@@ -29,6 +32,7 @@ import type {
|
||||
ExcalidrawArrowElement,
|
||||
ExcalidrawStickyNoteElement,
|
||||
ExcalidrawTextElement,
|
||||
ExcalidrawTextElementWithContainer,
|
||||
} from "../types";
|
||||
|
||||
const opts = { regenerateIds: false };
|
||||
@@ -1366,4 +1370,162 @@ describe("Test Transform", () => {
|
||||
// placed off A by the binding gap
|
||||
expect(arrow.x).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("should keep arrow labels where labelPosition puts them on the arrow as given", () => {
|
||||
const elements = convertToExcalidrawElements(
|
||||
[
|
||||
{ type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 100 },
|
||||
{ type: "rectangle", id: "B", x: 400, y: 0, width: 100, height: 100 },
|
||||
{
|
||||
type: "arrow",
|
||||
x: 80,
|
||||
y: 50,
|
||||
// starts inside A and ends short of B, so placing it shortens its
|
||||
// start end only
|
||||
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(250, 0)],
|
||||
start: { id: "A" },
|
||||
end: { id: "B" },
|
||||
// a quarter of the way along the arrow as given: x = 142.5
|
||||
label: { text: "LABEL", labelPosition: 0.25 },
|
||||
},
|
||||
],
|
||||
opts,
|
||||
);
|
||||
const arrow = elements.find(
|
||||
(element) => element.type === "arrow",
|
||||
) as ExcalidrawArrowElement;
|
||||
const label = elements.find(
|
||||
(element) => element.type === "text",
|
||||
) as ExcalidrawTextElementWithContainer;
|
||||
|
||||
// placed off A by the binding gap
|
||||
expect(arrow.x).toBeGreaterThan(100);
|
||||
const { x, y } = LinearElementEditor.getBoundTextElementPosition(
|
||||
arrow,
|
||||
label,
|
||||
arrayToMap(elements),
|
||||
);
|
||||
expect(x + label.width / 2).toBeCloseTo(142.5);
|
||||
expect(y + label.height / 2).toBeCloseTo(50, 1);
|
||||
});
|
||||
|
||||
it("should place arrow labels with no labelPosition as with the default one given", () => {
|
||||
const elements = convertToExcalidrawElements(
|
||||
[undefined, 0.5].flatMap((labelPosition, i) => [
|
||||
{
|
||||
type: "rectangle" as const,
|
||||
id: `A${i}`,
|
||||
x: 0,
|
||||
y: 200 * i,
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
{
|
||||
type: "rectangle" as const,
|
||||
id: `B${i}`,
|
||||
x: 400,
|
||||
y: 200 * i,
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
{
|
||||
type: "arrow" as const,
|
||||
id: `arrow${i}`,
|
||||
// starts inside A and ends short of B, so placing it shortens its
|
||||
// start end only
|
||||
x: 80,
|
||||
y: 200 * i + 50,
|
||||
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(250, 0)],
|
||||
start: { id: `A${i}` },
|
||||
end: { id: `B${i}` },
|
||||
// halfway along the arrow as given: x = 205
|
||||
label: { text: "LABEL", labelPosition },
|
||||
},
|
||||
]),
|
||||
opts,
|
||||
);
|
||||
const elementsMap = arrayToMap(elements);
|
||||
const [defaultLabel, givenLabel] = ["arrow0", "arrow1"].map((id) => {
|
||||
const arrow = elementsMap.get(id) as ExcalidrawArrowElement;
|
||||
const label = getBoundTextElement(
|
||||
arrow,
|
||||
elementsMap,
|
||||
) as ExcalidrawTextElementWithContainer;
|
||||
const { x } = LinearElementEditor.getBoundTextElementPosition(
|
||||
arrow,
|
||||
label,
|
||||
elementsMap,
|
||||
);
|
||||
return { label, centerX: x + label.width / 2 };
|
||||
});
|
||||
|
||||
expect(defaultLabel.label.labelPosition).toBeCloseTo(
|
||||
givenLabel.label.labelPosition!,
|
||||
);
|
||||
expect(defaultLabel.centerX).toBeCloseTo(205);
|
||||
expect(givenLabel.centerX).toBeCloseTo(205);
|
||||
});
|
||||
|
||||
it("should keep arrow labels clear of the arrow's ends when labelPosition puts them on a stretch placing trimmed off", () => {
|
||||
const elements = convertToExcalidrawElements(
|
||||
[0.05, 0.95].flatMap((labelPosition, i) => [
|
||||
{
|
||||
type: "rectangle" as const,
|
||||
id: `A${i}`,
|
||||
x: 0,
|
||||
y: 200 * i,
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
{
|
||||
type: "rectangle" as const,
|
||||
id: `B${i}`,
|
||||
x: 400,
|
||||
y: 200 * i,
|
||||
width: 100,
|
||||
height: 100,
|
||||
},
|
||||
{
|
||||
type: "arrow" as const,
|
||||
id: `arrow${i}`,
|
||||
// from A's center to B's center, as a layout engine might route it
|
||||
x: 50,
|
||||
y: 200 * i + 50,
|
||||
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],
|
||||
start: { id: `A${i}` },
|
||||
end: { id: `B${i}` },
|
||||
// inside A, and inside B
|
||||
label: { text: "LABEL", labelPosition },
|
||||
},
|
||||
]),
|
||||
opts,
|
||||
);
|
||||
const elementsMap = arrayToMap(elements);
|
||||
const [startLabel, endLabel] = ["arrow0", "arrow1"].map((id) => {
|
||||
const arrow = elementsMap.get(id) as ExcalidrawArrowElement;
|
||||
const label = getBoundTextElement(
|
||||
arrow,
|
||||
elementsMap,
|
||||
) as ExcalidrawTextElementWithContainer;
|
||||
const { x } = LinearElementEditor.getBoundTextElementPosition(
|
||||
arrow,
|
||||
label,
|
||||
elementsMap,
|
||||
);
|
||||
const [, [endX]] = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
arrow,
|
||||
elementsMap,
|
||||
);
|
||||
return { arrow, label, x, endX };
|
||||
});
|
||||
|
||||
// as close to the start as it can be without covering it
|
||||
expect(startLabel.label.labelPosition).toBeGreaterThan(0);
|
||||
expect(startLabel.x).toBeCloseTo(startLabel.arrow.x);
|
||||
// ...and to the end without covering its arrowhead
|
||||
expect(endLabel.label.labelPosition).toBeLessThan(1);
|
||||
expect(endLabel.x + endLabel.label.width).toBeCloseTo(
|
||||
endLabel.endX - getArrowheadSize("arrow"),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1991,40 +1991,14 @@ export class LinearElementEditor {
|
||||
pointerX - linearElementEditor.pointerOffset.x,
|
||||
pointerY - linearElementEditor.pointerOffset.y,
|
||||
);
|
||||
const { segments, lengths, prefixSums, totalLength } =
|
||||
getLinearElementPathMetrics(element, elementsMap);
|
||||
if (segments.length === 0 || totalLength === 0) {
|
||||
const labelPosition = LinearElementEditor.getPathParameterAtPoint(
|
||||
element,
|
||||
pointerGlobalPoint,
|
||||
elementsMap,
|
||||
);
|
||||
if (labelPosition === null) {
|
||||
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,
|
||||
@@ -2046,6 +2020,52 @@ export class LinearElementEditor {
|
||||
};
|
||||
}
|
||||
|
||||
static getPathLength(
|
||||
element: ExcalidrawLinearElement,
|
||||
elementsMap: ElementsMap,
|
||||
): number {
|
||||
return getLinearElementPathMetrics(element, elementsMap).totalLength;
|
||||
}
|
||||
|
||||
/** the path parameter (0-1) of the point on the path closest to `point` */
|
||||
static getPathParameterAtPoint(
|
||||
element: ExcalidrawLinearElement,
|
||||
point: GlobalPoint,
|
||||
elementsMap: ElementsMap,
|
||||
): number | null {
|
||||
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], point);
|
||||
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
bestSegmentIndex = i;
|
||||
bestParameter = t;
|
||||
}
|
||||
}
|
||||
|
||||
const lengthWithinSegment = pathSegmentLengthAtParameter(
|
||||
segments[bestSegmentIndex],
|
||||
bestParameter,
|
||||
lengths[bestSegmentIndex],
|
||||
);
|
||||
|
||||
return clamp(
|
||||
(prefixSums[bestSegmentIndex] + lengthWithinSegment) / totalLength,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
}
|
||||
|
||||
static getPointAtPathParameter(
|
||||
container: ExcalidrawLinearElement,
|
||||
pathParameter: number,
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { pointFrom, type LocalPoint } from "@excalidraw/math";
|
||||
import {
|
||||
clamp,
|
||||
pointFrom,
|
||||
vectorFromPoint,
|
||||
vectorNormalize,
|
||||
type GlobalPoint,
|
||||
type LocalPoint,
|
||||
} from "@excalidraw/math";
|
||||
|
||||
import {
|
||||
DEFAULT_FONT_FAMILY,
|
||||
@@ -51,18 +58,21 @@ import { syncInvalidIndices } from "./fractionalIndex";
|
||||
|
||||
import {
|
||||
DEFAULT_BOUND_TEXT_LABEL_POSITION,
|
||||
getBoundTextElement,
|
||||
redrawTextBoundingBox,
|
||||
} from "./textElement";
|
||||
|
||||
import { LinearElementEditor } from "./linearElementEditor";
|
||||
|
||||
import { getCommonBounds } from "./bounds";
|
||||
import { getArrowheadSize, getCommonBounds } from "./bounds";
|
||||
|
||||
import { Scene } from "./Scene";
|
||||
|
||||
import type { RenderEnvironment } from "./renderEnvironment";
|
||||
|
||||
import type {
|
||||
Arrowhead,
|
||||
ElementsMap,
|
||||
ExcalidrawArrowElement,
|
||||
ExcalidrawBindableElement,
|
||||
ExcalidrawElement,
|
||||
@@ -583,6 +593,44 @@ class ElementStore {
|
||||
};
|
||||
}
|
||||
|
||||
// a label point on a stretch placing trimmed off its arrow projects onto the
|
||||
// arrow's end, centering the label on its endpoint (or arrowhead): keep it as
|
||||
// close to there as it can be while clear of them
|
||||
const clampLabelPositionOffEnds = (
|
||||
arrow: ExcalidrawArrowElement,
|
||||
label: ExcalidrawTextElement,
|
||||
labelPosition: number,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const length = LinearElementEditor.getPathLength(arrow, elementsMap);
|
||||
// how far the label's center has to stay from the end leaving `from` for
|
||||
// `to`: half the label along the arrow there, past its arrowhead
|
||||
const margin = (
|
||||
from: LocalPoint,
|
||||
to: LocalPoint,
|
||||
arrowhead: Arrowhead | null,
|
||||
) => {
|
||||
const [dx, dy] = vectorNormalize(vectorFromPoint(to, from));
|
||||
return (
|
||||
(Math.abs(dx) * label.width + Math.abs(dy) * label.height) / 2 +
|
||||
(arrowhead ? getArrowheadSize(arrowhead) : 0)
|
||||
);
|
||||
};
|
||||
const { points } = arrow;
|
||||
const min = margin(points[0], points[1], arrow.startArrowhead) / length;
|
||||
const max =
|
||||
1 -
|
||||
margin(
|
||||
points[points.length - 1],
|
||||
points[points.length - 2],
|
||||
arrow.endArrowhead,
|
||||
) /
|
||||
length;
|
||||
|
||||
// too short to clear both ends: as close to both as it can be
|
||||
return min < max ? clamp(labelPosition, min, max) : 0.5;
|
||||
};
|
||||
|
||||
export const convertToExcalidrawElements = (
|
||||
elementsSkeleton: ExcalidrawElementSkeleton[] | null,
|
||||
opts?: { regenerateIds?: boolean; renderEnvironment?: RenderEnvironment },
|
||||
@@ -757,6 +805,8 @@ export const convertToExcalidrawElements = (
|
||||
const elementsMap = elementStore.getElementsMap();
|
||||
// we don't have a real scene, so we just use a temp scene to query and mutate elements
|
||||
const scene = new Scene(elementsMap);
|
||||
// where on the arrows as given their labels' `labelPosition` puts them
|
||||
const labelPoints = new Map<ExcalidrawTextElement["id"], GlobalPoint>();
|
||||
|
||||
// Add labels and arrow bindings
|
||||
for (const [id, element] of elementsWithIds) {
|
||||
@@ -780,6 +830,18 @@ export const convertToExcalidrawElements = (
|
||||
elementStore.add(container);
|
||||
elementStore.add(text);
|
||||
|
||||
// given or default alike: omitting it is the same as giving 0.5
|
||||
if (isArrowElement(container) && text.labelPosition != null) {
|
||||
const labelPoint = LinearElementEditor.getPointAtPathParameter(
|
||||
container,
|
||||
text.labelPosition,
|
||||
elementsMap,
|
||||
);
|
||||
if (labelPoint) {
|
||||
labelPoints.set(text.id, labelPoint);
|
||||
}
|
||||
}
|
||||
|
||||
if (isArrowElement(container)) {
|
||||
const originalStart =
|
||||
element.type === "arrow" ? element?.start : undefined;
|
||||
@@ -878,6 +940,31 @@ export const convertToExcalidrawElements = (
|
||||
}
|
||||
}
|
||||
|
||||
// placing an arrow shortens its path, so its label's `labelPosition` would
|
||||
// no longer put it where it was placed (e.g. by a layout engine)
|
||||
const placedElementsMap = boundScene.getNonDeletedElementsMap();
|
||||
for (const arrow of updatedArrows) {
|
||||
const label = getBoundTextElement(arrow, placedElementsMap);
|
||||
const labelPoint = label && labelPoints.get(label.id);
|
||||
if (labelPoint && isArrowElement(arrow)) {
|
||||
const labelPosition = LinearElementEditor.getPathParameterAtPoint(
|
||||
arrow,
|
||||
labelPoint,
|
||||
placedElementsMap,
|
||||
);
|
||||
if (labelPosition !== null) {
|
||||
boundScene.mutateElement(label, {
|
||||
labelPosition: clampLabelPositionOffEnds(
|
||||
arrow,
|
||||
label,
|
||||
labelPosition,
|
||||
placedElementsMap,
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Once all the excalidraw elements are created, we can add frames since we
|
||||
// need to calculate coordinates and dimensions of frame which is possible after all
|
||||
// frame children are processed.
|
||||
|
||||
Reference in new issue
Block a user