Virtual whiteboard for sketching hand-drawn like diagrams
fix(packages/excalidraw): update arrow binding on skeleton transform (#12425)
David Luzar808d068e1826
diff --git a/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap b/packages/element/src/__tests__/__snapshots__/transform.test.ts.snapindex 5488f6448b..d24ddc8376 100644--- a/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap+++ b/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap@@ -100,7 +100,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"fillStyle": "solid","frameId": null,"groupIds": [],- "height": 35,+ "height": 32.91822178473251,"id": Any<String>,"index": "a2","isDeleted": false,@@ -113,8 +113,8 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s0,],[- 394,- 34,+ 371.50564585626694,+ 32.91822178473251,],],"roughness": 1,@@ -125,7 +125,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"elementId": "id49","fixedPoint": [1,- 0.5001,+ 0.5443037974683543,],"mode": "orbit",},@@ -134,11 +134,11 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 395,- "x": 247.5,- "y": 420.5,+ "width": 371.50564585626694,+ "x": 253,+ "y": 420.53164556962025,}`;@@ -162,7 +162,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"fillStyle": "solid","frameId": null,"groupIds": [],- "height": 0,+ "height": 0.009591838889264181,"id": Any<String>,"index": "a3","isDeleted": false,@@ -175,8 +175,8 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s0,],[- 399,- 0,+ 383.0807596341628,+ -0.009591838889264181,],],"roughness": 1,@@ -196,11 +196,11 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 400,- "x": 227.5,- "y": 450,+ "width": 383.0807596341628,+ "x": 241.7419168232014,+ "y": 450.00964627197783,}`;@@ -238,7 +238,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s"versionNonce": Any<Number>,"width": 300,"x": -53,- "y": 270,+ "y": 256.7088607594937,}`;@@ -357,7 +357,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t"endBinding": {"elementId": "text-2","fixedPoint": [- -2.05,+ 0,0.5001,],"mode": "orbit",@@ -378,7 +378,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t0,],[- 99,+ 293,0,],],@@ -399,11 +399,11 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 100,- "x": 255.5,- "y": 239,+ "width": 293,+ "x": 261,+ "y": 239.00250000000003,}`;@@ -446,8 +446,8 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t"versionNonce": Any<Number>,"verticalAlign": "middle","width": 130,- "x": 240,- "y": 226.5,+ "x": 342.5,+ "y": 226.50250000000003,}`;@@ -489,7 +489,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe0,],[- 99,+ 88.00000089285714,0,],],@@ -510,11 +510,11 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 100,- "x": 255.5,- "y": 239,+ "width": 88.00000089285714,+ "x": 261,+ "y": 239.01,}`;@@ -537,7 +537,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe"id": Any<String>,"index": "a1","isDeleted": false,- "labelPosition": 0.5,+ "labelPosition": 0.4999999949269481,"lineHeight": 1.25,"link": null,"locked": false,@@ -553,12 +553,12 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe"textAlign": "center","type": "text","updated": 1,- "version": 3,+ "version": 4,"versionNonce": Any<Number>,"verticalAlign": "middle","width": 130,"x": 240,- "y": 226.5,+ "y": 226.51,}`;@@ -676,7 +676,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when0,],[- 99,+ 88,0,],],@@ -697,11 +697,11 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 100,- "x": 255.5,- "y": 239,+ "width": 88,+ "x": 261,+ "y": 239.0025,}`;@@ -745,7 +745,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when"verticalAlign": "middle","width": 130,"x": 240,- "y": 226.5,+ "y": 226.5025,}`;@@ -906,7 +906,7 @@ exports[`Test Transform > should transform linear elements 1`] = `0,],[- 99,+ 100,0,],],@@ -923,7 +923,7 @@ exports[`Test Transform > should transform linear elements 1`] = `"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 100.5,+ "x": 100,"y": 20,}`;@@ -954,7 +954,7 @@ exports[`Test Transform > should transform linear elements 2`] = `0,],[- 99,+ 100,0,],],@@ -971,7 +971,7 @@ exports[`Test Transform > should transform linear elements 2`] = `"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 450.5,+ "x": 450,"y": 20,}`;@@ -1572,7 +1572,7 @@ exports[`Test Transform > should transform the elements correctly when linear el0,],[- 271.985,+ 266.28515625,0,],],@@ -1595,11 +1595,11 @@ exports[`Test Transform > should transform the elements correctly when linear el"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 7,"versionNonce": Any<Number>,- "width": 272.985,- "x": 111.762,- "y": 57,+ "width": 266.28515625,+ "x": 117.26171875,+ "y": 57.004400000000004,}`;@@ -1660,7 +1660,7 @@ exports[`Test Transform > should transform the elements correctly when linear el"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 4,+ "version": 6,"versionNonce": Any<Number>,"width": 0,"x": 77.017,@@ -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,12 +1887,12 @@ 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,- "x": 187.75450000000004,- "y": 44.5,+ "x": 187.816836560854,+ "y": 44.504400000000004,}`;@@ -1971,7 +1971,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide0,],[- 99,+ 100,0,],],@@ -1988,7 +1988,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 100.5,+ "x": 100,"y": 100,}`;@@ -2024,7 +2024,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide0,],[- 99,+ 100,0,],],@@ -2041,7 +2041,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 100.5,+ "x": 100,"y": 200,}`;@@ -2077,7 +2077,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide0,],[- 99,+ 100,0,],],@@ -2094,7 +2094,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 100.5,+ "x": 100,"y": 300,}`;@@ -2130,7 +2130,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide0,],[- 99,+ 100,0,],],@@ -2147,7 +2147,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide"version": 2,"versionNonce": Any<Number>,"width": 100,- "x": 100.5,+ "x": 100,"y": 400,}`;diff --git a/packages/element/src/__tests__/transform.test.ts b/packages/element/src/__tests__/transform.test.tsindex 9c44e59812..770ce3793a 100644--- a/packages/element/src/__tests__/transform.test.ts+++ b/packages/element/src/__tests__/transform.test.ts@@ -1,13 +1,16 @@import {+ arrayToMap,DEFAULT_STICKY_NOTE_BG,DEFAULT_STICKY_NOTE_SIZE,STICKY_NOTE_MIN_FONT_SIZE,STICKY_NOTE_MIN_SIZE,getUpdatedTimestamp,} from "@excalidraw/common";-import { pointFrom } from "@excalidraw/math";+import { pointDistance, pointFrom } from "@excalidraw/math";import { vi } from "vitest";+import type { GlobalPoint, LocalPoint } from "@excalidraw/math";+import {newElement,newEmbeddableElement,@@ -15,15 +18,24 @@ import {newIframeElement,} from "../newElement";+import { getBindingGap } from "../binding";+import { getArrowheadSize, getCommonBounds } from "../bounds";+import { LinearElementEditor } from "../linearElementEditor";+import { getBoundTextElement } from "../textElement";+import * as textMeasurements from "../textMeasurements";+import * as textWrapping from "../textWrapping";import {convertToExcalidrawElements,type ExcalidrawElementSkeleton,} from "../transform";+import type { RenderEnvironment } from "../renderEnvironment";+import type {ExcalidrawArrowElement,ExcalidrawStickyNoteElement,ExcalidrawTextElement,+ ExcalidrawTextElementWithContainer,} from "../types";const opts = { regenerateIds: false };@@ -444,10 +456,11 @@ describe("Test Transform", () => {expect(excalidrawElements.length).toBe(4);const [arrow, text, rectangle, ellipse] = excalidrawElements;+ // placed where binding puts bound arrows: off the shape by the gap+ expect(arrow.y).toBeCloseTo(239, 1);expect(arrow).toMatchObject({type: "arrow",- x: 255.5,- y: 239,+ x: 261,boundElements: [{ id: text.id, type: "text" }],startBinding: {elementId: rectangle.id,@@ -457,9 +470,10 @@ describe("Test Transform", () => {},});+ // centered on the arrow as placed+ expect(text.x).toBeCloseTo(240, 1);+ expect(text.y).toBeCloseTo(226.5, 1);expect(text).toMatchObject({- x: 240,- y: 226.5,type: "text",text: "HELLO WORLD!!",containerId: arrow.id,@@ -526,10 +540,11 @@ describe("Test Transform", () => {expect(excalidrawElements.length).toBe(4);const [arrow, text1, text2, text3] = excalidrawElements;+ // placed where binding puts bound arrows: off the text by the gap+ expect(arrow.y).toBeCloseTo(239, 1);expect(arrow).toMatchObject({type: "arrow",- x: 255.5,- y: 239,+ x: 261,boundElements: [{ id: text1.id, type: "text" }],startBinding: {elementId: text2.id,@@ -539,9 +554,10 @@ describe("Test Transform", () => {},});+ // centered on the arrow as placed+ expect(text1.x).toBeCloseTo(240, 1);+ expect(text1.y).toBeCloseTo(226.5, 1);expect(text1).toMatchObject({- x: 240,- y: 226.5,type: "text",text: "HELLO WORLD!!",containerId: arrow.id,@@ -668,6 +684,8 @@ describe("Test Transform", () => {type: "arrow",x: 255,y: 239,+ // reaching text-2, within its binding area+ width: 305,label: {text: "HELLO WORLD!!",},@@ -743,7 +761,7 @@ describe("Test Transform", () => {const [, , arrow, text] = excalidrawElements;expect(arrow).toMatchObject({type: "arrow",- x: 255.5,+ x: 255,y: 239,boundElements: [{@@ -769,7 +787,8 @@ describe("Test Transform", () => {const elements = [{type: "arrow",- x: 255,+ // reaching rect-1, within its binding area+ x: 460,y: 239,end: {id: "rect-1",@@ -793,7 +812,7 @@ describe("Test Transform", () => {const [arrow, rect] = excalidrawElements;expect((arrow as ExcalidrawArrowElement).endBinding).toStrictEqual({elementId: "rect-1",- fixedPoint: [-2.05, 0.5001],+ fixedPoint: [0, 0.5001],mode: "orbit",});expect(rect.boundElements).toStrictEqual([@@ -1187,4 +1206,899 @@ describe("Test Transform", () => {expect(note.height).toBeGreaterThan(DEFAULT_STICKY_NOTE_SIZE);});});++ it("should position arrow labels along the arrow when labelPosition provided", () => {+ const elements = convertToExcalidrawElements(+ [+ {+ type: "arrow",+ x: 100,+ y: 100,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],+ label: { text: "QUARTER", labelPosition: 0.25 },+ },+ {+ type: "arrow",+ x: 100,+ y: 200,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],+ label: { text: "HALF" },+ },+ ],+ opts,+ );+ const [arrow, defaultArrow] = elements.filter(+ (element) => element.type === "arrow",+ );+ const getLabel = (containerId: string) =>+ elements.find(+ (element) =>+ element.type === "text" && element.containerId === containerId,+ ) as ExcalidrawTextElement;++ expect(getLabel(arrow.id).labelPosition).toBe(0.25);+ expect(getLabel(defaultArrow.id).labelPosition).toBe(0.5);+ // centered a quarter of the way along the arrow+ const label = getLabel(arrow.id);+ expect(label.x + label.width / 2).toBeCloseTo(150);+ });++ it("should clamp out-of-range arrow label positions as restore does", () => {+ const elements = convertToExcalidrawElements(+ [-1, 5].map((labelPosition, i) => ({+ type: "arrow" as const,+ x: 100,+ y: 100 * i,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],+ label: { text: "LABEL", labelPosition },+ })),+ opts,+ );+ const labels = elements.filter(+ (element) => element.type === "text",+ ) as ExcalidrawTextElement[];++ expect(labels.map((label) => label.labelPosition)).toEqual([0, 1]);+ });++ it("should measure bound arrow labels with the given render environment", () => {+ const renderEnvironment: RenderEnvironment = {+ createCanvas: () => document.createElement("canvas"),+ createImage: () => ({} as HTMLImageElement),+ textMetrics: { getLineWidth: () => 42 },+ };+ 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: 100,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(300, 0)],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: "LABEL" },+ },+ ],+ { ...opts, renderEnvironment },+ );+ const label = elements.find(+ (element) => element.type === "text",+ ) as ExcalidrawTextElement;++ expect(label.width).toBe(42);+ });++ it("should size frames around bound arrows as placed by their bindings", () => {+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],+ start: { id: "A" },+ end: { id: "B" },+ // fits on one line along the arrow as given (280px), but wraps+ // along the arrow shortened by its binding gaps+ label: { text: "aaaa bbbb cccc dddd eeee fff" },+ },+ { type: "frame", children: ["A", "B", "arrow"] },+ ],+ opts,+ );+ const frame = elements.find((element) => element.type === "frame")!;+ const label = elements.find(+ (element) => element.type === "text",+ ) as ExcalidrawTextElement;++ expect(label.text).toContain("\n");+ const [, minY, , maxY] = getCommonBounds(+ elements.filter((element) => element.frameId === frame.id),+ );+ expect(frame.y).toBeLessThanOrEqual(minY);+ expect(frame.y + frame.height).toBeGreaterThanOrEqual(maxY);+ });++ it("should keep bound arrows sized by their points when labels rewrap", () => {+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ x: 100,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],+ start: { id: "A" },+ end: { id: "B" },+ // wraps to a taller label along the arrow shortened by its binding+ label: { text: "aaaa bbbb cccc dddd eeee fff" },+ },+ ],+ opts,+ );+ const arrow = elements.find(+ (element) => element.type === "arrow",+ ) as ExcalidrawArrowElement;+ const label = elements.find(+ (element) => element.type === "text",+ ) as ExcalidrawTextElement;++ expect(label.text).toContain("\n");+ expect(arrow.points.every(([, y]) => y === 0)).toBe(true);+ expect(arrow.height).toBe(0);+ });++ it("should place bound arrows listed by elements they aren't bound to", () => {+ const convert = (stale: boolean) =>+ convertToExcalidrawElements(+ [+ // lists the arrow without it being bound to it+ ...(stale+ ? [+ {+ type: "rectangle" as const,+ id: "X",+ x: 0,+ y: 300,+ boundElements: [{ id: "arrow", type: "arrow" as const }],+ },+ ]+ : []),+ { 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",+ id: "arrow",+ x: 100,+ y: 50,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(300, 0),+ ],+ start: { id: "A" },+ end: { id: "B" },+ },+ ],+ opts,+ ).find((element) => element.id === "arrow")!;++ const arrow = convert(true);+ expect(arrow).toMatchObject({+ x: convert(false).x,+ width: convert(false).width,+ });+ // 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"),+ );+ });++ it("should store bound arrow labels' x/y where the placed arrows put them", () => {+ const elements = convertToExcalidrawElements(+ [undefined, 0.25].flatMap((labelPosition, i) => [+ {+ type: "rectangle" as const,+ id: `A${i}`,+ x: 0,+ y: 100 * i,+ width: 100,+ height: 20,+ },+ {+ type: "rectangle" as const,+ id: `B${i}`,+ x: 500,+ y: 100 * i,+ width: 100,+ height: 20,+ },+ {+ type: "arrow" as const,+ x: 100,+ y: 100 * i + 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],+ start: { id: `A${i}` },+ end: { id: `B${i}` },+ // wraps along the arrow shortened by its binding gaps+ label: { text: "aaaa bbbb cccc dddd eeee fff", labelPosition },+ },+ ]),+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const labels = elements.filter(+ (element) => element.type === "text",+ ) as ExcalidrawTextElementWithContainer[];++ expect(labels).toHaveLength(2);+ for (const label of labels) {+ const arrow = elementsMap.get(+ label.containerId,+ ) as ExcalidrawArrowElement;+ expect(label.text).toContain("\n");+ const { x, y } = LinearElementEditor.getBoundTextElementPosition(+ arrow,+ label,+ elementsMap,+ );+ expect(label.x).toBeCloseTo(x);+ expect(label.y).toBeCloseTo(y);+ }+ });++ it("should keep arrows' unbound ends where they're given", () => {+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 100 },+ {+ type: "arrow",+ id: "half-bound",+ x: 100,+ y: 50,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(300, 100),+ ],+ start: { id: "A" },+ },+ {+ type: "arrow",+ id: "unbound",+ x: 100,+ y: 300,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(300, 0)],+ },+ ],+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const halfBound = elementsMap.get("half-bound") as ExcalidrawArrowElement;+ const unbound = elementsMap.get("unbound") as ExcalidrawArrowElement;++ // placed off A by the binding gap+ expect(halfBound.x).toBeGreaterThan(100);+ const [endX, endY] = LinearElementEditor.getPointAtIndexGlobalCoordinates(+ halfBound,+ -1,+ elementsMap,+ );+ expect(endX).toBeCloseTo(400);+ expect(endY).toBeCloseTo(150);+ expect(unbound).toMatchObject({+ x: 100,+ y: 300,+ width: 300,+ points: [+ [0, 0],+ [300, 0],+ ],+ });+ });++ it("should unbind arrow ends given beyond the binding areas of the elements they're bound to", () => {+ // e.g. a sequence diagram's messages, bound to their participants' headers+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ id: "beyond",+ x: 50,+ // further below them than binding distance+ y: 40,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(500, 0)],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: "message" },+ },+ {+ type: "arrow",+ id: "half-far",+ x: 100,+ y: 10,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(450, 490),+ ],+ start: { id: "A" },+ end: { id: "B" },+ },+ {+ type: "arrow",+ id: "near",+ x: 50,+ // within binding distance below them+ y: 30,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(500, 0)],+ start: { id: "A" },+ end: { id: "B" },+ },+ ],+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const near = elementsMap.get("near") as ExcalidrawArrowElement;+ const beyond = elementsMap.get("beyond") as ExcalidrawArrowElement;+ const halfFar = elementsMap.get("half-far") as ExcalidrawArrowElement;++ expect(beyond).toMatchObject({+ startBinding: null,+ endBinding: null,+ x: 50,+ y: 40,+ width: 500,+ height: 0,+ points: [+ [0, 0],+ [500, 0],+ ],+ });+ expect(near.startBinding?.elementId).toBe("A");+ expect(near.endBinding?.elementId).toBe("B");+ expect(halfFar.startBinding?.elementId).toBe("A");+ expect(halfFar.endBinding).toBeNull();+ expect(elementsMap.get("A")?.boundElements).toEqual([+ { id: "half-far", type: "arrow" },+ { id: "near", type: "arrow" },+ ]);+ expect(elementsMap.get("B")?.boundElements).toEqual([+ { id: "near", type: "arrow" },+ ]);++ // placed off A by the binding gap, its unbound end left where given+ expect(halfFar.x).toBeGreaterThan(100);+ const [endX, endY] = LinearElementEditor.getPointAtIndexGlobalCoordinates(+ halfFar,+ -1,+ elementsMap,+ );+ expect(endX).toBeCloseTo(550);+ expect(endY).toBeCloseTo(500);+ });++ it("should frame arrows unbound from a frame's children with them", () => {+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ id: "arrow",+ x: 50,+ // further below them than binding distance+ y: 60,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(500, 0)],+ start: { id: "A" },+ end: { id: "B" },+ },+ { type: "frame", children: ["A", "B"] },+ ],+ opts,+ );+ const frame = elements.find((element) => element.type === "frame")!;+ const arrow = elements.find(+ (element) => element.id === "arrow",+ ) as ExcalidrawArrowElement;++ expect(arrow.startBinding).toBeNull();+ expect(arrow.endBinding).toBeNull();+ expect(arrow.frameId).toBe(frame.id);+ const [, , , maxY] = getCommonBounds([arrow]);+ expect(frame.y + frame.height).toBeGreaterThanOrEqual(maxY);+ });++ it("should extend arrow ends falling short of the elements they're bound to onto them", () => {+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ id: "short",+ // ends 100px short of B: within its end segment's length+ x: 150,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(250, 0)],+ end: { id: "B" },+ },+ {+ type: "arrow",+ id: "stub",+ // starts 80px short of A: within the minimum extension+ x: 180,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(20, 0)],+ start: { id: "A" },+ },+ {+ type: "arrow",+ id: "too-short",+ // ends 200px short of B: beyond its end segment's length+ x: 200,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],+ end: { id: "B" },+ },+ ],+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const short = elementsMap.get("short") as ExcalidrawArrowElement;+ const stub = elementsMap.get("stub") as ExcalidrawArrowElement;+ const tooShort = elementsMap.get("too-short") as ExcalidrawArrowElement;++ expect(short.endBinding?.elementId).toBe("B");+ const [shortEndX, shortEndY] =+ LinearElementEditor.getPointAtIndexGlobalCoordinates(+ short,+ -1,+ elementsMap,+ );+ expect(shortEndX).toBeCloseTo(500 - getBindingGap(elementsMap.get("B")!));+ expect(shortEndY).toBeCloseTo(10);++ expect(stub.startBinding?.elementId).toBe("A");+ const [stubStartX, stubStartY] =+ LinearElementEditor.getPointAtIndexGlobalCoordinates(+ stub,+ 0,+ elementsMap,+ );+ expect(stubStartX).toBeCloseTo(100 + getBindingGap(elementsMap.get("A")!));+ expect(stubStartY).toBeCloseTo(10);++ expect(tooShort).toMatchObject({+ endBinding: null,+ x: 200,+ y: 10,+ points: [+ [0, 0],+ [100, 0],+ ],+ });+ expect(elementsMap.get("A")?.boundElements).toEqual([+ { id: "stub", type: "arrow" },+ ]);+ expect(elementsMap.get("B")?.boundElements).toEqual([+ { id: "short", type: "arrow" },+ ]);+ });++ it("should keep arrow ends bound to frame children where given, whether frameId or children is given", () => {+ for (const byFrameId of [true, false]) {+ const elements = convertToExcalidrawElements(+ [+ // not sized yet when arrow ends are checked+ {+ type: "frame",+ id: "frame",+ x: 0,+ y: 0,+ children: byFrameId ? [] : ["A", "B"],+ },+ {+ type: "rectangle",+ id: "A",+ x: 0,+ y: 0,+ width: 100,+ height: 20,+ ...(byFrameId && { frameId: "frame" }),+ },+ {+ type: "rectangle",+ id: "B",+ x: 300,+ y: 0,+ width: 100,+ height: 20,+ ...(byFrameId && { frameId: "frame" }),+ },+ {+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 10,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(200, 0),+ ],+ start: { id: "A" },+ end: { id: "B" },+ },+ ],+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const arrow = elementsMap.get("arrow") as ExcalidrawArrowElement;++ expect(elementsMap.get("A")?.frameId).toBe("frame");+ expect(elementsMap.get("B")?.frameId).toBe("frame");+ // on the edges they're given on, facing each other+ expect(arrow.startBinding).toStrictEqual({+ elementId: "A",+ fixedPoint: [1, 0.5001],+ mode: "orbit",+ });+ expect(arrow.endBinding).toStrictEqual({+ elementId: "B",+ fixedPoint: [0, 0.5001],+ mode: "orbit",+ });+ }+ });++ it("should bind arrows to elements sized to fit their labels after them as to those before them", () => {+ const convert = (rectangleFirst: boolean) => {+ // sized to fit its label, after the arrows listed before it are bound+ const rectangle = {+ type: "rectangle",+ id: "B",+ x: 400,+ y: 25,+ label: { text: "B" },+ } as const;+ const arrow = {+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 50,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(300, 0)],+ end: { id: "B" },+ } as const;+ const elements = convertToExcalidrawElements(+ rectangleFirst ? [rectangle, arrow] : [arrow, rectangle],+ opts,+ );+ return elements.find(+ (element) => element.id === "arrow",+ ) as ExcalidrawArrowElement;+ };+ const arrowFirst = convert(false);+ const rectangleFirst = convert(true);++ // not bound to the center of B as it was before being sized, but where+ // the end was given: B's left edge+ expect(arrowFirst.endBinding?.fixedPoint[0]).toBeCloseTo(0);+ expect(arrowFirst.endBinding).toEqual(rectangleFirst.endBinding);+ expect(arrowFirst.points).toEqual(rectangleFirst.points);+ expect(arrowFirst.height).toBe(0);+ });++ it("should route elbow arrows extended onto elements as to elements sized to fit their labels after them as to those before them", () => {+ // starting short of A, or ending short of B+ for (const [startX, endX] of [+ [150, 400],+ [106, 330],+ ]) {+ const convert = (rectangleFirst: boolean) => {+ const rectangleA = {+ type: "rectangle",+ id: "A",+ x: 0,+ y: 25,+ width: 100,+ height: 50,+ } as const;+ // sized to fit its label, after the arrows listed before it are bound+ const rectangleB = {+ type: "rectangle",+ id: "B",+ x: 400,+ y: 25,+ label: { text: "B" },+ } as const;+ const arrow = {+ type: "arrow",+ id: "arrow",+ elbowed: true,+ x: startX,+ y: 50,+ points: [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(endX - startX, 0),+ ],+ start: { id: "A" },+ end: { id: "B" },+ } as const;+ const elements = convertToExcalidrawElements(+ rectangleFirst+ ? [rectangleA, rectangleB, arrow]+ : [rectangleA, arrow, rectangleB],+ opts,+ );+ return elements.find(+ (element) => element.id === "arrow",+ ) as ExcalidrawArrowElement;+ };+ const arrowFirst = convert(false);+ const rectangleFirst = convert(true);++ // into B's left side, not routed around it from its center as it was+ // before being sized+ expect(arrowFirst.endBinding?.fixedPoint[0]).toBeLessThan(0);+ expect(arrowFirst.endBinding).toEqual(rectangleFirst.endBinding);+ expect(arrowFirst.points).toEqual(rectangleFirst.points);+ expect(arrowFirst.points).toHaveLength(2);+ }+ });++ it("should create shapes for start / end without ids where arrows in any direction start / end", () => {+ const arrows = {+ diagonal: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 100)],+ vertical: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(0, 200)],+ "right-to-left": [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(-200, 0),+ ],+ "multi-point": [+ pointFrom<LocalPoint>(0, 0),+ pointFrom<LocalPoint>(0, 150),+ pointFrom<LocalPoint>(200, 150),+ ],+ };+ for (const [id, points] of Object.entries(arrows)) {+ for (const [start, end] of [+ [{ type: "rectangle" }, { type: "ellipse" }],+ [{ type: "diamond" }, { type: "text", text: "end" }],+ ] as const) {+ const elements = convertToExcalidrawElements(+ [{ type: "arrow", id, x: 0, y: 0, points, start, end }],+ opts,+ );+ const elementsMap = arrayToMap(elements);+ const arrow = elementsMap.get(id) as ExcalidrawArrowElement;+ const [, startElement, endElement] = elements;++ expect(arrow.startBinding?.elementId).toBe(startElement.id);+ expect(arrow.endBinding?.elementId).toBe(endElement.id);+ expect(startElement.boundElements).toEqual([{ id, type: "arrow" }]);+ expect(endElement.boundElements).toEqual([{ id, type: "arrow" }]);++ // placed off the shapes by about the gap, not routed around them+ for (const [index, element, [x, y]] of [+ [0, startElement, points[0]],+ [-1, endElement, points[points.length - 1]],+ ] as const) {+ const point = LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ index,+ elementsMap,+ );+ // the arrows are at 0,0+ expect(+ pointDistance(point, pointFrom<GlobalPoint>(x, y)),+ ).toBeLessThan(2 * getBindingGap(element));+ }+ }+ }+ });++ it("should wrap and measure arrow labels once, along the arrows as placed", () => {+ const wrapTextSpy = vi.spyOn(textWrapping, "wrapText");+ const measureTextSpy = vi.spyOn(textMeasurements, "measureText");+ const elements = convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 20 },+ { type: "rectangle", id: "B", x: 500, y: 0, width: 100, height: 20 },+ {+ type: "arrow",+ id: "bound",+ x: 100,+ y: 10,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: "aaaa bbbb cccc dddd eeee fff" },+ },+ {+ type: "arrow",+ id: "unbound",+ x: 100,+ y: 300,+ points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(400, 0)],+ label: { text: "aaaa bbbb cccc dddd eeee fff" },+ },+ ],+ opts,+ );+ const labelOf = (arrowId: string) =>+ elements.find(+ (element) => element.type === "text" && element.containerId === arrowId,+ ) as ExcalidrawTextElement;++ // wrapped along the bound arrow shortened by its binding gaps, and along+ // the unbound one as given+ expect(labelOf("bound").text).toContain("\n");+ expect(labelOf("unbound").text).not.toContain("\n");+ // once each (plus each unwrapped label's measurement as created)+ expect(wrapTextSpy).toHaveBeenCalledTimes(2);+ expect(measureTextSpy).toHaveBeenCalledTimes(4);++ wrapTextSpy.mockRestore();+ measureTextSpy.mockRestore();+ });});diff --git a/packages/element/src/align.ts b/packages/element/src/align.tsindex 860e3473d3..683dcd8235 100644--- a/packages/element/src/align.ts+++ b/packages/element/src/align.ts@@ -6,6 +6,7 @@ import { getSelectedElementsByGroup } from "./groups";import { getNonDeletedElements } from ".";+import type { RenderEnvironment } from "./renderEnvironment";import type { Scene } from "./Scene";import type { BoundingBox } from "./bounds";@@ -21,6 +22,8 @@ export const alignElements = (alignment: Alignment,scene: Scene,appState: Readonly<AppState>,+ /** measures the labels of the bound arrows the alignment moves */+ renderEnvironment?: RenderEnvironment,): NonDeletedExcalidrawElement[] => {const groups = getSelectedElementsByGroup(selectedElements,@@ -45,6 +48,7 @@ export const alignElements = (// update bound elementsupdateBoundElements(element, scene, {simultaneouslyUpdated: group,+ renderEnvironment,});return updatedEle;});diff --git a/packages/element/src/binding.ts b/packages/element/src/binding.tsindex b0c6a56054..f5f0f97386 100644--- a/packages/element/src/binding.ts+++ b/packages/element/src/binding.ts@@ -35,6 +35,7 @@ import {hitElementItself,intersectElementWithLineSegment,isBindableElementInsideOtherBindable,+ isPointInBindingArea,isPointInElement,} from "./collision";import { distanceToElement } from "./distance";@@ -68,6 +69,7 @@ import {import { isNonDeletedElement } from ".";+import type { RenderEnvironment } from "./renderEnvironment";import type { Scene } from "./Scene";import type { ElementUpdate } from "./mutateElement";@@ -1184,6 +1186,100 @@ export const bindBindingElement = (applyBinding(arrow, hoveredElement, binding, startOrEnd, scene);};+/**+ * Whether the arrow's end is bound to an element it's beyond the binding area+ * of, i.e. that it couldn't be bound to in the editor (e.g. a participant's+ * header in a sequence diagram, as laid out by mermaid)+ */+export const isEndBoundBeyondBindingArea = (+ arrow: ExcalidrawArrowElement,+ startOrEnd: "start" | "end",+ elementsMap: NonDeletedSceneElementsMap,+ zoom: AppState["zoom"],+): boolean => {+ const binding =+ startOrEnd === "start" ? arrow.startBinding : arrow.endBinding;+ const bindableElement = binding && elementsMap.get(binding.elementId);+ return (+ !!bindableElement &&+ isBindableElement(bindableElement) &&+ !isPointInBindingArea(+ LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ startOrEnd === "start" ? 0 : -1,+ elementsMap,+ ),+ bindableElement,+ elementsMap,+ zoom,+ )+ );+};++// how far at least to extend an arrow's end segment looking for what it's+// bound to (see `getBoundEndExtension`)+const MIN_BOUND_END_EXTENSION = 100;++/**+ * Extends the arrow's bound end along its end segment, by the segment's length+ * (at least MIN_BOUND_END_EXTENSION), to find where it would reach the element+ * it's bound to, off the element by the binding gap. Moving the end there+ * restores bindings given to arrows that just fall short of their elements.+ *+ * @returns where to move the end to, or null if it doesn't reach the element+ */+export const getBoundEndExtension = (+ arrow: ExcalidrawArrowElement,+ startOrEnd: "start" | "end",+ elementsMap: NonDeletedSceneElementsMap,+): GlobalPoint | null => {+ const binding =+ startOrEnd === "start" ? arrow.startBinding : arrow.endBinding;+ const bindableElement = binding && elementsMap.get(binding.elementId);+ if (+ !bindableElement ||+ !isBindableElement(bindableElement) ||+ arrow.points.length < 2+ ) {+ return null;+ }++ const end = LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ startOrEnd === "start" ? 0 : -1,+ elementsMap,+ );+ const adjacent = LinearElementEditor.getPointAtIndexGlobalCoordinates(+ arrow,+ startOrEnd === "start" ? 1 : -2,+ elementsMap,+ );+ const segmentLength = pointDistance(adjacent, end);+ if (segmentLength < PRECISION) {+ return null;+ }++ const extension = lineSegment(+ end,+ pointFromVector(+ vectorScale(+ vectorNormalize(vectorFromPoint(end, adjacent)),+ Math.max(segmentLength, MIN_BOUND_END_EXTENSION),+ ),+ end,+ ),+ );+ return (+ intersectElementWithLineSegment(+ bindableElement,+ elementsMap,+ extension,+ getBindingGap(bindableElement),+ ).sort((a, b) => pointDistanceSq(a, end) - pointDistanceSq(b, end))[0] ??+ null+ );+};+export const unbindBindingElement = (arrow: ExcalidrawArrowElement,startOrEnd: "start" | "end",@@ -1316,6 +1412,88 @@ export const reanchorBindingsToOutline = (});};+/**+ * Places both bound ends of `arrow` where its bindings put them on the elements+ * in `elementsMap` they're bound to, and rewraps its label along it as placed.+ * Leaves the label's x/y as they were (the editor derives arrow labels' x/y as+ * it renders them), so callers returning the elements as data must store them+ * (see `LinearElementEditor.getBoundTextElementPosition`).+ */+export const updateBoundArrow = (+ arrow: NonDeleted<ExcalidrawArrowElement>,+ scene: Scene,+ elementsMap: ElementsMap,+ /** measures the arrow's label */+ renderEnvironment?: RenderEnvironment,+ /**+ * whether it's placed as what it's bound to moved: an arrow bound to one+ * element at both ends then moves with it whole (its midpoints with its+ * start), rather than only at its ends+ */+ boundElementMoved = true,+) => {+ const startBindingElement = arrow.startBinding+ ? elementsMap.get(arrow.startBinding.elementId)+ : null;+ const endBindingElement = arrow.endBinding+ ? // PERF: If the arrow is bound to the same element on both ends.+ startBindingElement?.id === arrow.endBinding.elementId+ ? startBindingElement+ : elementsMap.get(arrow.endBinding.elementId)+ : null;++ const updates = bindableElementsVisitor(+ elementsMap,+ arrow,+ (bindableElement, bindingProp) => {+ if (+ bindableElement &&+ isBindableElement(bindableElement) &&+ (bindingProp === "startBinding" || bindingProp === "endBinding")+ ) {+ const point = updateBoundPoint(+ arrow,+ bindingProp,+ arrow[bindingProp],+ bindableElement,+ elementsMap,+ );++ if (point) {+ return [+ bindingProp === "startBinding" ? 0 : arrow.points.length - 1,+ { point },+ ] as MapEntry<PointsPositionUpdates>;+ }+ }++ return null;+ },+ ).filter(+ (update): update is MapEntry<PointsPositionUpdates> => update !== null,+ );++ LinearElementEditor.movePoints(arrow, scene, new Map(updates), undefined, {+ moveMidPointsWithElement:+ boundElementMoved &&+ !!startBindingElement &&+ startBindingElement?.id === endBindingElement?.id,+ });++ const boundText = getBoundTextElement(arrow, elementsMap);+ if (boundText && !boundText.isDeleted) {+ handleBindTextResize(+ arrow,+ scene,+ false,+ false,+ false,+ false,+ renderEnvironment,+ );+ }+};+// Supports translating, rotating and scaling `changedElement` with bound// linear elements.export const updateBoundElements = (@@ -1325,6 +1503,8 @@ export const updateBoundElements = (/** see `getSimultaneouslyUpdatedElementIds` for how to pass it */simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[];changedElements?: Map<string, ExcalidrawElement>;+ /** measures the labels of the arrows it updates (the host's, in the editor) */+ renderEnvironment?: RenderEnvironment;},) => {if (!isBindableElement(changedElement)) {@@ -1361,68 +1541,12 @@ export const updateBoundElements = (return;}- // Check for intersections before updating bound elements incase connected elements overlap- const startBindingElement = element.startBinding- ? elementsMap.get(element.startBinding.elementId)- : null;- const endBindingElement = element.endBinding- ? // PERF: If the arrow is bound to the same element on both ends.- startBindingElement?.id === element.endBinding.elementId- ? startBindingElement- : elementsMap.get(element.endBinding.elementId)- : null;-// `linearElement` is being moved/scaled already, just update the bindingif (simultaneouslyUpdatedElementIds.has(element.id)) {return;}- const updates = bindableElementsVisitor(- elementsMap,- element,- (bindableElement, bindingProp) => {- if (- bindableElement &&- isBindableElement(bindableElement) &&- (bindingProp === "startBinding" || bindingProp === "endBinding") &&- (changedElement.id === element[bindingProp]?.elementId ||- changedElement.id ===- element[- bindingProp === "startBinding" ? "endBinding" : "startBinding"- ]?.elementId)- ) {- const point = updateBoundPoint(- element,- bindingProp,- element[bindingProp],- bindableElement,- elementsMap,- );-- if (point) {- return [- bindingProp === "startBinding" ? 0 : element.points.length - 1,- { point },- ] as MapEntry<PointsPositionUpdates>;- }- }-- return null;- },- ).filter(- (update): update is MapEntry<PointsPositionUpdates> => update !== null,- );-- LinearElementEditor.movePoints(element, scene, new Map(updates), {- moveMidPointsWithElement:- !!startBindingElement &&- startBindingElement?.id === endBindingElement?.id,- });-- const boundText = getBoundTextElement(element, elementsMap);- if (boundText && !boundText.isDeleted) {- handleBindTextResize(element, scene, false);- }+ updateBoundArrow(element, scene, elementsMap, options?.renderEnvironment);};boundElementsVisitor(elementsMap, changedElement, visitor);@@ -1500,6 +1624,8 @@ export const updateBindings = (options?: {simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[];newSize?: { width: number; height: number };+ /** measures the labels of the bound arrows it updates */+ renderEnvironment?: RenderEnvironment;},) => {if (isArrowElement(latestElement)) {diff --git a/packages/element/src/collision.ts b/packages/element/src/collision.tsindex cb1f13f675..bc07024a18 100644--- a/packages/element/src/collision.ts+++ b/packages/element/src/collision.ts@@ -320,10 +320,6 @@ const bindableElementBorderDistanceIfClose = (return -Infinity;}- if (isPointClippedByEnclosingFrame(element, point, elementsMap)) {- return -Infinity;- }-const isInside = isPointInElement(point, element, elementsMap);// frames are only bindable from the outside, so arrows ending inside// a frame can bind to its children (or stay unbound)@@ -339,6 +335,29 @@ const bindableElementBorderDistanceIfClose = (return distance > tolerance ? -Infinity : -distance;};+/**+ * Whether an arrow endpoint at the point could bind to the element: inside it,+ * or within binding distance of its outline. Unlike `getBindingCandidates`,+ * it ignores frame clipping, as frames may not be sized yet (e.g. while+ * converting skeletons, where frames are sized around their children last)+ */+export const isPointInBindingArea = (+ point: GlobalPoint,+ element: NonDeleted<ExcalidrawBindableElement>,+ elementsMap: ElementsMap,+ zoom: AppState["zoom"],+) => {+ const maxDistance = maxBindingDistance_simple(zoom);+ return (+ bindableElementBorderDistanceIfClose(+ element,+ point,+ elementsMap,+ maxDistance,+ ) > -maxDistance+ );+};+type BindingCandidate = {element: NonDeleted<ExcalidrawBindableElement>;/** distance to the outline: positive inside, negative outside */@@ -399,6 +418,10 @@ const getBindingCandidates = (}}+ if (isPointClippedByEnclosingFrame(element, point, elementsMap)) {+ continue;+ }+const distance = bindableElementBorderDistanceIfClose(element,point,diff --git a/packages/element/src/delta.ts b/packages/element/src/delta.tsindex 8219389fd8..8b45b705e1 100644--- a/packages/element/src/delta.ts+++ b/packages/element/src/delta.ts@@ -64,6 +64,7 @@ import { Scene } from "./Scene";import type { BindableProp, BindingProp } from "./binding";import type { ElementUpdate } from "./mutateElement";+import type { RenderEnvironment } from "./renderEnvironment";/*** Represents the difference between two objects of the same type.@@ -1019,6 +1020,11 @@ type ElementPartial<TElement extends ExcalidrawElement = ExcalidrawElement> =export type ApplyToOptions = {excludedProperties?: Set<keyof ElementPartial>;+ /**+ * measures the labels re-laid out after applying (bound texts, and the+ * labels of bound arrows) -- the editor passes the host's+ */+ renderEnvironment?: RenderEnvironment;};type ApplyToFlags = {@@ -1508,7 +1514,11 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {): undefined;- ElementsDelta.redrawElements(nextElements, changedElements);+ ElementsDelta.redrawElements(+ nextElements,+ changedElements,+ options?.renderEnvironment,+ );if (versionsBeforeRedraw) {for (const [id, element] of nextElements) {@@ -2034,6 +2044,7 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {public static redrawElements(nextElements: SceneElementsMap,changedElements: Map<string, OrderedExcalidrawElement>,+ renderEnvironment?: RenderEnvironment,) {try {// we don't have an up-to-date scene, as we can be just in the middle of applying history entry@@ -2041,10 +2052,18 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {// so we are creating a temp scene just to query and mutate elementsconst tempScene = new Scene(nextElements, { skipValidation: true });- ElementsDelta.redrawTextBoundingBoxes(tempScene, changedElements);+ ElementsDelta.redrawTextBoundingBoxes(+ tempScene,+ changedElements,+ renderEnvironment,+ );// needs ordered nextElements to avoid z-index binding issues- ElementsDelta.redrawBoundArrows(tempScene, changedElements);+ ElementsDelta.redrawBoundArrows(+ tempScene,+ changedElements,+ renderEnvironment,+ );} catch (e) {console.error(`Couldn't redraw elements`, e);@@ -2059,6 +2078,7 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {private static redrawTextBoundingBoxes(scene: Scene,changed: Map<string, OrderedExcalidrawElement>,+ renderEnvironment?: RenderEnvironment,) {const elements = scene.getNonDeletedElementsMap();const boxesToRedraw = new Map<@@ -2100,13 +2120,14 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {continue;}- redrawTextBoundingBox(boundText, container, scene);+ redrawTextBoundingBox(boundText, container, scene, renderEnvironment);}}private static redrawBoundArrows(scene: Scene,changed: Map<string, OrderedExcalidrawElement>,+ renderEnvironment?: RenderEnvironment,) {for (const element of changed.values()) {if (!element.isDeleted && isBindableElement(element)) {@@ -2116,6 +2137,7 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {scene,{changedElements: changed,+ renderEnvironment,},);}diff --git a/packages/element/src/distribute.ts b/packages/element/src/distribute.tsindex 7409a61084..ccaab049e9 100644--- a/packages/element/src/distribute.ts+++ b/packages/element/src/distribute.ts@@ -7,6 +7,7 @@ import { getSelectedElementsByGroup } from "./groups";import { getNonDeletedElements } from ".";+import type { RenderEnvironment } from "./renderEnvironment";import type { Scene } from "./Scene";import type { ElementsMap, NonDeletedExcalidrawElement } from "./types";@@ -22,6 +23,8 @@ export const distributeElements = (distribution: Distribution,appState: Readonly<AppState>,scene: Scene,+ /** measures the labels of the bound arrows the distribution moves */+ renderEnvironment?: RenderEnvironment,): NonDeletedExcalidrawElement[] => {const [start, mid, end, extent] =distribution.axis === "x"@@ -79,6 +82,7 @@ export const distributeElements = (});updateBoundElements(element, scene, {simultaneouslyUpdated: group,+ renderEnvironment,});return updatedElement;});@@ -107,6 +111,7 @@ export const distributeElements = (});updateBoundElements(element, scene, {simultaneouslyUpdated: group,+ renderEnvironment,});return updatedElement;});diff --git a/packages/element/src/dragElements.ts b/packages/element/src/dragElements.tsindex 7678c0a18b..ad3cc0eba0 100644--- a/packages/element/src/dragElements.ts+++ b/packages/element/src/dragElements.ts@@ -47,6 +47,8 @@ export const dragSelectedElements = (y: number;},gridSize: NullableGridSize,+ /** measures the labels of the bound arrows the drag moves */+ renderEnvironment?: RenderEnvironment,) => {if (_selectedElements.length === 1 &&@@ -134,6 +136,7 @@ export const dragSelectedElements = (}updateBoundElements(element, scene, {simultaneouslyUpdated: elementsToUpdateArray,+ renderEnvironment,});} else if (// NOTE: Add a little initial drag to the arrow dragging when the arrowdiff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.tsindex 4274b54228..e3b395fff3 100644--- a/packages/element/src/linearElementEditor.ts+++ b/packages/element/src/linearElementEditor.ts@@ -127,7 +127,6 @@ const getNormalizedPoints = ({type PointMoveOtherUpdates = {startBinding?: FixedPointBinding | null;endBinding?: FixedPointBinding | null;- moveMidPointsWithElement?: boolean | null;suggestedBinding?: AppState["suggestedBinding"] | null;};@@ -387,7 +386,6 @@ export class LinearElementEditor {{startBinding: updates?.startBinding,endBinding: updates?.endBinding,- moveMidPointsWithElement: updates?.moveMidPointsWithElement,},{isBindingEnabled: app.state.isBindingEnabled,@@ -592,7 +590,6 @@ export class LinearElementEditor {{startBinding: updates?.startBinding,endBinding: updates?.endBinding,- moveMidPointsWithElement: updates?.moveMidPointsWithElement,},{isBindingEnabled: app.state.isBindingEnabled,@@ -633,7 +630,15 @@ export class LinearElementEditor {// Attached text might need to update if arrow dimensions changeconst boundTextElement = getBoundTextElement(element, elementsMap);if (boundTextElement) {- handleBindTextResize(element, app.scene, false);+ handleBindTextResize(+ element,+ app.scene,+ false,+ false,+ false,+ false,+ app.renderEnvironment,+ );}// Update selected points for elbow arrows because elbow arrows add and@@ -1653,11 +1658,11 @@ export class LinearElementEditor {otherUpdates?: {startBinding?: FixedPointBinding | null;endBinding?: FixedPointBinding | null;- moveMidPointsWithElement?: boolean | null;},options?: {isBindingEnabled?: boolean;isMidpointSnappingEnabled?: boolean;+ moveMidPointsWithElement?: boolean;},) {const { points } = element;@@ -1704,7 +1709,7 @@ export class LinearElementEditor {const current = pointUpdates.get(idx)?.point ?? p;if (- otherUpdates?.moveMidPointsWithElement &&+ options?.moveMidPointsWithElement &&idx !== 0 &&idx !== points.length - 1 &&!pointUpdates.has(idx)@@ -1979,6 +1984,48 @@ export class LinearElementEditor {pointerX - linearElementEditor.pointerOffset.x,pointerY - linearElementEditor.pointerOffset.y,);+ const labelPosition = LinearElementEditor.getPathParameterAtPoint(+ element,+ pointerGlobalPoint,+ elementsMap,+ );+ if (labelPosition === null) {+ return null;+ }+ 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 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) {@@ -1990,10 +2037,7 @@ export class LinearElementEditor {let bestParameter = 0;for (let i = 0; i < segments.length; i++) {- const { t, distance } = pathSegmentClosestParameter(- segments[i],- pointerGlobalPoint,- );+ const { t, distance } = pathSegmentClosestParameter(segments[i], point);if (distance < bestDistance) {bestDistance = distance;@@ -2008,30 +2052,11 @@ export class LinearElementEditor {lengths[bestSegmentIndex],);- const labelPosition = clamp(+ return 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(diff --git a/packages/element/src/listMarker.ts b/packages/element/src/listMarker.tsindex 37c0f6193c..a73ea91700 100644--- a/packages/element/src/listMarker.ts+++ b/packages/element/src/listMarker.ts@@ -8,6 +8,7 @@ import {} from "./textElement";import { isBoundToContainer, isTextElement } from "./typeChecks";+import type { RenderEnvironment } from "./renderEnvironment";import type { Scene } from "./Scene";import type { ExcalidrawElement, ExcalidrawTextElement } from "./types";@@ -208,11 +209,12 @@ const setText = (container: ExcalidrawElement | null,originalText: string,scene: Scene,+ renderEnvironment: RenderEnvironment | undefined,) => {if (container) {scene.mutateElement(element, { originalText });// re-wraps the label, and grows the container if need be- redrawTextBoundingBox(element, container, scene);+ redrawTextBoundingBox(element, container, scene, renderEnvironment);} else {scene.mutateElement(element, {originalText,@@ -222,6 +224,8 @@ const setText = (null,scene.getNonDeletedElementsMap(),originalText,+ undefined,+ renderEnvironment,),});}@@ -241,6 +245,8 @@ const setText = (export const advanceDuplicatedListMarkers = (duplicatedElements: readonly ExcalidrawElement[],scene: Scene,+ /** measures the re-numbered texts */+ renderEnvironment?: RenderEnvironment,): ListMarkerAdvance[] => {const duplicatesMap = arrayToMap(duplicatedElements);const elementsMap = scene.getNonDeletedElementsMap();@@ -323,7 +329,7 @@ export const advanceDuplicatedListMarkers = (: null,});- setText(element, container, nextOriginalText, scene);+ setText(element, container, nextOriginalText, scene, renderEnvironment);}}@@ -337,6 +343,8 @@ export const applyListMarkerAdvances = (advances: readonly ListMarkerAdvance[],direction: "prev" | "next",scene: Scene,+ /** measures the re-numbered texts */+ renderEnvironment?: RenderEnvironment,) => {const elementsMap = scene.getNonDeletedElementsMap();@@ -359,6 +367,7 @@ export const applyListMarkerAdvances = (? advance.prevOriginalText: advance.nextOriginalText,scene,+ renderEnvironment,);}};diff --git a/packages/element/src/resizeElements.ts b/packages/element/src/resizeElements.tsindex 78aad8e163..81394fd379 100644--- a/packages/element/src/resizeElements.ts+++ b/packages/element/src/resizeElements.ts@@ -120,7 +120,7 @@ export const transformElements = (pointerY,shouldRotateWithDiscreteAngle,);- updateBoundElements(element, scene);+ updateBoundElements(element, scene, { renderEnvironment });}} else if (transformHandleType) {const elementId = selectedElements[0].id;@@ -158,7 +158,7 @@ export const transformElements = (}}if (isTextElement(element)) {- updateBoundElements(element, scene);+ updateBoundElements(element, scene, { renderEnvironment });}return true;} else if (selectedElements.length > 1) {@@ -172,6 +172,7 @@ export const transformElements = (shouldRotateWithDiscreteAngle,centerX,centerY,+ renderEnvironment,);return true;} else if (transformHandleType) {@@ -436,6 +437,7 @@ const rotateMultipleElements = (shouldRotateWithDiscreteAngle: boolean,centerX: number,centerY: number,+ renderEnvironment?: RenderEnvironment,) => {const elementsMap = scene.getNonDeletedElementsMap();let centerAngle =@@ -478,6 +480,7 @@ const rotateMultipleElements = (updateBoundElements(element, scene, {simultaneouslyUpdated: elements,+ renderEnvironment,});if (isBindingElement(element)) {@@ -1006,7 +1009,7 @@ export const resizeSingleElement = ();}- updateBoundElements(latestElement, scene);+ updateBoundElements(latestElement, scene, { renderEnvironment });}};@@ -1580,6 +1583,7 @@ export const resizeMultipleElements = (} else {updateBoundElements(element, scene, {simultaneouslyUpdated: elementsToUpdate,+ renderEnvironment,});}diff --git a/packages/element/src/stickyNote.ts b/packages/element/src/stickyNote.tsindex f7ab36c5da..d68bd1ba6f 100644--- a/packages/element/src/stickyNote.ts+++ b/packages/element/src/stickyNote.ts@@ -867,11 +867,10 @@ export const updateStickyNoteLayout = (scene.mutateElement(textElement, layout.text);}if (bindings !== false && !container.isDeleted) {- updateBoundElements(- container as NonDeletedExcalidrawElement,- scene,- bindings || undefined,- );+ updateBoundElements(container as NonDeletedExcalidrawElement, scene, {+ ...bindings,+ renderEnvironment: layoutOpts.renderEnvironment,+ });}return layout;diff --git a/packages/element/src/textElement.ts b/packages/element/src/textElement.tsindex 843b5d0f3a..297a716a17 100644--- a/packages/element/src/textElement.ts+++ b/packages/element/src/textElement.ts@@ -218,8 +218,9 @@ export const handleBindTextResize = (nextHeight = metrics.height;nextWidth = metrics.width;}- // increase height in case text element height exceeds- if (nextHeight > maxHeight) {+ // increase height in case text element height exceeds (but not an+ // arrow's, which its points determine, and its label doesn't grow)+ if (!isArrowElement(container) && nextHeight > maxHeight) {containerHeight = computeContainerDimensionForBoundText(nextHeight,container.type,@@ -233,16 +234,15 @@ export const handleBindTextResize = (scene.mutateElement(container, {height: containerHeight,- ...(!isArrowElement(container) &&- getPositionAfterHeightChange(- container,- containerHeight,- shouldResizeFromCenter- ? "center"- : shouldResizeFromTop- ? "bottom"- : "top",- )),+ ...getPositionAfterHeightChange(+ container,+ containerHeight,+ shouldResizeFromCenter+ ? "center"+ : shouldResizeFromTop+ ? "bottom"+ : "top",+ ),});}diff --git a/packages/element/src/transform.ts b/packages/element/src/transform.tsindex d14ba3214b..db58a7a9bf 100644--- a/packages/element/src/transform.ts+++ b/packages/element/src/transform.ts@@ -1,4 +1,14 @@-import { pointFrom, type LocalPoint } from "@excalidraw/math";+import {+ clamp,+ isFiniteNumber,+ pointFrom,+ PRECISION,+ vectorFromPoint,+ vectorNormalize,+ type GlobalPoint,+ type LocalPoint,+ type Radians,+} from "@excalidraw/math";import {DEFAULT_FONT_FAMILY,@@ -23,7 +33,15 @@ import {import type { MarkOptional } from "@excalidraw/common/utility-types";import type { Zoom } from "@excalidraw/excalidraw/types";-import { bindBindingElement } from "./binding";+import {+ bindBindingElement,+ bindBindingElementToFixedPoint,+ calculateFixedPointForNonElbowArrowBinding,+ getBoundEndExtension,+ isEndBoundBeyondBindingArea,+ unbindBindingElement,+ updateBoundArrow,+} from "./binding";import {newArrowElement,newElement,@@ -41,24 +59,32 @@ import {} from "./newElement";import { normalizeStickyNoteStrokeColor } from "./stickyNote";import { measureText, normalizeText } from "./textMeasurements";-import { isArrowElement, isStickyNoteElement } from "./typeChecks";+import {+ isArrowElement,+ isBindableElement,+ isElbowArrow,+ isStickyNoteElement,+} from "./typeChecks";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,@@ -77,6 +103,7 @@ import type {NonDeletedExcalidrawElement,NonDeletedSceneElementsMap,Ordered,+ PointsPositionUpdates,TextAlign,VerticalAlign,ExcalidrawStickyNoteElement,@@ -102,6 +129,8 @@ export type ValidLinearElement = {fontFamily?: FontFamilyValues;textAlign?: TextAlign;verticalAlign?: VerticalAlign;+ /** where along an arrow's path (0-1) the label is centered */+ labelPosition?: ExcalidrawTextElement["labelPosition"];} & FragmentConstructorOpts;end?:| (@@ -260,7 +289,8 @@ const DEFAULT_DIMENSION = 100;const bindTextToContainer = (container: ExcalidrawElement,- textProps: { text: string } & FragmentConstructorOpts,+ textProps: { text: string } & FragmentConstructorOpts &+ Pick<Partial<ExcalidrawTextElement>, "labelPosition">,scene: Scene,renderEnvironment?: RenderEnvironment,) => {@@ -282,9 +312,14 @@ const bindTextToContainer = (...textProps,containerId: container.id,strokeColor: stickyInk ?? (textProps.strokeColor || container.strokeColor),+ // normalized as `restore` doeslabelPosition: isArrowElement(container)- ? DEFAULT_BOUND_TEXT_LABEL_POSITION+ ? isFiniteNumber(textProps.labelPosition)+ ? clamp(textProps.labelPosition, 0, 1)+ : DEFAULT_BOUND_TEXT_LABEL_POSITION: null,+ // normalized as `restore` does: arrow labels aren't rotated+ ...(isArrowElement(container) && { angle: 0 as Radians }),renderEnvironment,});@@ -298,11 +333,63 @@ const bindTextToContainer = (: null),});- redrawTextBoundingBox(textElement, container, scene, renderEnvironment);+ // the caller measures an arrow's label once, along its arrow as placed+ // (binding shortens a bound one)+ if (!isArrowElement(container)) {+ redrawTextBoundingBox(textElement, container, scene, renderEnvironment);+ }return [container, textElement] as const;};+// where to create a shape for an arrow end: centered on its end segment as+// extended past the end, with the end on its outline, so the arrow points+// into it (left to right if the segment has no length)+const getArrowEndShapePosition = (+ arrow: ExcalidrawLinearElement,+ startOrEnd: "start" | "end",+ type: ExcalidrawElement["type"] | undefined,+ width: number,+ height: number,+) => {+ const { points } = arrow;+ const [endPoint, nextPoint] =+ startOrEnd === "start"+ ? [points[0], points[1]]+ : [points[points.length - 1], points[points.length - 2]];+ let dx = nextPoint ? endPoint[0] - nextPoint[0] : 0;+ let dy = nextPoint ? endPoint[1] - nextPoint[1] : 0;+ const length = Math.hypot(dx, dy);+ if (length) {+ dx /= length;+ dy /= length;+ } else {+ dx = startOrEnd === "start" ? -1 : 1;+ }++ // from the center to the outline, along the segment+ const a = width / 2;+ const b = height / 2;+ let distance;+ if (type === "ellipse" || type === "diamond") {+ const denominator =+ type === "ellipse"+ ? Math.hypot(b * dx, a * dy)+ : b * Math.abs(dx) + a * Math.abs(dy);+ distance = denominator ? (a * b) / denominator : 0;+ } else {+ distance = Math.min(+ dx ? a / Math.abs(dx) : Infinity,+ dy ? b / Math.abs(dy) : Infinity,+ );+ }++ return {+ x: arrow.x + endPoint[0] + dx * distance - a,+ y: arrow.y + endPoint[1] + dy * distance - b,+ };+};+const bindLinearElementToElement = (linearElement: NonDeleted<ExcalidrawArrowElement>,start: ValidLinearElement["start"],@@ -336,9 +423,16 @@ const bindLinearElementToElement = (}}- const startX = start.x || linearElement.x - width;- const startY = start.y || linearElement.y - height / 2;const startType = existingElement ? existingElement.type : start.type;+ const startPosition = getArrowEndShapePosition(+ linearElement,+ "start",+ startType,+ width,+ height,+ );+ const startX = start.x || startPosition.x;+ const startY = start.y || startPosition.y;if (startType) {if (startType === "text") {@@ -363,9 +457,16 @@ const bindLinearElementToElement = (renderEnvironment,});// to position the text correctly when coordinates not provided+ const position = getArrowEndShapePosition(+ linearElement,+ "start",+ "text",+ startBoundElement.width,+ startBoundElement.height,+ );Object.assign(startBoundElement, {- x: start.x || linearElement.x - startBoundElement.width,- y: start.y || linearElement.y - startBoundElement.height / 2,+ x: start.x || position.x,+ y: start.y || position.y,});} else {switch (startType) {@@ -414,9 +515,16 @@ const bindLinearElementToElement = (console.error(`No element for end binding with id ${end.id} found`);}}- const endX = end.x || linearElement.x + linearElement.width;- const endY = end.y || linearElement.y - height / 2;const endType = existingElement ? existingElement.type : end.type;+ const endPosition = getArrowEndShapePosition(+ linearElement,+ "end",+ endType,+ width,+ height,+ );+ const endX = end.x || endPosition.x;+ const endY = end.y || endPosition.y;if (endType) {if (endType === "text") {@@ -442,8 +550,17 @@ const bindLinearElementToElement = (renderEnvironment,});// to position the text correctly when coordinates not provided+ const position = getArrowEndShapePosition(+ linearElement,+ "end",+ "text",+ endBoundElement.width,+ endBoundElement.height,+ );Object.assign(endBoundElement, {- y: end.y || linearElement.y - endBoundElement.height / 2,+ // an existing text keeps its x, as it always has+ x: end.x || (existingElement ? endBoundElement.x : position.x),+ y: end.y || position.y,});} else {switch (endType) {@@ -482,64 +599,6 @@ const bindLinearElementToElement = (}}- // Safe check to early return for single point- if (linearElement.points.length < 2) {- return {- linearElement,- startBoundElement,- endBoundElement,- };- }-- // Update start/end points by 0.5 so bindings don't overlap with start/end bound element coordinates.- const endPointIndex = linearElement.points.length - 1;- const delta = 0.5;-- const newPoints = cloneJSON<readonly LocalPoint[]>(linearElement.points);-- // left to right so shift the arrow towards right- if (- linearElement.points[endPointIndex][0] >- linearElement.points[endPointIndex - 1][0]- ) {- newPoints[0][0] = delta;- newPoints[endPointIndex][0] -= delta;- }-- // right to left so shift the arrow towards left- if (- linearElement.points[endPointIndex][0] <- linearElement.points[endPointIndex - 1][0]- ) {- newPoints[0][0] = -delta;- newPoints[endPointIndex][0] += delta;- }- // top to bottom so shift the arrow towards top- if (- linearElement.points[endPointIndex][1] >- linearElement.points[endPointIndex - 1][1]- ) {- newPoints[0][1] = delta;- newPoints[endPointIndex][1] -= delta;- }-- // bottom to top so shift the arrow towards bottom- if (- linearElement.points[endPointIndex][1] <- linearElement.points[endPointIndex - 1][1]- ) {- newPoints[0][1] = -delta;- newPoints[endPointIndex][1] += delta;- }-- Object.assign(- linearElement,- LinearElementEditor.getNormalizeElementPointsAndCoords({- ...linearElement,- points: newPoints,- }),- );-return {linearElement,startBoundElement,@@ -576,6 +635,48 @@ 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,+) => {+ // on the arrow as placed: keep it where it was put, as on unplaced arrows+ if (labelPosition > PRECISION && labelPosition < 1 - PRECISION) {+ return labelPosition;+ }+ 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 },@@ -748,8 +849,16 @@ 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+ // we don't have a real scene, so we just use a temp scene to query and mutate+ // elements (a snapshot of the store: resynced below once the store is complete)const scene = new Scene(elementsMap);+ // where on the arrows as given their labels' `labelPosition` puts them+ const labelPoints = new Map<ExcalidrawTextElement["id"], GlobalPoint>();+ // arrow labels yet to be measured, along their arrows+ const unmeasuredArrowLabels = new Map<+ ExcalidrawTextElement["id"],+ [ExcalidrawArrowElement, ExcalidrawTextElement]+ >();// Add labels and arrow bindingsfor (const [id, element] of elementsWithIds) {@@ -772,6 +881,21 @@ export const convertToExcalidrawElements = ();elementStore.add(container);elementStore.add(text);+ if (isArrowElement(container)) {+ unmeasuredArrowLabels.set(text.id, [container, 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 =@@ -840,6 +964,185 @@ export const convertToExcalidrawElements = (}}+ // Excalidraw places the ends of bound arrows itself whenever it updates+ // their bindings (e.g. on undo/redo, or moving what they're bound to), so+ // place them now, or they'd move then (before sizing frames around them).+ // The store has gained the labels and the elements bound arrows were+ // created to bind to since the scene was built, so resync it first+ scene.replaceAllElements(elementStore.getElementsMap());+ const placedElementsMap = scene.getNonDeletedElementsMap();+ // arrows unbound below, by what they were bound to: they still connect it+ // (e.g. they're framed with it)+ const unboundArrowIds = new Map<ExcalidrawElement["id"], string[]>();+ for (const arrow of scene.getNonDeletedElements()) {+ if (!isArrowElement(arrow)) {+ continue;+ }+ // users can't (re)bind an end given (e.g. by a layout engine) beyond the+ // binding area of what it's bound to, so don't leave it bound there,+ // unless it just falls short of it: then extend it onto it. Decide for+ // both ends as given, as moving either end of an elbow arrow reroutes it+ // from both its bindings, which could move the other end onto its element+ const extendedEnds: PointsPositionUpdates = new Map();+ const extendedEndPoints = new Map<"start" | "end", GlobalPoint>();+ for (const startOrEnd of ["start", "end"] as const) {+ if (+ !isEndBoundBeyondBindingArea(+ arrow,+ startOrEnd,+ placedElementsMap,+ DEFAULT_ZOOM,+ )+ ) {+ continue;+ }+ const extendedEnd = getBoundEndExtension(+ arrow,+ startOrEnd,+ placedElementsMap,+ );+ if (extendedEnd) {+ extendedEndPoints.set(startOrEnd, extendedEnd);+ extendedEnds.set(startOrEnd === "start" ? 0 : arrow.points.length - 1, {+ point: LinearElementEditor.pointFromAbsoluteCoords(+ arrow,+ extendedEnd,+ placedElementsMap,+ ),+ });+ continue;+ }+ const elementId = unbindBindingElement(arrow, startOrEnd, scene);+ if (elementId) {+ unboundArrowIds.set(elementId, [+ ...(unboundArrowIds.get(elementId) ?? []),+ arrow.id,+ ]);+ }+ }+ if (extendedEnds.size) {+ // moving an end reroutes elbow arrows from both their bindings, which+ // may have been made before what they're bound to was sized (see below),+ // so rebind them first: extended ends where they're extended to+ if (isElbowArrow(arrow)) {+ for (const startOrEnd of ["start", "end"] as const) {+ const binding =+ startOrEnd === "start" ? arrow.startBinding : arrow.endBinding;+ const bindableElement =+ binding && placedElementsMap.get(binding.elementId);+ if (!bindableElement || !isBindableElement(bindableElement)) {+ continue;+ }+ const extendedEnd = extendedEndPoints.get(startOrEnd);+ if (extendedEnd) {+ bindBindingElementToFixedPoint(+ arrow,+ bindableElement,+ startOrEnd,+ calculateFixedPointForNonElbowArrowBinding(+ arrow,+ bindableElement,+ startOrEnd,+ placedElementsMap,+ extendedEnd,+ ).fixedPoint,+ scene,+ );+ } else {+ bindBindingElement(+ arrow,+ bindableElement,+ binding.mode,+ startOrEnd,+ scene,+ DEFAULT_ZOOM,+ );+ }+ }+ }+ // once unbound, so elbow arrows aren't rerouted to what they were+ // bound to+ LinearElementEditor.movePoints(arrow, scene, extendedEnds);+ }+ for (const startOrEnd of ["start", "end"] as const) {+ // it was bound before what it's bound to was sized if that came later+ // (e.g. to fit its label), so its fixed point may be off (e.g. the+ // center of a 0x0 element): rebind it against the element as sized+ const binding =+ startOrEnd === "start" ? arrow.startBinding : arrow.endBinding;+ const bindableElement =+ binding && placedElementsMap.get(binding.elementId);+ if (bindableElement && isBindableElement(bindableElement)) {+ bindBindingElement(+ arrow,+ bindableElement,+ binding.mode,+ startOrEnd,+ scene,+ DEFAULT_ZOOM,+ );+ }+ }+ if (+ ![arrow.startBinding, arrow.endBinding].some(+ (binding) => binding && placedElementsMap.has(binding.elementId),+ )+ ) {+ continue;+ }+ // also wraps and measures its label, along it as placed. Nothing it's+ // bound to moved, so it keeps its midpoints where given, even if it's+ // bound to one element at both ends+ updateBoundArrow(+ arrow,+ scene,+ placedElementsMap,+ opts?.renderEnvironment,+ false,+ );++ const label = getBoundTextElement(arrow, placedElementsMap);+ if (!label) {+ continue;+ }+ unmeasuredArrowLabels.delete(label.id);+ // 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 labelPoint = labelPoints.get(label.id);+ if (labelPoint) {+ const labelPosition = LinearElementEditor.getPathParameterAtPoint(+ arrow,+ labelPoint,+ placedElementsMap,+ );+ if (labelPosition !== null) {+ scene.mutateElement(label, {+ labelPosition: clampLabelPositionOffEnds(+ arrow,+ label,+ labelPosition,+ placedElementsMap,+ ),+ });+ }+ }+ // the editor derives arrow labels' x/y from their arrows as it renders+ // them, but placing (and rewrapping) leaves them stale, and they're+ // returned as data, so store them where they're rendered+ scene.mutateElement(+ label,+ LinearElementEditor.getBoundTextElementPosition(+ arrow,+ label,+ placedElementsMap,+ ),+ );+ }+ // the labels of arrows not placed, along them as given+ for (const [arrow, label] of unmeasuredArrowLabels.values()) {+ redrawTextBoundingBox(label, arrow, scene, opts?.renderEnvironment);+ }+// 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.@@ -866,11 +1169,14 @@ export const convertToExcalidrawElements = (}Object.assign(elementInFrame, { frameId: frame.id });- elementInFrame?.boundElements?.forEach((boundElement) => {- const ele = elementStore.getElement(boundElement.id);+ [+ ...(elementInFrame.boundElements ?? []).map(({ id }) => id),+ ...(unboundArrowIds.get(elementInFrame.id) ?? []),+ ].forEach((boundElementId) => {+ const ele = elementStore.getElement(boundElementId);if (!ele) {throw new Error(- `Bound element with id ${boundElement.id} doesn't exist`,+ `Bound element with id ${boundElementId} doesn't exist`,);}Object.assign(ele, { frameId: frame.id });diff --git a/packages/element/tests/binding.test.tsx b/packages/element/tests/binding.test.tsxindex 4d2bd617af..04b03a6918 100644--- a/packages/element/tests/binding.test.tsx+++ b/packages/element/tests/binding.test.tsx@@ -23,6 +23,8 @@ import {getBindingGap,updateBoundElements,} from "../src/binding";+import { Scene } from "../src/Scene";+import { convertToExcalidrawElements } from "../src/transform";import { getAllMidpoints } from "../src/utils";import { getTransformHandles } from "../src/transformHandles";import {@@ -30,10 +32,12 @@ import {TEXT_EDITOR_SELECTOR,} from "../../excalidraw/tests/queries/dom";+import type { RenderEnvironment } from "../src/renderEnvironment";import type {ExcalidrawArrowElement,ExcalidrawBindableElement,ExcalidrawLinearElement,+ ExcalidrawTextElement,FixedPointBinding,NonDeleted,} from "../src/types";@@ -1101,3 +1105,49 @@ describe("binding to a point-like (sub-pixel) element", () => {},);});++describe("updateBoundElements with a render environment", () => {+ it("re-measures bound arrow labels with the given environment", () => {+ const renderEnvironment: RenderEnvironment = {+ createCanvas: () => document.createElement("canvas"),+ createImage: () => ({} as HTMLImageElement),+ textMetrics: { getLineWidth: (text) => text.length * 5 },+ };+ const scene = new Scene(+ 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: 100,+ y: 50,+ points: [pointFrom(0, 0), pointFrom(300, 0)],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: "aaaa bbbb cccc dddd eeee ffff" },+ },+ ],+ { regenerateIds: false, renderEnvironment },+ ),+ { skipValidation: true },+ );+ const label = scene+ .getNonDeletedElements()+ .find((element) => element.type === "text") as ExcalidrawTextElement;+ const rectB = scene.getElement(+ "B",+ ) as NonDeleted<ExcalidrawBindableElement>;++ expect(label.text).toBe("aaaa bbbb cccc dddd eeee ffff");+ expect(label.width).toBe(145);++ // as the drag does: move a bound shape, then its arrows (whose label the+ // default metrics would wrap after "dddd", 190px wide)+ scene.mutateElement(rectB, { x: rectB.x + 1 });+ updateBoundElements(rectB, scene, { renderEnvironment });++ expect(label.text).toBe("aaaa bbbb cccc dddd eeee ffff");+ expect(label.width).toBe(145);+ });+});diff --git a/packages/element/tests/linearElementEditor.test.tsx b/packages/element/tests/linearElementEditor.test.tsxindex acbf649d42..e5f8b8539d 100644--- a/packages/element/tests/linearElementEditor.test.tsx+++ b/packages/element/tests/linearElementEditor.test.tsx@@ -1517,7 +1517,7 @@ describe("Test Linear Elements", () => {expect({ width: container.width, height: container.height }).toMatchInlineSnapshot(`{- "height": 130,+ "height": 0,"width": 340,}`);@@ -2012,6 +2012,41 @@ describe("Test Linear Elements", () => {expect(line.points[line.points.length - 1][1]).toBe(-20);});+ it("should move midpoints with the element via the `moveMidPointsWithElement` option without storing it", () => {+ const line = createThreePointerLinearElement("arrow");+ const [origX, origY] = [line.x, line.y];+ const origMidPoint = line.points[1];+ const origEndPoint = line.points[2];++ act(() => {+ LinearElementEditor.movePoints(+ line,+ h.app.scene,+ new Map([+ [0, { point: pointFrom<LocalPoint>(10, 10) }],+ [+ 2,+ {+ point: pointFrom<LocalPoint>(+ origEndPoint[0] + 10,+ origEndPoint[1] + 10,+ ),+ },+ ],+ ]),+ undefined,+ { moveMidPointsWithElement: true },+ );+ });++ expect(line.x).toBe(origX + 10);+ expect(line.y).toBe(origY + 10);+ // local coords unchanged => the midpoint moved along with the element+ expect(line.points[1]).toEqual(origMidPoint);+ expect(line.points[2]).toEqual(origEndPoint);+ expect(line).not.toHaveProperty("moveMidPointsWithElement");+ });+it("should preserve original angle when dragging endpoint with SHIFT key", () => {createTwoPointerLinearElement("line");const line = h.elements[0] as ExcalidrawLinearElement;diff --git a/packages/excalidraw/actions/actionAlign.tsx b/packages/excalidraw/actions/actionAlign.tsxindex 83d2831087..5ffca9a184 100644--- a/packages/excalidraw/actions/actionAlign.tsx+++ b/packages/excalidraw/actions/actionAlign.tsx@@ -65,6 +65,7 @@ const alignSelectedElements = (alignment,app.scene,appState,+ app.renderEnvironment,);const updatedElementsMap = arrayToMap(updatedElements);diff --git a/packages/excalidraw/actions/actionDistribute.tsx b/packages/excalidraw/actions/actionDistribute.tsxindex 817f7ae4df..6d4e0615ed 100644--- a/packages/excalidraw/actions/actionDistribute.tsx+++ b/packages/excalidraw/actions/actionDistribute.tsx@@ -59,6 +59,7 @@ const distributeSelectedElements = (distribution,appState,app.scene,+ app.renderEnvironment,);const updatedElementsMap = arrayToMap(updatedElements);diff --git a/packages/excalidraw/actions/actionHistory.tsx b/packages/excalidraw/actions/actionHistory.tsxindex 203527d5c5..aadf64c70d 100644--- a/packages/excalidraw/actions/actionHistory.tsx+++ b/packages/excalidraw/actions/actionHistory.tsx@@ -74,7 +74,11 @@ export const createUndoAction: ActionCreator = (history) => ({viewMode: false,perform: (elements, appState, value, app) =>executeHistoryAction(app, appState, () =>- history.undo(arrayToMap(elements) as SceneElementsMap, appState),+ history.undo(+ arrayToMap(elements) as SceneElementsMap,+ appState,+ app.renderEnvironment,+ ),),keyTest: (event) =>event[KEYS.CTRL_OR_CMD] && matchKey(event, KEYS.Z) && !event.shiftKey,@@ -113,7 +117,11 @@ export const createRedoAction: ActionCreator = (history) => ({viewMode: false,perform: (elements, appState, __, app) =>executeHistoryAction(app, appState, () =>- history.redo(arrayToMap(elements) as SceneElementsMap, appState),+ history.redo(+ arrayToMap(elements) as SceneElementsMap,+ appState,+ app.renderEnvironment,+ ),),keyTest: (event) =>(event[KEYS.CTRL_OR_CMD] && event.shiftKey && matchKey(event, KEYS.Z)) ||diff --git a/packages/excalidraw/actions/actionProperties.tsx b/packages/excalidraw/actions/actionProperties.tsxindex 17297434fb..5666895a7c 100644--- a/packages/excalidraw/actions/actionProperties.tsx+++ b/packages/excalidraw/actions/actionProperties.tsx@@ -339,7 +339,9 @@ const changeFontSize = (includeBoundTextElement: true,}).forEach((element) => {if (isTextElement(element)) {- updateBoundElements(element, app.scene);+ updateBoundElements(element, app.scene, {+ renderEnvironment: app.renderEnvironment,+ });}});diff --git a/packages/excalidraw/actions/actionStyles.ts b/packages/excalidraw/actions/actionStyles.tsindex 2ec81bcbf3..1411631958 100644--- a/packages/excalidraw/actions/actionStyles.ts+++ b/packages/excalidraw/actions/actionStyles.ts@@ -225,7 +225,9 @@ export const actionPasteStyles = register({prev.x !== element.x ||prev.y !== element.y)) {- updateBoundElements(element, app.scene);+ updateBoundElements(element, app.scene, {+ renderEnvironment: app.renderEnvironment,+ });}}diff --git a/packages/excalidraw/actions/actionTextAutoResize.ts b/packages/excalidraw/actions/actionTextAutoResize.tsindex 70c980f53e..ff75e66297 100644--- a/packages/excalidraw/actions/actionTextAutoResize.ts+++ b/packages/excalidraw/actions/actionTextAutoResize.ts@@ -74,6 +74,7 @@ export const actionTextAutoResize = register({if (isNonDeletedElement(resized)) {updateBoundElements(resized, app.scene, {changedElements: new Map([[resized.id, resized]]),+ renderEnvironment: app.renderEnvironment,});}diff --git a/packages/excalidraw/components/App.duplicate.ts b/packages/excalidraw/components/App.duplicate.tsindex 88fd7ebf04..90f7ee2d26 100644--- a/packages/excalidraw/components/App.duplicate.ts+++ b/packages/excalidraw/components/App.duplicate.ts@@ -111,7 +111,11 @@ export class AppDuplicate {);return (- advanceDuplicatedListMarkers(duplicates, this.app.scene).length > 0+ advanceDuplicatedListMarkers(+ duplicates,+ this.app.scene,+ this.app.renderEnvironment,+ ).length > 0);});};@@ -224,10 +228,20 @@ export class AppDuplicate {return;}- applyListMarkerAdvances(advances, "prev", this.app.scene);+ applyListMarkerAdvances(+ advances,+ "prev",+ this.app.scene,+ this.app.renderEnvironment,+ );this.afterCommit(() => {- applyListMarkerAdvances(advances, "next", this.app.scene);+ applyListMarkerAdvances(+ advances,+ "next",+ this.app.scene,+ this.app.renderEnvironment,+ );editTextOnceCommitted();return true;});@@ -503,6 +517,7 @@ export class AppDuplicate {pointerDownState.hit.advancedListMarkers = advanceDuplicatedListMarkers(duplicatedElements,this.app.scene,+ this.app.renderEnvironment,);// (after advancing the list markers, which may resize the duplicates)@@ -518,7 +533,9 @@ export class AppDuplicate {isBindableElement(element) &&element.boundElements?.some((other) => other.type === "arrow")) {- updateBoundElements(element, this.app.scene);+ updateBoundElements(element, this.app.scene, {+ renderEnvironment: this.app.renderEnvironment,+ });}});diff --git a/packages/excalidraw/components/App.selectionTool.ts b/packages/excalidraw/components/App.selectionTool.tsindex b1ec916e84..da95743f71 100644--- a/packages/excalidraw/components/App.selectionTool.ts+++ b/packages/excalidraw/components/App.selectionTool.ts@@ -509,7 +509,9 @@ export class AppSelectionTool {),);- updateBoundElements(croppingElement, this.app.scene);+ updateBoundElements(croppingElement, this.app.scene, {+ renderEnvironment: this.app.renderEnvironment,+ });this.app.setState({isCropping: true,@@ -555,7 +557,9 @@ export class AppSelectionTool {if (updates) {this.app.store.scheduleCapture();this.app.scene.mutateElement(image, updates);- updateBoundElements(image, this.app.scene);+ updateBoundElements(image, this.app.scene, {+ renderEnvironment: this.app.renderEnvironment,+ });}return true;};@@ -991,6 +995,7 @@ export class AppSelectionTool {this.app.scene,snapOffset,event[KEYS.CTRL_OR_CMD] ? null : this.app.getEffectiveGridSize(),+ this.app.renderEnvironment,);}diff --git a/packages/excalidraw/components/App.text.ts b/packages/excalidraw/components/App.text.tsindex bce77ccb2c..fa25b2e318 100644--- a/packages/excalidraw/components/App.text.ts+++ b/packages/excalidraw/components/App.text.ts@@ -271,7 +271,9 @@ export class AppText {stickyContainer.id,);if (latestContainer) {- updateBoundElements(latestContainer, this.app.scene);+ updateBoundElements(latestContainer, this.app.scene, {+ renderEnvironment: this.app.renderEnvironment,+ });}}};@@ -294,7 +296,9 @@ export class AppText {onChange: withBatchedUpdates((nextOriginalText) => {updateElement(nextOriginalText, false);if (isNonDeletedElement(element)) {- updateBoundElements(element, this.app.scene);+ updateBoundElements(element, this.app.scene, {+ renderEnvironment: this.app.renderEnvironment,+ });}}),onSubmit: withBatchedUpdates(({ viaKeyboard, nextOriginalText }) => {diff --git a/packages/excalidraw/components/App.tsx b/packages/excalidraw/components/App.tsxindex 7e8164eea0..bf9bab2056 100644--- a/packages/excalidraw/components/App.tsx+++ b/packages/excalidraw/components/App.tsx@@ -5059,12 +5059,11 @@ class App extends React.Component<AppProps, AppState> {this.scene.getElementsMapIncludingDeleted(),) as SceneElementsMap;- return StoreDelta.applyTo(- aggregatedDelta,- nextElements,- nextAppState,- options,- );+ return StoreDelta.applyTo(aggregatedDelta, nextElements, nextAppState, {+ ...options,+ // labels re-laid out by the deltas are measured with the host's metrics+ renderEnvironment: options?.renderEnvironment ?? this.renderEnvironment,+ });};public mutateElement = <TElement extends Mutable<ExcalidrawElement>>(@@ -5479,6 +5478,7 @@ class App extends React.Component<AppProps, AppState> {updateBoundElements(element, this.scene, {simultaneouslyUpdated: selectedElements,+ renderEnvironment: this.renderEnvironment,});});diff --git a/packages/excalidraw/components/App.wrap.ts b/packages/excalidraw/components/App.wrap.tsindex b0b3ed9c60..b3c301850a 100644--- a/packages/excalidraw/components/App.wrap.ts+++ b/packages/excalidraw/components/App.wrap.ts@@ -240,7 +240,9 @@ export class AppWrap {({ id }) => !arrows.some((arrow) => arrow.id === id),),});- updateBoundElements(text, scene);+ updateBoundElements(text, scene, {+ renderEnvironment: this.app.renderEnvironment,+ });texts.push(text);}@@ -370,8 +372,10 @@ export class AppWrap {boundElements: null,...(isArrowContainer ? { angle: 0 as Radians } : null),});- redrawTextBoundingBox(text, container, scene);- updateBoundElements(container, scene);+ redrawTextBoundingBox(text, container, scene, this.app.renderEnvironment);+ updateBoundElements(container, scene, {+ renderEnvironment: this.app.renderEnvironment,+ });// the text may have changed layers sincenextElements = pushContainerBelowText(nextElements, container, text);diff --git a/packages/excalidraw/components/ConvertElementTypePopup.tsx b/packages/excalidraw/components/ConvertElementTypePopup.tsxindex 6c135ea4bc..88de719051 100644--- a/packages/excalidraw/components/ConvertElementTypePopup.tsx+++ b/packages/excalidraw/components/ConvertElementTypePopup.tsx@@ -487,7 +487,9 @@ export const convertElementTypes = (for (const element of Object.values(convertedElements)) {if (isBindableElement(element)) {reanchorBindingsToOutline(element, app.scene, app.state.zoom);- updateBindings(element, app.scene, app.state);+ updateBindings(element, app.scene, app.state, {+ renderEnvironment: app.renderEnvironment,+ });}const boundText = getBoundTextElement(diff --git a/packages/excalidraw/components/Stats/Angle.tsx b/packages/excalidraw/components/Stats/Angle.tsxindex 9b88a98dfc..44af920ed6 100644--- a/packages/excalidraw/components/Stats/Angle.tsx+++ b/packages/excalidraw/components/Stats/Angle.tsx@@ -49,7 +49,9 @@ const handleDegreeChange: DragInputCallbackType<AngleProps["property"]> = ({scene.mutateElement(latestElement, {angle: nextAngle,});- updateBindings(latestElement, scene, app.state);+ updateBindings(latestElement, scene, app.state, {+ renderEnvironment: app.renderEnvironment,+ });const boundTextElement = getBoundTextElement(latestElement, elementsMap);if (boundTextElement && !isArrowElement(latestElement)) {@@ -75,7 +77,9 @@ const handleDegreeChange: DragInputCallbackType<AngleProps["property"]> = ({scene.mutateElement(latestElement, {angle: nextAngle,});- updateBindings(latestElement, scene, app.state);+ updateBindings(latestElement, scene, app.state, {+ renderEnvironment: app.renderEnvironment,+ });const boundTextElement = getBoundTextElement(latestElement, elementsMap);if (boundTextElement && !isArrowElement(latestElement)) {diff --git a/packages/excalidraw/components/Stats/MultiDimension.tsx b/packages/excalidraw/components/Stats/MultiDimension.tsxindex 1d3d5325ff..8df541d091 100644--- a/packages/excalidraw/components/Stats/MultiDimension.tsx+++ b/packages/excalidraw/components/Stats/MultiDimension.tsx@@ -128,7 +128,7 @@ const resizeElementInGroup = ();if (boundTextElement) {const newFontSize = boundTextElement.fontSize * scale;- updateBoundElements(latestElement, scene);+ updateBoundElements(latestElement, scene, { renderEnvironment });const latestBoundTextElement = elementsMap.get(boundTextElement.id);if (latestBoundTextElement && isTextElement(latestBoundTextElement)) {scene.mutateElement(latestBoundTextElement, {diff --git a/packages/excalidraw/components/Stats/MultiPosition.tsx b/packages/excalidraw/components/Stats/MultiPosition.tsxindex 030e77694b..d7cdacd695 100644--- a/packages/excalidraw/components/Stats/MultiPosition.tsx+++ b/packages/excalidraw/components/Stats/MultiPosition.tsx@@ -11,7 +11,7 @@ import type {NonDeletedExcalidrawElement,} from "@excalidraw/element/types";-import type { Scene } from "@excalidraw/element";+import type { RenderEnvironment, Scene } from "@excalidraw/element";import StatsDragInput from "./DragInput";import {@@ -43,6 +43,7 @@ const moveElements = (originalElementsMap: ElementsMap,scene: Scene,appState: AppState,+ renderEnvironment: RenderEnvironment,) => {for (let i = 0; i < originalElements.length; i++) {const origElement = originalElements[i];@@ -71,6 +72,7 @@ const moveElements = (appState,originalElementsMap,false,+ renderEnvironment,);}};@@ -82,6 +84,7 @@ const moveGroupTo = (originalElementsMap: ElementsMap,scene: Scene,appState: AppState,+ renderEnvironment: RenderEnvironment,) => {const elementsMap = scene.getNonDeletedElementsMap();const [x1, y1, ,] = getCommonBounds(originalElements);@@ -117,6 +120,7 @@ const moveGroupTo = (appState,originalElementsMap,false,+ renderEnvironment,);}}@@ -162,6 +166,7 @@ const handlePositionChange: DragInputCallbackType<originalElementsMap,scene,app.state,+ app.renderEnvironment,);} else {const origElement = elementsInUnit[0]?.original;@@ -191,6 +196,7 @@ const handlePositionChange: DragInputCallbackType<app.state,originalElementsMap,false,+ app.renderEnvironment,);}}@@ -215,6 +221,7 @@ const handlePositionChange: DragInputCallbackType<originalElementsMap,scene,app.state,+ app.renderEnvironment,);scene.triggerUpdate();diff --git a/packages/excalidraw/components/Stats/Position.tsx b/packages/excalidraw/components/Stats/Position.tsxindex fde51de431..52c9e4058c 100644--- a/packages/excalidraw/components/Stats/Position.tsx+++ b/packages/excalidraw/components/Stats/Position.tsx@@ -137,6 +137,8 @@ const handlePositionChange: DragInputCallbackType<"x" | "y"> = ({scene,app.state,originalElementsMap,+ true,+ app.renderEnvironment,);return;}@@ -169,6 +171,8 @@ const handlePositionChange: DragInputCallbackType<"x" | "y"> = ({scene,app.state,originalElementsMap,+ true,+ app.renderEnvironment,);};diff --git a/packages/excalidraw/components/Stats/utils.ts b/packages/excalidraw/components/Stats/utils.tsindex 49b8405da4..48f8f5c9dc 100644--- a/packages/excalidraw/components/Stats/utils.ts+++ b/packages/excalidraw/components/Stats/utils.ts@@ -27,7 +27,7 @@ import type {NonDeletedExcalidrawElement,} from "@excalidraw/element/types";-import type { Scene } from "@excalidraw/element";+import type { RenderEnvironment, Scene } from "@excalidraw/element";import type { AppState } from "../../types";@@ -119,6 +119,8 @@ export const moveElement = (appState: AppState,originalElementsMap: ElementsMap,shouldInformMutation = true,+ /** measures the labels of the bound arrows the move moves */+ renderEnvironment?: RenderEnvironment,) => {if (isBindingElement(originalElement) &&@@ -167,7 +169,7 @@ export const moveElement = (},{ informMutation: shouldInformMutation, isDragging: false },);- updateBindings(latestElement, scene, appState);+ updateBindings(latestElement, scene, appState, { renderEnvironment });const boundTextElement = getBoundTextElement(originalElement,@@ -227,6 +229,7 @@ export const moveElement = ();updateBindings(latestChildElement, scene, appState, {simultaneouslyUpdated: getNonDeletedElements(originalChildren),+ renderEnvironment,});});}diff --git a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsxindex df2d936a30..971e329aa7 100644--- a/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx+++ b/packages/excalidraw/components/TTDDialog/MermaidToExcalidraw.tsx@@ -117,6 +117,7 @@ const MermaidToExcalidraw = ({setError,mermaidDefinition: deferredText,theme,+ renderEnvironment: app.renderEnvironment,});if (!result.success) {@@ -134,7 +135,7 @@ const MermaidToExcalidraw = ({doRender();debouncedSaveMermaidDefinition(deferredText);}- }, [deferredText, mermaidToExcalidrawLib, isActive, theme]);+ }, [deferredText, mermaidToExcalidrawLib, isActive, theme, app]);useEffect(() => {const flush = () => debouncedSaveMermaidDefinition.flush();diff --git a/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx b/packages/excalidraw/components/TTDDialog/TextToDiagram.tsxindex 177e396ab0..e3dd71de21 100644--- a/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx+++ b/packages/excalidraw/components/TTDDialog/TextToDiagram.tsx@@ -136,6 +136,7 @@ const TextToDiagramContent = ({setError,mermaidDefinition: mermaidContent,theme: app.state.theme,+ renderEnvironment: app.renderEnvironment,});if (result.success) {diff --git a/packages/excalidraw/components/TTDDialog/common.ts b/packages/excalidraw/components/TTDDialog/common.tsindex 6f59c0727b..2d07245c1e 100644--- a/packages/excalidraw/components/TTDDialog/common.ts+++ b/packages/excalidraw/components/TTDDialog/common.ts@@ -4,6 +4,7 @@ import { convertToExcalidrawElements } from "@excalidraw/element";import { exportScene } from "@excalidraw/utils";+import type { RenderEnvironment } from "@excalidraw/element";import type {NonDeletedExcalidrawElement,Theme,@@ -43,6 +44,7 @@ export const convertMermaidToExcalidraw = async ({setError,data,theme,+ renderEnvironment,}: {canvasRef: React.RefObject<HTMLDivElement | null>;mermaidToExcalidrawLib: MermaidToExcalidrawLibProps;@@ -53,6 +55,8 @@ export const convertMermaidToExcalidraw = async ({files: BinaryFiles | null;}>;theme: Theme;+ /** the host's environment (`app.renderEnvironment`), to measure labels with */+ renderEnvironment?: RenderEnvironment;}): Promise<{ success: true } | { success: false; error?: Error }> => {const canvasNode = canvasRef.current;const parent = canvasNode?.parentElement;@@ -96,6 +100,7 @@ export const convertMermaidToExcalidraw = async ({data.current = {elements: convertToExcalidrawElements(elements, {regenerateIds: true,+ renderEnvironment,}),files,};diff --git a/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts b/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.tsindex b444397af9..7d9648e02a 100644--- a/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts+++ b/packages/excalidraw/components/TTDDialog/hooks/useMermaidRenderer.ts@@ -4,6 +4,8 @@ import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";import { useAtom } from "../../../editor-jotai";+import { useApp } from "../../App";+import { chatHistoryAtom, errorAtom, showPreviewAtom } from "../TTDContext";import { convertMermaidToExcalidraw } from "../common";import { isValidMermaidSyntax } from "../utils/mermaidValidation";@@ -59,6 +61,7 @@ export const useMermaidRenderer = ({const hasErrorOffsetRef = useRef(false);const currentThrottleDelayRef = useRef(FAST_THROTTLE_DELAY);+ const app = useApp();const { theme } = useUIAppState();const renderMermaid = useCallback(@@ -85,6 +88,7 @@ export const useMermaidRenderer = ({setError,mermaidDefinition,theme,+ renderEnvironment: app.renderEnvironment,});const renderDuration = performance.now() - renderStartTime;@@ -98,7 +102,7 @@ export const useMermaidRenderer = ({isRenderingRef.current = false;return result.success;},- [canvasRef, mermaidToExcalidrawLib, setError, theme],+ [app, canvasRef, mermaidToExcalidrawLib, setError, theme],);const throttledRenderMermaid = useMemo(() => {diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.tsindex 55d1558ad8..51201b773c 100644--- a/packages/excalidraw/data/restore.ts+++ b/packages/excalidraw/data/restore.ts@@ -454,6 +454,8 @@ const restoreElementWithProperties = <boundElementIds?: readonly ExcalidrawElement["id"][];/** @deprecated */strokeSharpness?: StrokeRoundness;+ /** @deprecated `movePoints()` option wrongly persisted on linear elements */+ moveMidPointsWithElement?: boolean | null;},K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>,>(@@ -530,6 +532,8 @@ const restoreElementWithProperties = <// strip legacy props (migrated in previous steps)delete ret.strokeSharpness;delete ret.boundElementIds;+ // not an element prop, but used to leak onto linear elements+ delete ret.moveMidPointsWithElement;return ret;};diff --git a/packages/excalidraw/history.ts b/packages/excalidraw/history.tsindex 482065be45..d7c2834704 100644--- a/packages/excalidraw/history.ts+++ b/packages/excalidraw/history.ts@@ -6,7 +6,11 @@ import {StoreDelta,} from "@excalidraw/element";-import type { StoreSnapshot, Store } from "@excalidraw/element";+import type {+ RenderEnvironment,+ StoreSnapshot,+ Store,+} from "@excalidraw/element";import type { SceneElementsMap } from "@excalidraw/element/types";@@ -20,6 +24,8 @@ export class HistoryDelta extends StoreDelta {elements: SceneElementsMap,appState: AppState,snapshot: StoreSnapshot,+ /** measures the labels re-laid out after applying */+ renderEnvironment?: RenderEnvironment,): [SceneElementsMap, AppState, boolean] {const [nextElements, elementsContainVisibleChange] = this.elements.applyTo(elements,@@ -31,6 +37,7 @@ export class HistoryDelta extends StoreDelta {// approaching each undo / redo as a new user action{excludedProperties: new Set(["version", "versionNonce"]),+ renderEnvironment,},);@@ -136,21 +143,33 @@ export class History {);}- public undo(elements: SceneElementsMap, appState: AppState) {+ public undo(+ elements: SceneElementsMap,+ appState: AppState,+ /** measures the labels re-laid out after undoing (the host's, in the editor) */+ renderEnvironment?: RenderEnvironment,+ ) {return this.perform(elements,appState,() => History.pop(this.undoStack),(entry: HistoryDelta) => History.push(this.redoStack, entry),+ renderEnvironment,);}- public redo(elements: SceneElementsMap, appState: AppState) {+ public redo(+ elements: SceneElementsMap,+ appState: AppState,+ /** measures the labels re-laid out after redoing (the host's, in the editor) */+ renderEnvironment?: RenderEnvironment,+ ) {return this.perform(elements,appState,() => History.pop(this.redoStack),(entry: HistoryDelta) => History.push(this.undoStack, entry),+ renderEnvironment,);}@@ -159,6 +178,7 @@ export class History {appState: AppState,pop: () => HistoryDelta | null,push: (entry: HistoryDelta) => void,+ renderEnvironment: RenderEnvironment | undefined,): [SceneElementsMap, AppState] | void {try {let historyDelta = pop();@@ -179,7 +199,12 @@ export class History {while (historyDelta) {try {[nextElements, nextAppState, containsVisibleChange] =- historyDelta.applyTo(nextElements, nextAppState, prevSnapshot);+ historyDelta.applyTo(+ nextElements,+ nextAppState,+ prevSnapshot,+ renderEnvironment,+ );const prevElements = prevSnapshot.elements;const nextSnapshot = prevSnapshot.maybeClone(diff --git a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snapindex 9d628d37e1..878d3b4956 100644--- a/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap+++ b/packages/excalidraw/tests/__snapshots__/history.test.tsx.snap@@ -217,7 +217,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -240,7 +239,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 22,+ "version": 21,"width": "94.00000","x": 0,"y": 0,@@ -367,7 +366,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 21,+ "version": 20,"width": "88.00000","y": "7.20923",},@@ -399,7 +398,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 20,+ "version": 19,"width": "88.00000","y": "0.01000",},@@ -456,7 +455,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],],"startBinding": null,- "version": 22,+ "version": 21,"width": "94.00000","x": 0,"y": 0,@@ -481,7 +480,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 21,+ "version": 20,"width": "88.00000","x": 6,"y": "7.20923",@@ -863,7 +862,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -886,7 +884,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 25,+ "version": 24,"width": 100,"x": 150,"y": 0,@@ -955,7 +953,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 24,+ "version": 23,"width": 44,"y": "0.01000",},@@ -987,7 +985,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 23,+ "version": 22,"width": 100,"y": "0.01000",},@@ -1036,7 +1034,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],],"startBinding": null,- "version": 25,+ "version": 24,"width": 100,"x": 150,"y": 0,@@ -1061,7 +1059,7 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl],"mode": "orbit",},- "version": 24,+ "version": 23,"width": 44,"x": 250,"y": "0.01000",@@ -1387,7 +1385,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -1765,7 +1762,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -2495,7 +2491,6 @@ exports[`history > multiplayer undo/redo > conflicts in arrows and their bindabl"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -17673,7 +17668,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -17703,7 +17697,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -17756,7 +17750,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding],"mode": "orbit",},- "version": 10,+ "version": 9,},"inserted": {"endBinding": {@@ -18446,7 +18440,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -18476,7 +18469,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -18787,7 +18780,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeStyle": "solid","strokeWidth": 2,"type": "arrow",- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -19117,7 +19110,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -19147,7 +19139,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -19458,7 +19450,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeStyle": "solid","strokeWidth": 2,"type": "arrow",- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -19786,7 +19778,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -19816,7 +19807,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 10,+ "version": 9,"width": "88.00000","x": 6,"y": "0.01000",@@ -19885,7 +19876,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding],"mode": "orbit",},- "version": 10,+ "version": 9,},"inserted": {"endBinding": {@@ -20563,7 +20554,6 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[@@ -20593,7 +20583,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding"strokeWidth": 2,"type": "arrow","updated": 1,- "version": 11,+ "version": 10,"width": "88.00000","x": 6,"y": "0.01000",@@ -20673,7 +20663,7 @@ exports[`history > singleplayer undo/redo > should support bidirectional binding],"mode": "orbit",},- "version": 11,+ "version": 10,},"inserted": {"endBinding": null,diff --git a/packages/excalidraw/tests/__snapshots__/move.test.tsx.snap b/packages/excalidraw/tests/__snapshots__/move.test.tsx.snapindex 2e0179e098..66f4b31e75 100644--- a/packages/excalidraw/tests/__snapshots__/move.test.tsx.snap+++ b/packages/excalidraw/tests/__snapshots__/move.test.tsx.snap@@ -201,7 +201,6 @@ exports[`move element > rectangles with binding arrow 7`] = `"isDeleted": false,"link": null,"locked": false,- "moveMidPointsWithElement": false,"opacity": 100,"points": [[diff --git a/packages/excalidraw/tests/data/restore.test.ts b/packages/excalidraw/tests/data/restore.test.tsindex 9be3b80aef..ffd52a96eb 100644--- a/packages/excalidraw/tests/data/restore.test.ts+++ b/packages/excalidraw/tests/data/restore.test.ts@@ -580,6 +580,24 @@ describe("restoreElements", () => {expect(restoredArrow.endArrowhead).toBe("cardinality_one_or_many");});+ it("should strip the leaked `moveMidPointsWithElement` prop from linear elements", () => {+ const arrowElement = API.createElement({ type: "arrow" });+ const lineElement = API.createElement({ type: "line" });++ const restoredElements = restore.restoreElements(+ [+ { ...arrowElement, moveMidPointsWithElement: false } as any,+ { ...lineElement, moveMidPointsWithElement: true } as any,+ ],+ null,+ );++ expect(restoredElements).toHaveLength(2);+ for (const element of restoredElements) {+ expect(element).not.toHaveProperty("moveMidPointsWithElement");+ }+ });+it("should strip element if restore fails", () => {const rect1 = API.createElement({type: "rectangle",diff --git a/packages/excalidraw/tests/renderEnvironmentLabels.test.tsx b/packages/excalidraw/tests/renderEnvironmentLabels.test.tsxnew file mode 100644index 0000000000..b2fa0f0117--- /dev/null+++ b/packages/excalidraw/tests/renderEnvironmentLabels.test.tsx@@ -0,0 +1,228 @@+import React from "react";+import { KEYS, reseed } from "@excalidraw/common";+import { pointFrom } from "@excalidraw/math";++import type { RenderEnvironment } from "@excalidraw/element";+import type {+ ExcalidrawArrowElement,+ ExcalidrawTextElement,+} from "@excalidraw/element/types";++import { Excalidraw, convertToExcalidrawElements } from "../index";+import { actionAlignTop } from "../actions/actionAlign";++import { API } from "./helpers/api";+import { mockMermaidToExcalidraw } from "./helpers/mocks";+import { Keyboard, Pointer, UI } from "./helpers/ui";+import { fireEvent, render, unmountComponent, waitFor } from "./test-utils";++// Mock CodeMirror deps so the TTD dialog falls back to a <textarea>.+vi.mock("@codemirror/view", () => ({}));+vi.mock("@codemirror/state", () => ({}));+vi.mock("@codemirror/language", () => ({}));+vi.mock("@lezer/highlight", () => ({}));++unmountComponent();++const { h } = window;+const mouse = new Pointer("mouse");++const LABEL = "aaaa bbbb cccc dddd eeee ffff";++/**+ * A host whose text metrics differ from the default (canvas) ones, so that any+ * label re-measured without it wraps differently: with it, `LABEL` fits on one+ * line (145px); with the default metrics, it wraps after "dddd".+ */+const renderEnvironment: RenderEnvironment = {+ createCanvas: () => document.createElement("canvas"),+ createImage: () => document.createElement("img"),+ textMetrics: { getLineWidth: (text) => text.length * 5 },+};++const getLabel = () =>+ h.elements.find(+ (element) => element.type === "text",+ ) as ExcalidrawTextElement;+const getRect = (id: string) =>+ h.elements.find((element) => element.id === id)!;++const expectLabelMeasuredByHost = () => {+ const label = getLabel();+ expect(label.text).toBe(LABEL);+ expect(label.width).toBe(145);+};++describe("bound labels re-measured with the host's render environment", () => {+ beforeEach(async () => {+ reseed(7);+ mouse.reset();+ await render(+ <Excalidraw+ handleKeyboardGlobally={true}+ renderEnvironment={renderEnvironment}+ />,+ );+ API.setElements(+ convertToExcalidrawElements(+ [+ { type: "rectangle", id: "A", x: 0, y: 0, width: 100, height: 100 },+ {+ type: "rectangle",+ id: "B",+ x: 400,+ y: 10,+ width: 100,+ height: 100,+ },+ {+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 50,+ points: [pointFrom(0, 0), pointFrom(300, 0)],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: LABEL },+ },+ ],+ { regenerateIds: false, renderEnvironment },+ ),+ );+ expect(h.app.renderEnvironment).toBe(renderEnvironment);+ expectLabelMeasuredByHost();+ });++ const dragRectBBy1px = () => {+ const rectB = getRect("B");+ mouse.select(rectB);+ mouse.downAt(rectB.x + 50, rectB.y + 50);+ mouse.moveTo(rectB.x + 51, rectB.y + 50);+ mouse.upAt(rectB.x + 51, rectB.y + 50);+ };++ it("when dragging a bound shape", () => {+ dragRectBBy1px();++ expect(getRect("B").x).toBe(401);+ expectLabelMeasuredByHost();+ });++ it("when nudging a bound shape with the arrow keys", () => {+ mouse.select(getRect("B"));+ Keyboard.keyPress(KEYS.ARROW_RIGHT);++ expect(getRect("B").x).toBe(401);+ expectLabelMeasuredByHost();+ });++ it("when aligning bound shapes", () => {+ mouse.select([getRect("A"), getRect("B")]);+ API.executeAction(actionAlignTop);++ expect(getRect("B").y).toBe(0);+ expectLabelMeasuredByHost();+ });++ it("when undoing and redoing a drag of a bound shape", () => {+ dragRectBBy1px();+ expect(getRect("B").x).toBe(401);++ Keyboard.undo();+ expect(getRect("B").x).toBe(400);+ expectLabelMeasuredByHost();++ Keyboard.redo();+ expect(getRect("B").x).toBe(401);+ expectLabelMeasuredByHost();+ });++ it("when dragging an arrow's point", () => {+ const arrow = h.elements.find(+ (element) => element.id === "arrow",+ ) as ExcalidrawArrowElement;+ mouse.select(arrow);+ UI.clickTool("selection");+ const [x, y] = [arrow.x + arrow.points[0][0], arrow.y + arrow.points[0][1]];+ mouse.downAt(x, y);+ mouse.moveTo(x, y + 1);+ mouse.upAt(x, y + 1);++ expectLabelMeasuredByHost();+ });+});++describe("mermaid labels measured with the host's render environment", () => {+ beforeAll(() => {+ mockMermaidToExcalidraw({+ parseMermaidToExcalidraw: async () => ({+ elements: [+ {+ type: "rectangle",+ id: "A",+ x: 0,+ y: 0,+ width: 100,+ height: 40,+ // fits on one line with the host's metrics (70px), but wraps with+ // the default ones, growing the rectangle to fit two lines+ label: { text: "aaaa bbbb cccc" },+ },+ {+ type: "rectangle",+ id: "B",+ x: 400,+ y: 10,+ width: 100,+ height: 100,+ },+ {+ type: "arrow",+ id: "arrow",+ x: 100,+ y: 50,+ points: [+ [0, 0],+ [300, 0],+ ],+ start: { id: "A" },+ end: { id: "B" },+ label: { text: LABEL },+ },+ ],+ }),+ });+ });++ it("when inserting from the mermaid dialog", async () => {+ await render(+ <Excalidraw+ renderEnvironment={renderEnvironment}+ initialData={{+ appState: { openDialog: { name: "ttd", tab: "mermaid" } },+ }}+ />,+ );+ const dialog = document.querySelector(".ttd-dialog")!;+ await waitFor(() => expect(dialog.querySelector("canvas")).not.toBeNull());++ fireEvent.click(+ Array.from(dialog.querySelectorAll("button")).find(+ (button) => button.textContent === "Insert",+ )!,+ );++ const texts = h.elements.filter(+ (element): element is ExcalidrawTextElement => element.type === "text",+ );+ const rectLabel = texts.find((text) => text.originalText !== LABEL)!;+ const arrowLabel = texts.find((text) => text.originalText === LABEL)!;+ expect(rectLabel.text).toBe("aaaa bbbb cccc");+ expect(rectLabel.width).toBe(70);+ expect(+ h.elements.find((el) => el.id === rectLabel.containerId)!.height,+ ).toBe(40);+ expect(arrowLabel.text).toBe(LABEL);+ expect(arrowLabel.width).toBe(145);+ });+});diff --git a/packages/excalidraw/wysiwyg/textWysiwyg.tsx b/packages/excalidraw/wysiwyg/textWysiwyg.tsxindex 7022d012e1..233ccaba93 100644--- a/packages/excalidraw/wysiwyg/textWysiwyg.tsx+++ b/packages/excalidraw/wysiwyg/textWysiwyg.tsx@@ -421,7 +421,9 @@ export const textWysiwyg = ({app.scene.mutateElement(container, {height: targetContainerHeight,});- updateBoundElements(container, app.scene);+ updateBoundElements(container, app.scene, {+ renderEnvironment: app.renderEnvironment,+ });return;} else if (// autoshrink container height until original container height@@ -437,7 +439,9 @@ export const textWysiwyg = ({app.scene.mutateElement(container, {height: targetContainerHeight,});- updateBoundElements(container, app.scene);+ updateBoundElements(container, app.scene, {+ renderEnvironment: app.renderEnvironment,+ });} else {const { x, y } = computeBoundTextPosition(container,