From 808d068e18266ff9311809c23c19261fa0eb1014 Mon Sep 17 00:00:00 2001 From: David Luzar <5153846+dwelle@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:37:03 +0100 Subject: [PATCH] fix(packages/excalidraw): update arrow binding on skeleton transform (#12425) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(element): don't store movePoints() options on linear elements `LinearElementEditor.movePoints()` passed its `otherUpdates` straight into `mutateElement()`, so the `moveMidPointsWithElement` option ended up as a property on every arrow updated through its bindings. Only the bindings are element properties now. Claude Opus 5.5 (xhigh) * feat(element): position skeleton arrow labels with `label.labelPosition` `convertToExcalidrawElements()` always centered an arrow's label halfway along it. A skeleton arrow's `label` can now set `labelPosition` (0-1 along the arrow's path, as bound arrow labels store it), e.g. to keep a label where a layout engine placed it. Claude Opus 5.5 (xhigh) * fix(element): place skeleton bound arrows where binding puts them `convertToExcalidrawElements()` bound arrows to elements but kept the endpoints the skeleton gave, which aren't where Excalidraw puts the ends of bound arrows. The first time their bindings were updated (e.g. on undo/redo, or moving an element they're bound to) the arrows jumped there, e.g. by up to ~50px for arrows converted from Mermaid diagrams. Bound arrows are now placed where their bindings put them once all elements are converted. Claude Opus 5.5 (xhigh) * fix(element): measure and frame skeleton bound arrows as placed Placing bound arrows in `convertToExcalidrawElements()` re-measured their labels without the given render environment (`updateBoundElements()` now forwards one to `handleBindTextResize()`), and ran after frames were sized around them, so a label rewrapped by its shortened arrow could stick out of its frame. Arrows are now placed before frames are sized. Claude Opus 5.5 (xhigh) * fix(element): don't skip placing arrows listed by elements they aren't bound to Placing skeleton bound arrows skips arrows already updated through another element, but marked every arrow an element's `boundElements` listed as updated, though `updateBoundElements()` only updates those bound to it. A stale entry on an element placed earlier kept the arrow from being placed. Claude Opus 5.5 (xhigh) * fix(element): don't grow arrow height to fit rewrapped labels Review finding 1. The skeleton placement pass in convertToExcalidrawElements() calls updateBoundElements(), which calls handleBindTextResize() for arrows with labels. When the label rewraps taller than getBoundTextMaxHeight() allows (for arrows under 80px tall, that is the label's old height), it set the arrow's `height` from the text, leaving it inconsistent with its points. Reproduction steps: convertToExcalidrawElements() with rectangles A (0,0,100x20) and B (500,0,100x20), an arrow at (100,10) with points [[0,0],[400,0]] bound from A to B with label "aaaa bbbb cccc dddd eeee fff", and a frame containing all three. Placement shortens the arrow, so the label wraps to 2 lines (height 25 -> 50). Failure case: observed arrow height 130 (50 + 80 padding) with points [[0,0],[388,0]]; expected 0, as the points are horizontal. The stale height persists through updateScene() and inflates later getBoundTextMaxHeight() results. The same happens in the editor: dragging the end point of a horizontal labelled arrow (linearElementEditor.test.tsx) left it at height 130. Fix: handleBindTextResize() no longer grows arrow containers to fit their label, matching redrawTextBoundingBox(), which already exempts arrows: an arrow's size derives from its points, and its label is positioned along them rather than within its height. The label itself still rewraps. The linearElementEditor inline snapshot that recorded the bogus height of 130 for a horizontal arrow is updated to 0. * fix(element): keep skeleton arrow labels where labelPosition put them Review finding 2. A skeleton arrow's `label.labelPosition` is a fraction of the arrow's path as given (the only path a caller such as a layout engine knows), but the placement pass (updateBoundElements() on bound arrows) then shortens both ends by their binding gaps, and the stored fraction was resolved against the shortened path. Unless both ends were trimmed equally, the label no longer sat where the caller put it. Reproduction steps: convertToExcalidrawElements() with rectangles A (0,0,100x100) and B (400,0,100x100), and an arrow at (80,50) with points [[0,0],[250,0]] bound from A to B, label { text: "LABEL", labelPosition: 0.25 }. The fraction denotes x = 80 + 0.25 * 250 = 142.5 on the arrow as given. Placement moves the start to x = 106 (off A by the gap) and keeps the end at 330. Label center measured with LinearElementEditor.getBoundTextElementPosition(). Failure case: observed label center x = 162 (0.25 of the placed 106..330 path), expected 142.5: 19.5px off. Other inputs: arrow 60..440, labelPosition 0.8 rendered at 336.4 instead of 364 (-27.6px); arrow 100..400, labelPosition 0.25 at 178 instead of 175 (+3px). Fix: convertToExcalidrawElements() records the point a given labelPosition denotes on the arrow as given, and after placing bound arrows re-derives labelPosition as the parameter of the closest point on the placed path, so the label stays at that point. Default labels (no labelPosition given) are re-projected as an explicit 0.5 is: a layout engine that omits it (mermaid-to-excalidraw does, for every edge label) puts its labels at the midpoints of its routes as given. A point on a stretch placing trimmed off projects onto the arrow's end, so the label is kept as close to it as it can be while clear of the arrow's ends and arrowheads (clampLabelPositionOffEnds()). The closest-point projection is extracted from handleBoundTextDragging() into LinearElementEditor.getPathParameterAtPoint() and reused, unchanged. * fix(element): clamp skeleton arrow label positions as restore does Review finding 3. Reproduction steps: - Call `convertToExcalidrawElements` with arrows whose `label.labelPosition` is 5, -1, NaN, Infinity or -Infinity, both unbound and bound to two rectangles via `start`/`end`. - Read `labelPosition` off the resulting text elements. Failure case: - Unbound arrows: 5 -> stored 5, -1 -> stored -1 (expected 1 and 0, what `restore` would produce via `clamp(v, 0, 1)`). - Bound arrows: already 1 and 0, only because the placement pass re-derives `labelPosition` from the placed path. - NaN/Infinity/-Infinity: 0.5 on both, since `cloneJSON` of the skeleton turns them into `null`, which falls back to the default. Fix: `bindTextToContainer` now normalizes an arrow label's `labelPosition` the way `restore` does: finite values are clamped to [0,1], anything else falls back to DEFAULT_BOUND_TEXT_LABEL_POSITION. This covers every arrow label at creation, independent of the cloneJSON side effect and of whether the placement pass touches the arrow. The `labelPoints` lookup is unaffected, as `getPointAtPathParameter` already clamps and rejects non-finite values. * fix(element): store skeleton arrow label x/y where placed arrows put them Review finding 4. Placing bound arrows (updateBoundElements) moves and shortens them and rewraps their labels via handleBindTextResize, which sets the label's new width/height but, for arrow containers, never its x/y. The labels convertToExcalidrawElements returned kept the x/y computed for the arrow as given and the label as first wrapped. Reproduction: convertToExcalidrawElements with rectangles A(0,0,100x20) and B(500,0,100x20), and an arrow at (100,10) with points (0,0)-(400,0) bound A->B, labelled "aaaa bbbb cccc dddd eeee fff". Compare the label's stored x/y with LinearElementEditor.getBoundTextElementPosition on the returned elements. Failure case (observed vs expected, i.e. derived from the placed arrow): - in a frame, or not: x=160, y=-2.5 (240x50) vs x=180, y=-14.998 - with labelPosition 0.25: x=60, y=-2.5 vs x=80, y=-14.998 - short label "hi" (no rewrap): y=-2.5 vs y=-2.498 (the old 0.5px drift) Consumers reading label.x/y directly, rather than through getTextElementWithAccuratePosition, saw the box ~20px off. Fix: in transform.ts, in the loop after placement that re-derives labelPosition, also set every placed arrow's label x/y to LinearElementEditor.getBoundTextElementPosition, after labelPosition is final. All labels of placed arrows get it, given labelPosition or not. Not fixed in handleBindTextResize: the editor deliberately treats arrow label x/y as a cache. The renderer, bounds, hit testing and the WYSIWYG editor derive them from the arrow every time (see the doc comment on getTextElementWithAccuratePosition). Writing them there would change editor history/snapshots for no visible effect. convertToExcalidrawElements returns the elements as data, so its stored x/y should be right. Before this branch they were, up to 0.5px. Tests: a regression test checks that stored label x/y match the placed arrow, with and without labelPosition. It fails before the fix (160 vs 180). Two exact x/y assertions on "HELLO WORLD!!" labels became toBeCloseTo. Four snapshots change: label x/y now follow the placed arrows (sub-pixel in y, up to ~3px in x where placement is asymmetric), and version goes 3 -> 4 from the extra mutation. * fix(excalidraw): strip leaked moveMidPointsWithElement on restore `LinearElementEditor.movePoints()` used to spread its `otherUpdates` straight into `mutateElement()`, so the `moveMidPointsWithElement` option was persisted as a property on every arrow/line updated through its bindings. 25902dc3b stopped writing it, but scenes saved before that still carry it, and `restoreElementWithProperties()` keeps unknown keys (it spreads `...element` and only deletes `strokeSharpness` and `boundElementIds`), so the junk prop survived every load and kept travelling through saved files, collab payloads and history deltas. Reproduction steps: - Call `restoreElements()` on an arrow carrying `moveMidPointsWithElement: false` and a line carrying `moveMidPointsWithElement: true` (new test in restore.test.ts). Failure case: - Observed: the restored arrow still has `moveMidPointsWithElement: false` ("expected { id: 'id1', type: 'arrow', ... } to not have property "moveMidPointsWithElement"", received `false`). - Expected: the prop is not an element property and is dropped. Fix: - Delete `moveMidPointsWithElement` alongside the other stripped legacy props in `restoreElementWithProperties()`, and type it as a deprecated input prop there. History: the leak was introduced by c141960ad ("feat: Non-elbow arrow snapping and behavior changes (#9670)"), merged to master on 2025-11-25, and it is still present on master. It is not in any npm release tag (v0.18.0, v0.18.1), but it shipped via master builds (excalidraw.com and `@next` prereleases) for ~11 months, so real scenes carry the prop. Review finding 5. * refactor(element): pass moveMidPointsWithElement as a movePoints option Review finding 6. Reproduction / evidence: `LinearElementEditor.movePoints()` took `moveMidPointsWithElement` in its `otherUpdates` argument (typed next to `startBinding`/`endBinding`), which is the bag of element updates forwarded to `_updatePoints()` and from there into `scene.mutateElement()`. Callers: - `updateBoundElements()` (binding.ts) passed `{ moveMidPointsWithElement: }` as `otherUpdates` - the only caller setting a real value. - `LinearElementEditor` point dragging (two call sites) forwarded `updates?.moveMidPointsWithElement` from `PointMoveOtherUpdates`, but `pointDraggingUpdates()` never sets that field, so it was always undefined there. Before 25902dc3b this put `moveMidPointsWithElement: false/true` on every arrow updated through its bindings (and bumped its version). 25902dc3b fixed it by copying only `startBinding`/`endBinding` out of `otherUpdates` in the non-elbow branch of `_updatePoints()`. Failure case: `otherUpdates` still mixed a behaviour flag with element properties, so the filter in `_updatePoints()` had to know about every non-property key. Any new option added to `otherUpdates` the same way would be silently persisted on linear elements (and saved to scenes) unless the filter was updated too. Fix: move `moveMidPointsWithElement` into `movePoints()`'s existing `options` parameter, next to `isBindingEnabled` / `isMidpointSnappingEnabled`, and drop it from `otherUpdates` and from `PointMoveOtherUpdates` (along with the dead forwarding at the two drag call sites). `otherUpdates` now only holds element properties, so the non-elbow branch of `_updatePoints()` spreads it directly again, as on master; `mutateElement()` skips undefined values, so explicitly undefined bindings remain no-ops. The elbow branch's binding filtering is untouched. Behaviour is unchanged (no snapshot changes). Added a test that the option still keeps midpoints moving with the element and isn't stored on it. * refactor(element): place skeleton bound arrows once each, per arrow Review finding 8. The placement pass in `convertToExcalidrawElements` simulated moving every bindable element (`updateBoundElements` per bindable) and repurposed `simultaneouslyUpdated` as an "already placed" ledger (a fresh copy per call to dodge the id-set cache), then re-collected the arrows each call touched for the label loop. Its correctness hinged on `updateBoundElements` internals: updating both ends from either one, the `doesNeedUpdate` stale `boundElements` filter, and the array-identity id cache. It already broke once (fdc8262d5). Reproduction / evidence: a scratch vitest dumped the output (minus seeds, nonces and timestamps, versions kept) of `convertToExcalidrawElements` for arrows bound across two shapes, to the same shape at both ends (2- and 4-point), elbow arrows (one and two ends bound), arrows in frames, six arrows on one labelled hub, text ends with ids referenced before the elements, and multi-point arrows, and spied on `movePoints`. Every bound arrow was placed exactly once. Failure case: none found. Skeleton bindings all go through `applyBinding`, which always lists the arrow on the bindable, so the ledger never skipped or double-placed an arrow. This is a maintainability fix. Fix: extract the per-arrow body of `updateBoundElements`' visitor into an exported `updateBoundArrow` (`updateBoundPoint` for each binding, then `movePoints` with `moveMidPointsWithElement` for arrows bound to one element at both ends, then `handleBindTextResize`), and call it from `updateBoundElements`. Dropped the visitor's per-binding `changedElement` check: after `doesNeedUpdate`, one end is always bound to `changedElement`, so it always held. The transform pass now iterates the arrows bound to elements present and places each once, re-deriving its label's `labelPosition` and x/y in the same loop. No ledger, no copies of it, no per-bindable calls. Outputs of the scratch dump, versions included, are byte-identical before and after; all existing tests and snapshots pass unchanged. * fix(element): don't nudge skeleton arrow ends by 0.5px bindLinearElementToElement() moved every skeleton arrow's start 0.5px towards its end and its end 0.5px towards its start, "so bindings don't overlap with start/end bound element coordinates" (#7195). The placement pass now re-places every bound end with updateBoundArrow(), which puts it off the bound element by the binding gap, so for bound ends the nudge was dead work (a clone, nudge and normalize that's overwritten). It only still had an effect on ends nothing re-places: the unbound end of half-bound arrows, and both ends of unbound arrows (including those whose start/end reference missing ids, which bind nothing). Reproduction (convertToExcalidrawElements, regenerateIds: false): - fully bound: rect A (0,0,100x100), rect B (400,0,100x100), arrow at (100,50) points [0,0]->[300,0], start A, end B - half bound: rect A, arrow at (100,50) points [0,0]->[300,100], start A - half bound: rect B, arrow at (100,50) points [0,0]->[300,0], end B - start: { id: "nope" } (missing), and an arrow with no start/end, both at (100,50) points [0,0]->[300,0] Failure case (observed -> expected): - fully bound: x 106, points [0,0]->[288,0], version 5 both with and without the nudge (it's fully overwritten) - half bound (start): unbound end at (399.5, 149.5) -> (400, 150) - half bound (end): unbound start at x 100.5 -> 100 - missing ref / unbound: x 100.5, points [0,0]->[299,0] while width stays 300 (stale, getNormalizeElementPointsAndCoords() doesn't update it) -> x 100, points [0,0]->[300,0], width 300 Fix: remove the nudge (and the single point early return that only guarded it), so ends are either placed by their bindings or kept where the skeleton puts them. Bound ends can't be left unplaced: the bound elements are always added to the element store, and updateBoundPoint() only skips degenerate arrows the nudge didn't change either. Snapshot changes: the unbound arrows in "should transform linear elements" and "should transform to labelled arrows when label provided for arrows" now keep x as given (100/450 instead of 100.5/450.5) and points spanning their width ([0,0]->[100,0] instead of [99,0]). Their labels don't move (the arrow midpoints are unchanged). The "should bind arrows to existing elements if ids are correct" assertion, whose ids are missing and so bind nothing, now expects x 255 as given (was 255.5). Adds a regression test that a half-bound arrow's unbound end and an unbound arrow stay where the skeleton puts them. Review finding 9. * perf(element): measure skeleton arrow labels once, as placed Review finding 11. `bindTextToContainer` ran `redrawTextBoundingBox` on every label, so an arrow's label was wrapped and measured against the arrow as given, then the placement pass (`updateBoundArrow` -> `handleBindTextResize`) wrapped and measured it again against the arrow shortened by its binding gaps, always throwing the first result away. Reproduction: a scratch vitest mocked `wrapText` / `measureText` with counters and converted two shapes and a 400px arrow bound to both with the label "aaaa bbbb cccc dddd eeee fff". Failure case: observed wrapText x2 (maxWidth 280, then 271.6) and measureText x3 (newTextElement's unwrapped measurement, the discarded redraw, the placed rewrap); expected wrapText x1, measureText x2. Six labelled arrows on one shape: wrapText 13, measureText 20 (now 7 / 14). Unbound labelled arrows were already measured once (wrap 1 / measure 2). Fix: `bindTextToContainer` no longer measures arrow labels; the transform records them, the placement pass drops each label `updateBoundArrow` just measured, and the labels left (of arrows not placed) are measured after it with `redrawTextBoundingBox`, as before. Nothing between creating a label and the pass reads its size: binding only sets `startBinding` / `endBinding` (no points), `labelPoints` is still taken on the input arrow, and for arrow containers `handleBindTextResize` ignores the old label height. Measuring the leftovers after the pass, rather than predicting at creation which arrows get placed, means no label can go unmeasured. A scratch dump of 18 scenarios (bound / one end / same shape both ends / elbow / created and text ends / missing end id / ids before data / frame / single point / autoResize: false / labelPosition in and out of range / unbound / hub of six / shape labels) is identical before and after (seeds, nonces and timestamps stripped, versions kept), except the label `version` of placed arrows, one lower for the dropped mutation; the 4 snapshot changes are exactly that. Added a test asserting the wrap / measure counts for a bound and an unbound labelled arrow (fails before: 3 wraps vs 2). * fix(editor): re-measure bound labels with the host's render environment Review finding 12. The finding: the `renderEnvironment` option this branch added to `updateBoundElements` (a9b2d2878) was passed only by the transform, and since e0f198c15 not even by that (it calls `updateBoundArrow` directly), so the option was dead while documenting that it "measures the labels of the updated arrows". Meanwhile every editor path re-measured bound labels with the default environment, ignoring the host's `` (its custom `textMetrics`), so a label laid out with the host's metrics re-wrapped the first time its arrow was touched. The re-wrap itself predates this branch: master's `updateBoundElements` never took an environment and called `handleBindTextResize(element, scene, false)`, as `LinearElementEditor`'s point drag still did. Rather than drop the dead option, this wires it (and the other label-measuring editor paths) to the host's environment. Reproduction: convert two rectangles A, B and an arrow bound to both, labelled "aaaa bbbb cccc dddd eeee ffff", with `convertToExcalidrawElements(..., { renderEnvironment })`, whose `textMetrics.getLineWidth` is `text.length * 5`. Move B by 1px and call `updateBoundElements(B, scene)` as the drag path does. In the editor: render `` with the same scene and drag or arrow-key nudge B, align A and B, undo/redo the drag, or drag the arrow's point. Failure case (this branch and master alike): observed: "aaaa bbbb cccc dddd eeee ffff", width 145, becomes "aaaa bbbb cccc dddd\neeee ffff", width 190 expected: unchanged, "aaaa bbbb cccc dddd eeee ffff", width 145 Cause: no editor caller passed `updateBoundElements` an environment, so it called `updateBoundArrow` without one; `ElementsDelta`'s redraw, `LinearElementEditor`'s point drag and `listMarker`'s re-numbering likewise measured without one. Fix: optional `renderEnvironment` threaded the way resize already does it (a trailing param, or an option where the function takes an options bag): - `updateBoundElements`: its existing option is now passed by the editor (doc comment updated); `updateBindings` gains the same option and forwards it. Both pass it to `updateBoundArrow`. - drag: `dragSelectedElements` (new trailing param), from the selection tool. - arrow-key nudge (App.tsx). - align / distribute: `alignElements` / `distributeElements` (new trailing param), from their actions. - rotate/resize: the `updateBoundElements` calls in `transformElements`, `rotateMultipleElements`, `resizeSingleElement`, `resizeMultipleElements` now pass the environment they already had. - sticky notes: `updateStickyNoteLayout` passes its `renderEnvironment` on to its bound-arrow pass. - undo/redo: `ApplyToOptions.renderEnvironment` reaches `ElementsDelta.redrawElements` (both the bound-text redraw and the bound-arrow pass); `History.undo/redo` and `HistoryDelta.applyTo` take it, the history actions pass `app.renderEnvironment`, and `App.applyDeltas` defaults to it. - `LinearElementEditor` point drag: `handleBindTextResize` gets `app.renderEnvironment`. - list-marker re-numbering on duplicate (`advanceDuplicatedListMarkers`, `applyListMarkerAdvances`, new trailing param): both its label redraw and its free-text refresh. - the remaining editor callers of `updateBoundElements` / `updateBindings`, each of which can move a labelled arrow bound to the element: text editing (App.text, textWysiwyg), duplicate, crop/uncrop, wrap/unwrap (also its `redrawTextBoundingBox`), font/style/auto-resize actions, element type conversion, and the Stats position/angle/dimension inputs (`moveElement` gets a trailing param). Left alone: - `updateBindings`' arrow branch (`updateArrowBindings`): it only rebinds the arrow's ends and measures no label. - `transform.ts`: already measured with its environment (via `updateBoundArrow`). - callers that already passed `app.renderEnvironment` to `redrawTextBoundingBox` / `handleBindTextResize` (resize, Stats font size, font/bound-text actions, textWysiwyg submit, type conversion). - `updateBoundElements` re-measures only arrow labels (its visitor skips non-arrows), so no non-arrow container label path needed changing there. - free-text measurement helpers called directly (`measureText`, `wrapText`, `refreshTextDimensions`, ...) outside these bound-label paths: not part of this finding. Without the prop, `app.renderEnvironment` is the owner-window environment with no `textMetrics`, so measurement still falls back to the global provider or a canvas; single-window behaviour is unchanged (no snapshot changes). All new params are optional, so external callers are unaffected. Tests: a direct `updateBoundElements` test (packages/element) and editor tests rendering `` for drag, nudge, align, undo/redo and arrow point drag; each fails without its path's change. * refactor(element): build one scene in skeleton conversion, resync it convertToExcalidrawElements built a temp `scene` from the element store before labels and the elements skeleton arrows bind to were created, and then a second `boundScene` from the completed store for the bound-arrow placement pass, so the function held two scenes over overlapping element objects (Review finding 13). Evidence that the divergence produces no wrong output: the early scene is only used to measure non-arrow container labels (the container and label are passed directly; the sticky fit gets its label explicitly) and by bindBindingElement (geometry from the arrow and the element passed in; the map is only consulted for a text's container, and containers are always in the snapshot). This was already so on master, where the same snapshot scene was used the same way. To check, the scene was temporarily resynced (replaceAllElements) after every store addition, including before each bindBindingElement, and outputs were diffed against the current code (reseeded, ids canonicalized) for created rectangle/ellipse/diamond/text ends, elbow arrows, existing ids bound by two arrows (copied twice), text ends, a labelled sticky note, a frame around them, and an arrow label (given its own id) used as another arrow's start: all identical, and the full suite passed in that mode. So this is a maintainability fix: drop `boundScene` and resync the one scene with replaceAllElements once the store is complete, which is what `new Scene(...)` did. Outputs, snapshots and versions are unchanged. * fix(element): place skeleton arrows' created end shapes along the arrow `convertToExcalidrawElements` creates a rectangle/ellipse/diamond/text for a skeleton arrow's `start`/`end` given by `type` (no id), and placed it as if every arrow ran left to right: the start shape left of the arrow's `x`, the end shape right of `x + width`, both centered on the arrow's `y`. For any other direction the shape isn't where the arrow starts or ends, so the arrow is bound to a shape it doesn't reach, and the placement pass (e0f198c15) then moves its ends to where those bindings put them. Reproduction: an arrow at (0,0) with `start: { type: "rectangle" }`, `end: { type: "ellipse" }` and - "diagonal": points [0,0]->[100,100] - "vertical": points [0,0]->[0,200] - "right-to-left": points [0,0]->[-200,0] or `end: { type: "text", text: "end" }` on the diagonal one. Failure case (HEAD): the shapes are at (-100,-50) and (100,-50) whatever the direction, and the ends are bound at fixedPoints the editor can't create, outside the shapes: - "diagonal": ellipse at (100,-50), the arrow ends at (100,100): end bound at fixedPoint [0,1.5]. - "vertical": end bound at [0,2.5], and the start is placed at y=56, as the arrow runs down the rectangle's edge. - "right-to-left": ellipse at x=200, on the wrong side: end bound at [-4,0.5001], and the start is placed at x=-106, on the far side of the rectangle the arrow passes through. - the text end is bound at [0,4.5] the same way. Expected: the shapes at the arrow's start/end, the arrow pointing into them, both ends bound on their outlines and placed off them by the binding gap. Fix: new `getArrowEndShapePosition` centers the shape on the arrow's first/last segment as extended past the end, at the distance from its center to its outline (rectangle/text box, ellipse or diamond) in that direction, so the end lies on its outline. Explicit `x`/`y` still win, and an existing end text still keeps its x. Left-to-right arrows are placed as before. Other directions change, e.g. the 300x300 start rectangle of the 395x35 arrow in "should bind arrows to existing shapes when start / end provided with ids" moves up 13.3px, onto the arrow's line (snapshot updated). * fix(element): unbind unreachable skeleton arrow ends, rebind the rest `convertToExcalidrawElements` binds skeleton arrows to their `start`/`end` elements while it is still creating elements, and the placement pass (e0f198c15) then places every bound end where its binding puts it. Two kinds of bindings made at conversion time are wrong, and placing the arrows exposes them. 1. Ends given beyond the binding area of their element A layout engine (e.g. mermaid's sequence diagrams, whose messages are bound to the participants' headers but drawn far below them) can bind an end the user could never bind in the editor. Its fixedPoint lies well outside the element, and `normalizeFixedPoint` clamps it, so the binding can't hold the end where it was given. Reproduction: rectangles A (0,0 100x20) and B (500,0 100x20). - "half-far": an arrow at (100,10) with points [0,0]->[450,490], start A, end B, so its end is given at (550,500), far below B. - "beyond": an arrow at (50,40) with points [0,0]->[500,0], start A, end B, 20px below both, so beyond binding distance. Failure case (HEAD): - "half-far": end bound to B at fixedPoint [0.5001,10]. Placing moves the end from the given (550,500) to (550,200). - "beyond": both ends bound at fixedPoint [0.5001,2]. That's a binding the editor can't create, and it moves the arrow onto the headers the first time A or B is moved. Expected: ends beyond the binding area are left unbound where given. Ends within it stay bound. Fix: new `isPointInBindingArea` (collision.ts) checks whether a point is inside an element or within binding distance of its outline. `isEndBoundBeyondBindingArea` (binding.ts) applies it to an arrow's bound end. Before placing, the pass unbinds every end beyond its element's binding area (`unbindBindingElement`, which also drops the arrow from the element's `boundElements`). An arrow with no binding left isn't placed and keeps its geometry as given. The check ignores frame clipping (`getBindingCandidates` still skips the clipped parts of frame children): frames are sized around their children only at the end of the conversion, so an element given with a `frameId` would be checked against a 0x0 frame, and every end bound to it would be beyond reach. Arrows unbound from an element are still framed with it, as the frame pass frames what is bound to a frame's children (through their `boundElements`, which no longer list them). An end that just falls short of its element is extended onto it instead (`extendBoundEndOntoElement`, binding.ts): its end segment is extended past the end by the segment's length, at least 100px, and if that reaches the element, the end is moved to where it does, off the element by the binding gap, and stays bound. This keeps bindings a generator meant to make, but drew arrows slightly too short for. Reproduction: rectangle B (500,0 100x20), an arrow at (150,10) with points [0,0]->[250,0], end B, so its end is given 100px short of B. Expected: end bound to B, moved to (500 - binding gap, 10). 2. Ends bound before their element is sized A rectangle/ellipse/diamond with a label and no width/height is created 0x0 and sized to fit its label only when its label is bound. That happens in the same pass that binds arrows, in skeleton order. An arrow listed before the element therefore binds to a 0x0 element, and `calculateFixedPointForNonElbowArrowBinding` binds ends on elements smaller than MIN_BINDABLE_SIZE to their center. Nothing recomputes the binding once the element is sized, so the placement pass re-aims the end at the center, and the result depends on element order. Reproduction: an arrow at (100,50) with points [0,0]->[300,0], end bound to B, where B is a rectangle at (400,25) with label "B" and no size (sized to 20x35). Failure case (HEAD): arrow listed first: endBinding.fixedPoint [0.5001,0.5001] (center), points [[0,0],[294,-7.11]] (tilted) B listed first: endBinding.fixedPoint [0,0.714] (left edge), points [[0,0],[294,0]] (straight) Expected: the same in either order, the "B listed first" result. Fix: the pass rebinds each end that is still bound (`bindBindingElement`, keeping its mode) against its element as sized. For elements whose size didn't change after binding, this gives the same binding as before. Signed-off-by: Mark Tolmacs * fix(editor): convert TTD dialog diagrams with the host's render environment Review finding 7. The text-to-diagram dialog (the Mermaid tab, and the AI chat's preview and insert) converted mermaid's skeletons with `convertToExcalidrawElements` without the host's `renderEnvironment`, while pasting a mermaid definition (App.clipboard) passes `app.renderEnvironment`. So with a host's custom `textMetrics`, every label in the dialog's conversion, container and arrow labels alike, was measured with the default (canvas) metrics. The gap predates this branch: d3a9c2a19 added the option and passed it from the paste path, but not from the dialog. Reproduction: render ``, whose `textMetrics.getLineWidth` is `text.length * 5`, open the Mermaid dialog and insert a diagram with a 100x40 rectangle labelled "aaaa bbbb cccc", and an arrow labelled "aaaa bbbb cccc dddd eeee ffff" bound to it. Failure case: preview: both labels wrapped by the default metrics ("aaaa bbbb\ncccc", "aaaa bbbb cccc dddd\neeee ffff"), and the rectangle grown to height 60 to fit two lines inserted: `addElementsFromPasteOrLibrary` redraws the labels with the host's environment, so they end up on one line, but the rectangle stays 60 high, around a one-line label Expected: as when pasting the same definition: one-line labels (70px and 145px wide) in the preview and the scene, and the rectangle 40 high. Fix: `convertMermaidToExcalidraw` takes an optional `renderEnvironment` and passes it to `convertToExcalidrawElements`. Its three callers pass `app.renderEnvironment`: the Mermaid tab's preview (whose result is what it inserts), and the AI chat's preview (`useMermaidRenderer`, now using `useApp`) and insert (`TextToDiagram`). Left alone: `exportScene`, which renders the preview, takes no environment; it draws already measured elements, so the preview's layout now matches the inserted one. Without the prop, `app.renderEnvironment` has no `textMetrics`, so measurement falls back as before (no snapshot changes). Tests: inserting from the Mermaid dialog under a host environment (renderEnvironmentLabels.test.tsx); the rectangle's height fails without the fix. * fix(element): decide skeleton arrow end bindings before moving either end When placing skeleton arrows, each end bound beyond its element's binding area is either extended onto the element (if it just falls short) or unbound. 61255ad73 did this one end at a time: start first, then end. For elbow arrows, extending the start goes through `movePoints`, which reroutes the whole arrow from both its bindings. That moved the still-bound end onto its element before it was checked, so it was kept bound. The result depended on which end was the start. Reproduction: rectangles A (0,0 100x20) and B (500,0 100x20), and an elbow arrow (`elbowed: true`) [0,0]→[400,0]→[400,490] at (150,10), bound from A to B. Its start falls 50px short of A, and its end is at (550,500), far below B. Failure case: A→B: start extended onto A and bound, end rerouted to about (550,26) just under B, and left bound to B B→A (same arrow reversed): end extended onto A and bound, start left at (550,500) and unbound Expected: both directions as B→A: the A end extended and bound, the B end left where given and unbound. Fix: `extendBoundEndOntoElement` becomes `getBoundEndExtension`, which only returns where the end would be extended to and moves nothing. The skeleton conversion now checks both ends against the arrow as given. It unbinds the unreachable ends first, so the reroute doesn't take them along, then applies every extension in one `movePoints` call, then rebinds as before. Only elbow arrows were affected: moving one end of a non-elbow arrow leaves its other end in place. Mermaid's converter doesn't produce elbow arrows, so this needs hand-written or LLM-generated skeletons. Signed-off-by: Mark Tolmacs * fix(element): rebind elbow skeleton arrows before extending their ends The placement pass (61255ad73, 2fe86fe7f) extends bound ends that just fall short of their elements onto them with one `movePoints` call. Only after that does it rebind each end against its element as sized. For elbow arrows, `movePoints` reroutes the whole arrow from both its bindings. A binding made before its element was sized (a labelled shape with no width/height, listed after the arrow, is still 0x0 when the arrow binds to it) points at the element's center. The reroute then routes the end around the element to that center, and the rebind that follows keeps the side the end was rerouted to. The result depended on element order. Reproduction: rectangle A (0,25 100x50), rectangle B at (400,25) with label "B" and no size (sized to 20x35), and an elbow arrow (`elbowed: true`) at (150,50) with points [0,0]->[250,0], bound from A to B. Its start falls 50px short of A, so it gets extended. Failure case: [A, B, arrow]: endBinding.fixedPoint [-0.3,0.714] (B's left side), points [[0,0],[288,0]] [A, arrow, B]: endBinding.fixedPoint [1.3,0.5] (B's right side), six points running past B to x=466 and back into its right side at (426,42.5) The same happens when the extended end is the one bound to B (the arrow at (106,50) with points [0,0]->[224,0], ending 70px short of B), and when both ends are extended. Expected: the same in either order, the [A, B, arrow] result. Fix: before extending an elbow arrow's ends, rebind both of them against their elements as sized: an end being extended at the point it's extended to (`calculateFixedPointForNonElbowArrowBinding` with that point as the focus point, then `bindBindingElementToFixedPoint`), and any other end where it is (`bindBindingElement`). Then extend, and rebind as before. Rebinding before the move only the ends not being extended isn't enough: an extended end would still be rerouted to its element's center. Neither is rebinding only after the move, because by then the reroute has already put the end on the wrong side. Only elbow arrows were affected: moving one end of a non-elbow arrow doesn't reroute it, so the rebind after the move already corrects it. Tests: "should route elbow arrows extended onto elements as to elements sized to fit their labels after them as to those before them" (transform.test.ts), covering the start and the end extended. It fails without the fix (`expected 1.3 to be less than 0`). Signed-off-by: Mark Tolmacs * fix(element): clamp skeleton arrow labels only off the ends they're trimmed off ee5d10684 keeps skeleton arrow labels where `labelPosition` put them on the arrow as given, by projecting that point onto the arrow as placed. A point on a stretch placing trimmed off projects onto the arrow's end, so `clampLabelPositionOffEnds` keeps the label clear of the end and its arrowhead. But the clamp ran on the label of every bound arrow, wherever its point projected. Labels on the arrow as placed were moved off its ends too, which unbound (unplaced) arrows don't do. Reproduction: rectangles A (0,0 100x100) and B (192,0 100x100), and an arrow at (106,50) with points [0,0]->[80,0], bound from A to B. Its ends are already off A and B by the binding gap, so placing it trims nothing. Label widths are as measured in the tests. Failure case: label "LABEL" (50px), no labelPosition: labelPosition 0.375, center x=136, 10px toward the start, off the end arrowhead label "LABELX" (60px), no labelPosition: labelPosition 0.5, center x=146: too wide to clear both ends, so centered again. A 10px wider label jumps back 10px arrow [0,0]->[300,0] instead, label 220px wide at labelPosition 0.3: 0.3667, 20px off where it was given Expected: as on the same arrows unbound: 0.5 (center x=146) for both default labels, and 0.3 for the given one. Fix: `clampLabelPositionOffEnds` returns the position unchanged unless it is at an end of the arrow (0 or 1, within PRECISION), where points on trimmed-off stretches project to. Snapshot: the label in "should bind arrows to shapes when start / end provided without ids" was too wide to clear both ends, so the clamp had centered it at exactly 0.5. It now keeps its projected position, 0.4999999949 (and is stored at x=240 instead of 240.00000045, with its version bumped as the position changed). Signed-off-by: Mark Tolmacs * fix(element): create skeleton arrow labels unrotated Arrow labels aren't rotated: `restore` resets their `angle` to 0, and `redrawTextBoundingBox` asserts it outside production and resets it. A skeleton label can still give an `angle` (its type allows the generic element props). Until 472c87980 every skeleton label was measured with `redrawTextBoundingBox` as soon as it was created, so an arrow label's angle was reset there. Since then, labels of placed (bound) arrows are measured only as placed, through `handleBindTextResize`, which leaves `angle` as given. Labels of arrows not placed are still measured with `redrawTextBoundingBox`, so outside production a given angle failed its invariant. Reproduction: rectangles A (0,0 100x100) and B (400,0 100x100), and an arrow at (106,50) with points [0,0]->[288,0] and label { text: "L", angle: 1 }, once bound from A to B and once unbound. Failure case: bound: label angle 1 unbound: "text element angle must be 0 if bound to arrow container" (outside production; angle 0 in production) Expected: label angle 0 on both arrows, as after `restore`. Fix: the label of an arrow is created with angle 0, as `restore` normalizes it. The labels of other containers are still rotated with them by `redrawTextBoundingBox`. Signed-off-by: Mark Tolmacs * fix(element): keep skeleton loop arrows' midpoints where given The placement pass (45276e6a9) places skeleton bound arrows with `updateBoundArrow`, which the editor also uses as an element moves. For an arrow bound to the same element at both ends, it passes `moveMidPointsWithElement`, so that a loop moves with its element as a whole: its midpoints follow its start. Placing a skeleton arrow moves nothing it's bound to, only its ends, so a loop's midpoints followed its start as it was placed off the element, and the loop changed shape. Midpoints of other arrows stay where given. Only the start drags them, so the result also depended on which end was the start. Reproduction: rectangle A (0,0 100x100), and an arrow from A's center around to A's right side: points (50,50) (50,-60) (160,-60) (160,50) (106,50), bound to A at both ends. Failure case: from the center: start placed off A's top edge, 56px up, at (50,-6), and the midpoints 56px up with it: (50,-116) (160,-116) (160,-6). The loop is 56px taller, and its last segment into A is diagonal from A's top edge (50,0): midpoints 6px up: (50,-66) (160,-66) (160,44) either, reversed: no change, as its start is already off A Expected: the midpoints where given, (50,-60) (160,-60) (160,50), with only the ends placed. Fix: `updateBoundArrow` takes `boundElementMoved` (default true, as the editor calls it). The placement pass passes false, so loops are placed like other arrows: only their ends move. Placed loops stay put under the editor's next binding update, and still move whole with their element. Left alone: a reversed loop given from the center still keeps its end there. For loops, `updateBoundPoint` places the end with the arrowhead at its fixed point and the other on the outline, and a skeleton end is bound where given, here at the center. That's the editor's own rule from master, applied to the binding as given. Signed-off-by: Mark Tolmacs --------- Signed-off-by: Mark Tolmacs Co-authored-by: Mark Tolmacs --- .../__snapshots__/transform.test.ts.snap | 120 +-- .../element/src/__tests__/transform.test.ts | 938 +++++++++++++++++- packages/element/src/align.ts | 4 + packages/element/src/binding.ts | 240 +++-- packages/element/src/collision.ts | 31 +- packages/element/src/delta.ts | 30 +- packages/element/src/distribute.ts | 5 + packages/element/src/dragElements.ts | 3 + packages/element/src/linearElementEditor.ts | 101 +- packages/element/src/listMarker.ts | 13 +- packages/element/src/resizeElements.ts | 10 +- packages/element/src/stickyNote.ts | 9 +- packages/element/src/textElement.ts | 24 +- packages/element/src/transform.ts | 458 +++++++-- packages/element/tests/binding.test.tsx | 50 + .../tests/linearElementEditor.test.tsx | 37 +- packages/excalidraw/actions/actionAlign.tsx | 1 + .../excalidraw/actions/actionDistribute.tsx | 1 + packages/excalidraw/actions/actionHistory.tsx | 12 +- .../excalidraw/actions/actionProperties.tsx | 4 +- packages/excalidraw/actions/actionStyles.ts | 4 +- .../actions/actionTextAutoResize.ts | 1 + .../excalidraw/components/App.duplicate.ts | 25 +- .../components/App.selectionTool.ts | 9 +- packages/excalidraw/components/App.text.ts | 8 +- packages/excalidraw/components/App.tsx | 12 +- packages/excalidraw/components/App.wrap.ts | 10 +- .../components/ConvertElementTypePopup.tsx | 4 +- .../excalidraw/components/Stats/Angle.tsx | 8 +- .../components/Stats/MultiDimension.tsx | 2 +- .../components/Stats/MultiPosition.tsx | 9 +- .../excalidraw/components/Stats/Position.tsx | 4 + packages/excalidraw/components/Stats/utils.ts | 7 +- .../TTDDialog/MermaidToExcalidraw.tsx | 3 +- .../components/TTDDialog/TextToDiagram.tsx | 1 + .../excalidraw/components/TTDDialog/common.ts | 5 + .../TTDDialog/hooks/useMermaidRenderer.ts | 6 +- packages/excalidraw/data/restore.ts | 4 + packages/excalidraw/history.ts | 33 +- .../tests/__snapshots__/history.test.tsx.snap | 50 +- .../tests/__snapshots__/move.test.tsx.snap | 1 - .../excalidraw/tests/data/restore.test.ts | 18 + .../tests/renderEnvironmentLabels.test.tsx | 228 +++++ packages/excalidraw/wysiwyg/textWysiwyg.tsx | 8 +- 44 files changed, 2210 insertions(+), 341 deletions(-) create mode 100644 packages/excalidraw/tests/renderEnvironmentLabels.test.tsx diff --git a/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap b/packages/element/src/__tests__/__snapshots__/transform.test.ts.snap index 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, "index": "a2", "isDeleted": false, @@ -113,8 +113,8 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s 0, ], [ - 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, - "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, "index": "a3", "isDeleted": false, @@ -175,8 +175,8 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s 0, ], [ - 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, - "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, "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 t 0, ], [ - 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, - "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, "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 whe 0, ], [ - 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, - "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, "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, "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 when 0, ], [ - 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, - "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, "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, "width": 100, - "x": 450.5, + "x": 450, "y": 20, } `; @@ -1572,7 +1572,7 @@ exports[`Test Transform > should transform the elements correctly when linear el 0, ], [ - 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, - "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, "width": 0, "x": 77.017, @@ -1871,7 +1871,7 @@ exports[`Test Transform > should transform the elements correctly when linear el "id": Any, "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, "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 provide 0, ], [ - 99, + 100, 0, ], ], @@ -1988,7 +1988,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide "version": 2, "versionNonce": Any, "width": 100, - "x": 100.5, + "x": 100, "y": 100, } `; @@ -2024,7 +2024,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide 0, ], [ - 99, + 100, 0, ], ], @@ -2041,7 +2041,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide "version": 2, "versionNonce": Any, "width": 100, - "x": 100.5, + "x": 100, "y": 200, } `; @@ -2077,7 +2077,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide 0, ], [ - 99, + 100, 0, ], ], @@ -2094,7 +2094,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide "version": 2, "versionNonce": Any, "width": 100, - "x": 100.5, + "x": 100, "y": 300, } `; @@ -2130,7 +2130,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide 0, ], [ - 99, + 100, 0, ], ], @@ -2147,7 +2147,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide "version": 2, "versionNonce": Any, "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.ts index 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(0, 0), pointFrom(200, 0)], + label: { text: "QUARTER", labelPosition: 0.25 }, + }, + { + type: "arrow", + x: 100, + y: 200, + points: [pointFrom(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), + pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), + pointFrom(300, 100), + ], + start: { id: "A" }, + }, + { + type: "arrow", + id: "unbound", + x: 100, + y: 300, + points: [pointFrom(0, 0), pointFrom(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(0, 0), pointFrom(500, 0)], + start: { id: "A" }, + end: { id: "B" }, + label: { text: "message" }, + }, + { + type: "arrow", + id: "half-far", + x: 100, + y: 10, + points: [ + pointFrom(0, 0), + pointFrom(450, 490), + ], + start: { id: "A" }, + end: { id: "B" }, + }, + { + type: "arrow", + id: "near", + x: 50, + // within binding distance below them + y: 30, + points: [pointFrom(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), pointFrom(250, 0)], + end: { id: "B" }, + }, + { + type: "arrow", + id: "stub", + // starts 80px short of A: within the minimum extension + x: 180, + y: 10, + points: [pointFrom(0, 0), pointFrom(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(0, 0), pointFrom(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(0, 0), + pointFrom(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(0, 0), pointFrom(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(0, 0), + pointFrom(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(0, 0), pointFrom(100, 100)], + vertical: [pointFrom(0, 0), pointFrom(0, 200)], + "right-to-left": [ + pointFrom(0, 0), + pointFrom(-200, 0), + ], + "multi-point": [ + pointFrom(0, 0), + pointFrom(0, 150), + pointFrom(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(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(0, 0), pointFrom(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(0, 0), pointFrom(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.ts index 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, + /** 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 elements updateBoundElements(element, scene, { simultaneouslyUpdated: group, + renderEnvironment, }); return updatedEle; }); diff --git a/packages/element/src/binding.ts b/packages/element/src/binding.ts index 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, + 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; + } + } + + return null; + }, + ).filter( + (update): update is MapEntry => 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; + /** 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 binding if (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; - } - } - - return null; - }, - ).filter( - (update): update is MapEntry => 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.ts index 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, + elementsMap: ElementsMap, + zoom: AppState["zoom"], +) => { + const maxDistance = maxBindingDistance_simple(zoom); + return ( + bindableElementBorderDistanceIfClose( + element, + point, + elementsMap, + maxDistance, + ) > -maxDistance + ); +}; + type BindingCandidate = { element: NonDeleted; /** 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.ts index 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 = export type ApplyToOptions = { excludedProperties?: Set; + /** + * 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 { ) : 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 { public static redrawElements( nextElements: SceneElementsMap, changedElements: Map, + 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 { // so we are creating a temp scene just to query and mutate elements const 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 { private static redrawTextBoundingBoxes( scene: Scene, changed: Map, + renderEnvironment?: RenderEnvironment, ) { const elements = scene.getNonDeletedElementsMap(); const boxesToRedraw = new Map< @@ -2100,13 +2120,14 @@ export class ElementsDelta implements DeltaContainer { continue; } - redrawTextBoundingBox(boundText, container, scene); + redrawTextBoundingBox(boundText, container, scene, renderEnvironment); } } private static redrawBoundArrows( scene: Scene, changed: Map, + renderEnvironment?: RenderEnvironment, ) { for (const element of changed.values()) { if (!element.isDeleted && isBindableElement(element)) { @@ -2116,6 +2137,7 @@ export class ElementsDelta implements DeltaContainer { scene, { changedElements: changed, + renderEnvironment, }, ); } diff --git a/packages/element/src/distribute.ts b/packages/element/src/distribute.ts index 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, 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.ts index 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 arrow diff --git a/packages/element/src/linearElementEditor.ts b/packages/element/src/linearElementEditor.ts index 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 change const 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,40 +1984,14 @@ export class LinearElementEditor { pointerX - linearElementEditor.pointerOffset.x, pointerY - linearElementEditor.pointerOffset.y, ); - const { segments, lengths, prefixSums, totalLength } = - getLinearElementPathMetrics(element, elementsMap); - if (segments.length === 0 || totalLength === 0) { + const labelPosition = LinearElementEditor.getPathParameterAtPoint( + element, + pointerGlobalPoint, + elementsMap, + ); + if (labelPosition === null) { return null; } - - let bestDistance = Infinity; - let bestSegmentIndex = 0; - let bestParameter = 0; - - for (let i = 0; i < segments.length; i++) { - const { t, distance } = pathSegmentClosestParameter( - segments[i], - pointerGlobalPoint, - ); - - if (distance < bestDistance) { - bestDistance = distance; - bestSegmentIndex = i; - bestParameter = t; - } - } - - const lengthWithinSegment = pathSegmentLengthAtParameter( - segments[bestSegmentIndex], - bestParameter, - lengths[bestSegmentIndex], - ); - - const labelPosition = clamp( - (prefixSums[bestSegmentIndex] + lengthWithinSegment) / totalLength, - 0, - 1, - ); const pathPoint = LinearElementEditor.getPointAtPathParameter( element, labelPosition, @@ -2034,6 +2013,52 @@ export class LinearElementEditor { }; } + static getPathLength( + element: ExcalidrawLinearElement, + elementsMap: ElementsMap, + ): number { + return getLinearElementPathMetrics(element, elementsMap).totalLength; + } + + /** the path parameter (0-1) of the point on the path closest to `point` */ + static getPathParameterAtPoint( + element: ExcalidrawLinearElement, + point: GlobalPoint, + elementsMap: ElementsMap, + ): number | null { + const { segments, lengths, prefixSums, totalLength } = + getLinearElementPathMetrics(element, elementsMap); + if (segments.length === 0 || totalLength === 0) { + return null; + } + + let bestDistance = Infinity; + let bestSegmentIndex = 0; + let bestParameter = 0; + + for (let i = 0; i < segments.length; i++) { + const { t, distance } = pathSegmentClosestParameter(segments[i], point); + + if (distance < bestDistance) { + bestDistance = distance; + bestSegmentIndex = i; + bestParameter = t; + } + } + + const lengthWithinSegment = pathSegmentLengthAtParameter( + segments[bestSegmentIndex], + bestParameter, + lengths[bestSegmentIndex], + ); + + return clamp( + (prefixSums[bestSegmentIndex] + lengthWithinSegment) / totalLength, + 0, + 1, + ); + } + static getPointAtPathParameter( container: ExcalidrawLinearElement, pathParameter: number, diff --git a/packages/element/src/listMarker.ts b/packages/element/src/listMarker.ts index 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.ts index 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.ts index 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.ts index 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.ts index 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, "labelPosition">, scene: Scene, renderEnvironment?: RenderEnvironment, ) => { @@ -282,9 +312,14 @@ const bindTextToContainer = ( ...textProps, containerId: container.id, strokeColor: stickyInk ?? (textProps.strokeColor || container.strokeColor), + // normalized as `restore` does labelPosition: 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, 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(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(); + // arrow labels yet to be measured, along their arrows + const unmeasuredArrowLabels = new Map< + ExcalidrawTextElement["id"], + [ExcalidrawArrowElement, ExcalidrawTextElement] + >(); // Add labels and arrow bindings for (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(); + 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.tsx index 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; + + 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.tsx index 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(10, 10) }], + [ + 2, + { + point: pointFrom( + 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.tsx index 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.tsx index 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.tsx index 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.tsx index 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.ts index 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.ts index 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.ts index 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.ts index 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.ts index 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.tsx index 7e8164eea0..bf9bab2056 100644 --- a/packages/excalidraw/components/App.tsx +++ b/packages/excalidraw/components/App.tsx @@ -5059,12 +5059,11 @@ class App extends React.Component { 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 = >( @@ -5479,6 +5478,7 @@ class App extends React.Component { updateBoundElements(element, this.scene, { simultaneouslyUpdated: selectedElements, + renderEnvironment: this.renderEnvironment, }); }); diff --git a/packages/excalidraw/components/App.wrap.ts b/packages/excalidraw/components/App.wrap.ts index 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 since nextElements = pushContainerBelowText(nextElements, container, text); diff --git a/packages/excalidraw/components/ConvertElementTypePopup.tsx b/packages/excalidraw/components/ConvertElementTypePopup.tsx index 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.tsx index 9b88a98dfc..44af920ed6 100644 --- a/packages/excalidraw/components/Stats/Angle.tsx +++ b/packages/excalidraw/components/Stats/Angle.tsx @@ -49,7 +49,9 @@ const handleDegreeChange: DragInputCallbackType = ({ 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 = ({ 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.tsx index 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.tsx index 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.tsx index 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.ts index 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.tsx index 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.tsx index 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.ts index 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; 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.ts index 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.ts index 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, 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.ts index 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.snap index 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.snap index 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.ts index 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.tsx new file mode 100644 index 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