Files
excalidraw/packages/element/tests/linearElementEditor.test.tsx
David LuzarandMark Tolmacs 808d068e18 fix(packages/excalidraw): update arrow binding on skeleton transform (#12425)
* 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: <same element at both ends> }` 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
`<Excalidraw renderEnvironment>` (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 `<Excalidraw renderEnvironment={env}>` 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 `<Excalidraw renderEnvironment>` 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 <mark@lazycat.hu>

* 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 `<Excalidraw renderEnvironment={env}>`, 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 <mark@lazycat.hu>

* 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 <mark@lazycat.hu>

* 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 <mark@lazycat.hu>

* 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 <mark@lazycat.hu>

* 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 <mark@lazycat.hu>

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
2026-10-27 16:37:03 +01:00

2101 lines
64 KiB
TypeScript

import { pointCenter, pointFrom } from "@excalidraw/math";
import { act, queryByTestId, queryByText } from "@testing-library/react";
import { vi } from "vitest";
import {
CURSOR_TYPE,
ROUNDNESS,
VERTICAL_ALIGN,
KEYS,
reseed,
arrayToMap,
} from "@excalidraw/common";
import { Excalidraw } from "@excalidraw/excalidraw";
import * as InteractiveCanvas from "@excalidraw/excalidraw/renderer/interactiveScene";
import * as StaticScene from "@excalidraw/excalidraw/renderer/staticScene";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { Keyboard, Pointer, UI } from "@excalidraw/excalidraw/tests/helpers/ui";
import {
screen,
render,
fireEvent,
GlobalTestState,
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
import type { GlobalPoint, LocalPoint } from "@excalidraw/math";
import { hasBoundingBox, wrapText } from "../src";
import * as textElementUtils from "../src/textElement";
import { getBoundTextElementPosition, getBoundTextMaxWidth } from "../src";
import { LinearElementEditor } from "../src";
import { newArrowElement } from "../src";
import { getLinearElementPathSegments } from "../src/utils";
import {
getTextEditor,
TEXT_EDITOR_SELECTOR,
} from "../../excalidraw/tests/queries/dom";
import type {
ExcalidrawArrowElement,
ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextElementWithContainer,
FontString,
NonDeletedExcalidrawElement,
} from "../src/types";
const renderInteractiveScene = vi.spyOn(
InteractiveCanvas,
"renderInteractiveScene",
);
const renderStaticScene = vi.spyOn(StaticScene, "renderStaticScene");
const { h } = window;
const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
describe("Test Linear Elements", () => {
let container: HTMLElement;
let interactiveCanvas: HTMLCanvasElement;
beforeEach(async () => {
unmountComponent();
localStorage.clear();
renderInteractiveScene.mockClear();
renderStaticScene.mockClear();
reseed(7);
const comp = await render(<Excalidraw handleKeyboardGlobally={true} />);
h.state.width = 1000;
h.state.height = 1000;
container = comp.container;
interactiveCanvas = container.querySelector("canvas.interactive")!;
});
const p1 = pointFrom<GlobalPoint>(20, 20);
const p2 = pointFrom<GlobalPoint>(60, 20);
const midpoint = pointCenter<GlobalPoint>(p1, p2);
const delta = 50;
const mouse = new Pointer("mouse");
const createTwoPointerLinearElement = (
type: ExcalidrawLinearElement["type"],
roundness: ExcalidrawElement["roundness"] = null,
roughness: ExcalidrawLinearElement["roughness"] = 0,
) => {
const line = API.createElement({
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
type,
roughness,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], p2[1] - p1[1])],
roundness,
});
API.setElements([line]);
mouse.clickAt(p1[0], p1[1]);
return line;
};
const createThreePointerLinearElement = (
type: ExcalidrawLinearElement["type"],
roundness: ExcalidrawElement["roundness"] = null,
roughness: ExcalidrawLinearElement["roughness"] = 0,
) => {
//dragging line from midpoint
const p3 = [midpoint[0] + delta - p1[0], midpoint[1] + delta - p1[1]];
const line = API.createElement({
x: p1[0],
y: p1[1],
width: p3[0] - p1[0],
height: 0,
type,
roughness,
points: [
pointFrom(0, 0),
pointFrom(p3[0], p3[1]),
pointFrom(p2[0] - p1[0], p2[1] - p1[1]),
],
roundness,
});
h.app.scene.mutateElement(line, { points: line.points });
API.setElements([line]);
mouse.clickAt(p1[0], p1[1]);
return line;
};
const enterLineEditingMode = (
line: ExcalidrawLinearElement,
selectProgrammatically = false,
) => {
if (selectProgrammatically) {
API.setSelectedElements([line] as NonDeletedExcalidrawElement[]);
} else {
mouse.clickAt(p1[0], p1[1]);
}
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ENTER);
});
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(line.id);
};
const drag = (startPoint: GlobalPoint, endPoint: GlobalPoint) => {
fireEvent.pointerDown(interactiveCanvas, {
clientX: startPoint[0],
clientY: startPoint[1],
});
fireEvent.pointerMove(interactiveCanvas, {
clientX: endPoint[0],
clientY: endPoint[1],
});
fireEvent.pointerUp(interactiveCanvas, {
clientX: endPoint[0],
clientY: endPoint[1],
});
};
const deletePoint = (point: GlobalPoint) => {
fireEvent.pointerDown(interactiveCanvas, {
clientX: point[0],
clientY: point[1],
});
fireEvent.pointerUp(interactiveCanvas, {
clientX: point[0],
clientY: point[1],
});
Keyboard.keyPress(KEYS.DELETE);
};
it("should normalize the element points at creation", () => {
const element = newArrowElement({
type: "arrow",
points: [pointFrom<LocalPoint>(0.5, 0), pointFrom<LocalPoint>(100, 100)],
x: 0,
y: 0,
});
expect(element.points).toEqual([
pointFrom<LocalPoint>(0.5, 0),
pointFrom<LocalPoint>(100, 100),
]);
new LinearElementEditor(element, arrayToMap(h.elements));
expect(element.points).toEqual([
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(99.5, 100),
]);
});
it("should not drag line and add midpoint until dragged beyond a threshold", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
const originalX = line.x;
const originalY = line.y;
expect(line.points.length).toEqual(2);
mouse.clickAt(midpoint[0], midpoint[1]);
drag(midpoint, pointFrom(midpoint[0] + 1, midpoint[1] + 1));
expect(line.points.length).toEqual(2);
expect(line.x).toBe(originalX);
expect(line.y).toBe(originalY);
expect(line.points.length).toEqual(2);
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(line.x).toBe(originalX);
expect(line.y).toBe(originalY);
expect(line.points.length).toEqual(3);
});
it("should allow dragging line from midpoint in 2 pointer lines outside editor", async () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`6`);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`5`);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toEqual(2);
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`10`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
expect(line.points.length).toEqual(3);
expect(line.points).toMatchInlineSnapshot(`
[
[
0,
0,
],
[
70,
50,
],
[
40,
0,
],
]
`);
});
it("should hide the bounding box while creating or dragging a point", () => {
const line = createTwoPointerLinearElement("line");
const editorInterface = {
userAgent: { isMobileDevice: false },
} as Parameters<typeof hasBoundingBox>[2];
fireEvent.pointerDown(interactiveCanvas, {
clientX: midpoint[0],
clientY: midpoint[1],
});
fireEvent.pointerMove(interactiveCanvas, {
clientX: midpoint[0] + delta,
clientY: midpoint[1] + delta,
});
expect(line.points.length).toBe(3);
expect(h.state.selectedLinearElement?.isDragging).toBe(true);
expect(hasBoundingBox([line], h.state, editorInterface)).toBe(false);
fireEvent.pointerUp(interactiveCanvas, {
clientX: midpoint[0] + delta,
clientY: midpoint[1] + delta,
});
const addedPoint = LinearElementEditor.getPointAtIndexGlobalCoordinates(
line,
1,
h.scene.getNonDeletedElementsMap(),
);
fireEvent.pointerDown(interactiveCanvas, {
clientX: addedPoint[0],
clientY: addedPoint[1],
});
fireEvent.pointerMove(interactiveCanvas, {
clientX: addedPoint[0] + 1,
clientY: addedPoint[1] + 1,
});
expect(h.state.selectedLinearElement?.isDragging).toBe(true);
expect(hasBoundingBox([line], h.state, editorInterface)).toBe(false);
fireEvent.pointerUp(interactiveCanvas, {
clientX: addedPoint[0],
clientY: addedPoint[1],
});
});
it("should allow entering and exiting line editor via context menu", () => {
createTwoPointerLinearElement("line");
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: midpoint[0],
clientY: midpoint[1],
});
// Enter line editor
const contextMenu = document.querySelector(".context-menu");
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: midpoint[0],
clientY: midpoint[1],
});
fireEvent.click(queryByText(contextMenu as HTMLElement, "Edit line")!);
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should allow editing an arrow from the context menu when its bound text appears earlier in the elements array", () => {
const arrow = createTwoPointerLinearElement("arrow");
const textElement = API.createElement({
type: "text",
x: 0,
y: 0,
text: "abc",
containerId: arrow.id,
width: 30,
height: 20,
});
const updatedArrow = {
...arrow,
boundElements: [{ type: "text" as const, id: textElement.id }],
};
// text element intentionally placed before its container in the array
API.setElements([textElement, updatedArrow]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: midpoint[0],
clientY: midpoint[1],
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: midpoint[0],
clientY: midpoint[1],
});
expect(() =>
fireEvent.click(queryByText(contextMenu as HTMLElement, "Edit arrow")!),
).not.toThrow();
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(updatedArrow.id);
});
it("should enter line editor via enter (line)", () => {
createTwoPointerLinearElement("line");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
mouse.clickAt(midpoint[0], midpoint[1]);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
// ctrl+enter alias (to align with arrows)
it("should enter line editor via ctrl+enter (line)", () => {
createTwoPointerLinearElement("line");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
mouse.clickAt(midpoint[0], midpoint[1]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ENTER);
});
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should enter line editor via ctrl+enter (arrow)", () => {
createTwoPointerLinearElement("arrow");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
mouse.clickAt(midpoint[0], midpoint[1]);
Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.ENTER);
});
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should enter line editor on ctrl+dblclick (simple arrow)", () => {
createTwoPointerLinearElement("arrow");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
Keyboard.withModifierKeys({ ctrl: true }, () => {
mouse.doubleClick();
});
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should enter line editor on ctrl+dblclick (line)", () => {
createTwoPointerLinearElement("line");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
Keyboard.withModifierKeys({ ctrl: true }, () => {
mouse.doubleClick();
});
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should enter line editor on dblclick (line)", () => {
createTwoPointerLinearElement("line");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
mouse.doubleClick();
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("should not enter line editor on dblclick (arrow)", async () => {
createTwoPointerLinearElement("arrow");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
mouse.doubleClickAt(midpoint[0], midpoint[1]);
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
await getTextEditor();
});
it("updates the hovered handles together (midpoint, then endpoint)", () => {
createTwoPointerLinearElement("arrow");
mouse.moveTo(midpoint[0], midpoint[1]);
expect(
h.state.selectedLinearElement?.segmentMidPointHoveredCoords,
).not.toBe(null);
mouse.moveTo(p2[0], p2[1]);
expect(h.state.selectedLinearElement).toMatchObject({
hoverPointIndex: 1,
segmentMidPointHoveredCoords: null,
});
});
it("doesn't highlight the arrow's midpoint while its label is edited", async () => {
createTwoPointerLinearElement("arrow");
mouse.moveTo(midpoint[0], midpoint[1]);
expect(
h.state.selectedLinearElement?.segmentMidPointHoveredCoords,
).not.toBe(null);
mouse.doubleClickAt(midpoint[0], midpoint[1]);
await getTextEditor();
expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(
null,
);
// (beside the editor)
mouse.moveTo(midpoint[0] + 8, midpoint[1]);
expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(
null,
);
});
it.each([
["start", null],
["start", "triangle"],
["end", null],
["end", "triangle"],
] as const)(
"should not toggle the %s arrowhead from %s on endpoint dblclick",
async (side, arrowhead) => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], p2[1] - p1[1])],
startArrowhead: side === "start" ? arrowhead : null,
endArrowhead: side === "end" ? arrowhead : null,
});
API.setElements([arrow]);
mouse.clickAt(midpoint[0], midpoint[1]);
const endpoint = side === "start" ? p1 : p2;
mouse.doubleClickAt(endpoint[0], endpoint[1]);
const updatedArrow = h.elements[0] as ExcalidrawArrowElement;
expect(
side === "start"
? updatedArrow.startArrowhead
: updatedArrow.endArrowhead,
).toBe(arrowhead);
await getTextEditor();
},
);
it("shouldn't create text element on double click in line editor (arrow)", async () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
enterLineEditingMode(arrow);
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(arrow.id);
mouse.doubleClick();
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toEqual(arrow.id);
expect(h.elements.length).toEqual(1);
expect(document.querySelector(TEXT_EDITOR_SELECTOR)).toBe(null);
});
describe("Inside editor", () => {
it("should not drag line and add midpoint when dragged irrespective of threshold", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
const originalX = line.x;
const originalY = line.y;
enterLineEditingMode(line);
expect(h.state.selectedLinearElement?.isEditing).toBe(true);
expect(line.points.length).toEqual(2);
mouse.clickAt(midpoint[0], midpoint[1]);
expect(line.points.length).toEqual(2);
drag(midpoint, pointFrom(midpoint[0] + 1, midpoint[1] + 1));
expect(line.x).toBe(originalX);
expect(line.y).toBe(originalY);
expect(line.points.length).toEqual(3);
});
it("should allow dragging line from midpoint in 2 pointer lines", async () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
enterLineEditingMode(line);
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
expect(line.points.length).toEqual(3);
expect(line.points).toMatchInlineSnapshot(`
[
[
0,
0,
],
[
70,
50,
],
[
40,
0,
],
]
`);
});
it("should update the midpoints when element roundness changed", async () => {
createThreePointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
expect(line.points.length).toEqual(3);
enterLineEditingMode(line);
const midPointsWithSharpEdge = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
// update roundness
fireEvent.click(screen.getByTitle("Round"));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`11`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`6`);
const midPointsWithRoundEdge = LinearElementEditor.getEditorMidPoints(
h.elements[0] as ExcalidrawLinearElement,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(midPointsWithRoundEdge[0]).not.toEqual(midPointsWithSharpEdge[0]);
expect(midPointsWithRoundEdge[1]).not.toEqual(midPointsWithSharpEdge[1]);
expect(midPointsWithRoundEdge).toMatchInlineSnapshot(`
[
[
"54.27552",
"46.16120",
],
[
"76.95494",
"44.56052",
],
]
`);
});
it("should update all the midpoints when element position changed", async () => {
const elementsMap = arrayToMap(h.elements);
createThreePointerLinearElement("line", {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
});
const line = h.elements[0] as ExcalidrawLinearElement;
expect(line.points.length).toEqual(3);
enterLineEditingMode(line);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
expect([line.x, line.y]).toEqual(points[0]);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const startPoint = pointCenter(points[0], midPoints[0]!);
const deltaX = 50;
const deltaY = 20;
const endPoint = pointFrom<GlobalPoint>(
startPoint[0] + deltaX,
startPoint[1] + deltaY,
);
// Move the element
drag(startPoint, endPoint);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`13`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
expect([line.x, line.y]).toEqual([
points[0][0] + deltaX,
points[0][1] + deltaY,
]);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(midPoints[0]).not.toEqual(newMidPoints[0]);
expect(midPoints[1]).not.toEqual(newMidPoints[1]);
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"104.27552",
"66.16120",
],
[
"126.95494",
"64.56052",
],
]
`);
});
describe("When edges are round", () => {
// This is the expected midpoint for line with round edge
// hence hardcoding it so if later some bug is introduced
// this will fail and we can fix it
const firstSegmentMidpoint = pointFrom<GlobalPoint>(55, 45);
const lastSegmentMidpoint = pointFrom<GlobalPoint>(75, 40);
let line: ExcalidrawLinearElement;
beforeEach(() => {
line = createThreePointerLinearElement("line");
expect(line.points.length).toEqual(3);
enterLineEditingMode(line);
});
it("should allow dragging lines from midpoints in between segments", async () => {
// drag line via first segment midpoint
drag(
firstSegmentMidpoint,
pointFrom(
firstSegmentMidpoint[0] + delta,
firstSegmentMidpoint[1] + delta,
),
);
expect(line.points.length).toEqual(4);
// drag line from last segment midpoint
drag(
lastSegmentMidpoint,
pointFrom(
lastSegmentMidpoint[0] + delta,
lastSegmentMidpoint[1] + delta,
),
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(line.points.length).toEqual(5);
expect((h.elements[0] as ExcalidrawLinearElement).points)
.toMatchInlineSnapshot(`
[
[
0,
0,
],
[
85,
75,
],
[
70,
50,
],
[
105,
70,
],
[
40,
0,
],
]
`);
});
it("should update only the first segment midpoint when its point is dragged", async () => {
const elementsMap = arrayToMap(h.elements);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const hitCoords = pointFrom<GlobalPoint>(points[0][0], points[0][1]);
// Drag from first point
drag(hitCoords, pointFrom(hitCoords[0] - delta, hitCoords[1] - delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
const newPoints = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
expect([newPoints[0][0], newPoints[0][1]]).toEqual([
points[0][0] - delta,
points[0][1] - delta,
]);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(midPoints[0]).not.toEqual(newMidPoints[0]);
expect(midPoints[1]).toEqual(newMidPoints[1]);
});
it("should hide midpoints in the segment when points moved close", async () => {
const elementsMap = arrayToMap(h.elements);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const hitCoords = pointFrom<GlobalPoint>(points[0][0], points[0][1]);
// Drag from first point
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
const newPoints = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
expect([newPoints[0][0], newPoints[0][1]]).toEqual([
points[0][0] + delta,
points[0][1] + delta,
]);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
// This midpoint is hidden since the points are too close
expect(newMidPoints[0]).toBeNull();
expect(midPoints[1]).toEqual(newMidPoints[1]);
});
it("should remove the midpoint when one of the points in the segment is deleted", async () => {
const line = h.elements[0] as ExcalidrawLinearElement;
enterLineEditingMode(line);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
arrayToMap(h.elements),
);
// dragging line from last segment midpoint
drag(
lastSegmentMidpoint,
pointFrom(lastSegmentMidpoint[0] + 50, lastSegmentMidpoint[1] + 50),
);
expect(line.points.length).toEqual(4);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
// delete 3rd point
deletePoint(points[2]);
expect(line.points.length).toEqual(3);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`22`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`10`);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(newMidPoints.length).toEqual(2);
expect(midPoints[0]).toEqual(newMidPoints[0]);
expect(midPoints[1]).toEqual(newMidPoints[1]);
});
});
describe("When edges are round", () => {
// This is the expected midpoint for line with round edge
// hence hardcoding it so if later some bug is introduced
// this will fail and we can fix it
const firstSegmentMidpoint = pointFrom<GlobalPoint>(
55.9697848965255,
47.442326230998205,
);
const lastSegmentMidpoint = pointFrom<GlobalPoint>(
76.08587175006699,
43.294165939653226,
);
let line: ExcalidrawLinearElement;
beforeEach(() => {
line = createThreePointerLinearElement("line", {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
});
expect(line.points.length).toEqual(3);
enterLineEditingMode(line);
});
it("should allow dragging lines from midpoints in between segments", async () => {
// drag line from first segment midpoint
drag(
firstSegmentMidpoint,
pointFrom(
firstSegmentMidpoint[0] + delta,
firstSegmentMidpoint[1] + delta,
),
);
expect(line.points.length).toEqual(4);
// drag line from last segment midpoint
drag(
lastSegmentMidpoint,
pointFrom(
lastSegmentMidpoint[0] + delta,
lastSegmentMidpoint[1] + delta,
),
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(line.points.length).toEqual(5);
expect((h.elements[0] as ExcalidrawLinearElement).points)
.toMatchInlineSnapshot(`
[
[
0,
0,
],
[
"85.96978",
"77.44233",
],
[
70,
50,
],
[
"106.08587",
"73.29417",
],
[
40,
0,
],
]
`);
});
it("should update all the midpoints when its point is dragged", async () => {
const elementsMap = arrayToMap(h.elements);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const hitCoords = pointFrom<GlobalPoint>(points[0][0], points[0][1]);
// Drag from first point
drag(hitCoords, pointFrom(hitCoords[0] - delta, hitCoords[1] - delta));
const newPoints = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
expect([newPoints[0][0], newPoints[0][1]]).toEqual([
points[0][0] - delta,
points[0][1] - delta,
]);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(midPoints[0]).not.toEqual(newMidPoints[0]);
expect(midPoints[1]).not.toEqual(newMidPoints[1]);
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"29.28349",
"20.91105",
],
[
"78.86048",
"46.12277",
],
]
`);
});
it("should hide midpoints in the segment when points moved close", async () => {
const elementsMap = arrayToMap(h.elements);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const hitCoords = pointFrom<GlobalPoint>(points[0][0], points[0][1]);
// Drag from first point
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
const newPoints = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
expect([newPoints[0][0], newPoints[0][1]]).toEqual([
points[0][0] + delta,
points[0][1] + delta,
]);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
// This mid point is hidden due to point being too close
expect(newMidPoints[0]).toBeNull();
expect(newMidPoints[1]).not.toEqual(midPoints[1]);
});
it("should update all the midpoints when a point is deleted", async () => {
const elementsMap = arrayToMap(h.elements);
drag(
lastSegmentMidpoint,
pointFrom(
lastSegmentMidpoint[0] + delta,
lastSegmentMidpoint[1] + delta,
),
);
expect(line.points.length).toEqual(4);
const midPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
// delete 3rd point
deletePoint(points[2]);
expect(line.points.length).toEqual(3);
const newMidPoints = LinearElementEditor.getEditorMidPoints(
line,
h.app.scene.getNonDeletedElementsMap(),
h.state,
);
expect(newMidPoints.length).toEqual(2);
expect(midPoints[0]).not.toEqual(newMidPoints[0]);
expect(midPoints[1]).not.toEqual(newMidPoints[1]);
expect(newMidPoints).toMatchInlineSnapshot(`
[
[
"54.27552",
"46.16120",
],
[
"76.95494",
"44.56052",
],
]
`);
});
});
it("in-editor dragging a line point covered by another element", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
API.setElements([
line,
API.createElement({
type: "rectangle",
x: line.x - 50,
y: line.y - 50,
width: 100,
height: 100,
backgroundColor: "red",
fillStyle: "solid",
}),
]);
const dragEndPositionOffset = [100, 100] as const;
API.setSelectedElements([line] as NonDeletedExcalidrawElement[]);
enterLineEditingMode(line, true);
drag(
pointFrom(line.points[0][0] + line.x, line.points[0][1] + line.y),
pointFrom(
dragEndPositionOffset[0] + line.x,
dragEndPositionOffset[1] + line.y,
),
);
expect(line.points).toMatchInlineSnapshot(`
[
[
0,
0,
],
[
-60,
-100,
],
]
`);
});
});
describe("Test bound text element", () => {
const DEFAULT_TEXT = "Online whiteboard collaboration made easy";
const createBoundTextElement = (
text: string,
container: ExcalidrawLinearElement,
) => {
const textElement = API.createElement({
type: "text",
x: 0,
y: 0,
text: wrapText(text, font, getBoundTextMaxWidth(container, null)),
containerId: container.id,
width: 30,
height: 20,
}) as ExcalidrawTextElementWithContainer;
container = {
...container,
boundElements: (container.boundElements || []).concat({
type: "text",
id: textElement.id,
}),
};
const elements: ExcalidrawElement[] = [];
h.elements.forEach((element) => {
if (element.id === container.id) {
elements.push(container);
} else {
elements.push(element);
}
});
const updatedTextElement = { ...textElement, originalText: text };
API.setElements([...elements, updatedTextElement]);
return { textElement: updatedTextElement, container };
};
describe("Test getBoundTextElementPosition", () => {
it("should return correct position for 2 pointer arrow", () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
const { textElement, container } = createBoundTextElement(
DEFAULT_TEXT,
arrow,
);
const position = LinearElementEditor.getBoundTextElementPosition(
container,
textElement,
arrayToMap(h.elements),
);
expect(position).toMatchInlineSnapshot(`
{
"x": 25,
"y": 10,
}
`);
});
it("should return correct position for arrow with odd points", () => {
createThreePointerLinearElement("arrow", {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
});
const arrow = h.elements[0] as ExcalidrawLinearElement;
const { textElement, container } = createBoundTextElement(
DEFAULT_TEXT,
arrow,
);
const position = LinearElementEditor.getBoundTextElementPosition(
container,
textElement,
arrayToMap(h.elements),
);
expect(position).toMatchInlineSnapshot(`
{
"x": 75,
"y": 60,
}
`);
});
it("should return correct position for arrow with even points", () => {
createThreePointerLinearElement("arrow", {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
});
const arrow = h.elements[0] as ExcalidrawLinearElement;
const { textElement, container } = createBoundTextElement(
DEFAULT_TEXT,
arrow,
);
enterLineEditingMode(container);
// This is the expected midpoint for line with round edge
// hence hardcoding it so if later some bug is introduced
// this will fail and we can fix it
const firstSegmentMidpoint = pointFrom<GlobalPoint>(
55.9697848965255,
47.442326230998205,
);
// drag line from first segment midpoint
drag(
firstSegmentMidpoint,
pointFrom(
firstSegmentMidpoint[0] + delta,
firstSegmentMidpoint[1] + delta,
),
);
const position = LinearElementEditor.getBoundTextElementPosition(
container,
textElement,
arrayToMap(h.elements),
);
expect(position).toMatchInlineSnapshot(`
{
"x": "86.17305",
"y": "76.11251",
}
`);
});
});
describe("Test getPointAtPathParameter", () => {
it("should survive midpoint insertion", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
roundness: null,
});
API.setElements([arrow]);
const before = LinearElementEditor.getPointAtPathParameter(
arrow,
0.25,
arrayToMap(h.elements),
)!;
expect(before[0]).toBeCloseTo(25);
expect(before[1]).toBeCloseTo(0);
// inserting a midpoint re-segments the path but must not move the
// point at the same normalized arc-length parameter
act(() => {
h.app.scene.mutateElement(arrow, {
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(50, 0),
pointFrom<LocalPoint>(100, 0),
],
});
});
const after = LinearElementEditor.getPointAtPathParameter(
arrow,
0.25,
arrayToMap(h.elements),
)!;
expect(after[0]).toBeCloseTo(before[0]);
expect(after[1]).toBeCloseTo(before[1]);
});
it("should use the unrounded logical path of elbow arrows", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 100,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 0),
pointFrom<LocalPoint>(100, 100),
],
elbowed: true,
});
API.setElements([arrow]);
const elementsMap = arrayToMap(h.elements);
// Until mixed paths are supported, elbow arrows are treated as the
// straight segments between their logical points.
const segments = getLinearElementPathSegments(arrow, elementsMap);
expect(segments).toHaveLength(2);
for (let i = 1; i < segments.length; i++) {
const prevEnd = segments[i - 1][segments[i - 1].length - 1];
expect(segments[i][0][0]).toBeCloseTo(prevEnd[0]);
expect(segments[i][0][1]).toBeCloseTo(prevEnd[1]);
}
const expectedPoints = [
pointFrom<GlobalPoint>(0, 0),
pointFrom<GlobalPoint>(50, 0),
pointFrom<GlobalPoint>(100, 0),
pointFrom<GlobalPoint>(100, 50),
pointFrom<GlobalPoint>(100, 100),
];
for (const [index, parameter] of [0, 0.25, 0.5, 0.75, 1].entries()) {
const point = LinearElementEditor.getPointAtPathParameter(
arrow,
parameter,
elementsMap,
);
expect(point).toEqual(expectedPoints[index]);
}
});
});
it("should match styles for text editor", async () => {
createTwoPointerLinearElement("arrow");
Keyboard.keyPress(KEYS.ENTER);
const editor = await getTextEditor();
expect(editor).toMatchSnapshot();
});
it("should bind text to arrow when double clicked", async () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(arrow.id);
mouse.doubleClickAt(midpoint[0], midpoint[1]);
expect(h.elements.length).toBe(2);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(arrow.id);
mouse.down();
const editor = await getTextEditor();
fireEvent.change(editor, {
target: { value: DEFAULT_TEXT },
});
Keyboard.exitTextEditor(editor);
expect(arrow.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).text,
).toMatchSnapshot();
});
it("should bind text to arrow when clicked on arrow and enter pressed", async () => {
const arrow = createTwoPointerLinearElement("arrow");
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(arrow.id);
Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(2);
const textElement = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(textElement.type).toBe("text");
expect(textElement.containerId).toBe(arrow.id);
const editor = await getTextEditor();
fireEvent.change(editor, {
target: { value: DEFAULT_TEXT },
});
Keyboard.exitTextEditor(editor);
expect(arrow.boundElements).toStrictEqual([
{ id: textElement.id, type: "text" },
]);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).text,
).toMatchSnapshot();
});
it("should not bind text to line when double clicked", async () => {
const line = createTwoPointerLinearElement("line");
expect(h.elements.length).toBe(1);
mouse.doubleClickAt(line.x, line.y);
expect(h.elements.length).toBe(1);
});
// TODO fix #7029 and rewrite this test
it.todo(
"should not rotate the bound text and update position of bound text and bounding box correctly when arrow rotated",
);
it("should resize and position the bound text and bounding box correctly when 3 pointer arrow element resized", () => {
createThreePointerLinearElement("arrow", {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
});
const arrow = h.elements[0] as ExcalidrawLinearElement;
const { textElement, container } = createBoundTextElement(
DEFAULT_TEXT,
arrow,
);
expect(container.width).toBe(70);
expect(container.height).toBe(50);
expect(
getBoundTextElementPosition(
container,
textElement,
arrayToMap(h.elements),
),
).toMatchInlineSnapshot(`
{
"x": 75,
"y": 60,
}
`);
expect(textElement.text).toMatchSnapshot();
expect(
LinearElementEditor.getElementAbsoluteCoords(
container,
h.app.scene.getNonDeletedElementsMap(),
true,
),
).toMatchInlineSnapshot(`
[
20,
20,
105,
80,
"55.45894",
45,
]
`);
UI.resize(container, "ne", [300, 200]);
expect({ width: container.width, height: container.height })
.toMatchInlineSnapshot(`
{
"height": 150,
"width": "366.11716",
}
`);
expect(
getBoundTextElementPosition(
container,
textElement,
arrayToMap(h.elements),
),
).toMatchInlineSnapshot(`
{
"x": "271.11716",
"y": 45,
}
`);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).text,
).toMatchSnapshot();
expect(
LinearElementEditor.getElementAbsoluteCoords(
container,
h.app.scene.getNonDeletedElementsMap(),
true,
),
).toMatchInlineSnapshot(`
[
20,
45,
"501.11716",
220,
"205.45894",
145,
]
`);
});
it("should resize and position the bound text correctly when 2 pointer linear element resized", () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
const { textElement, container } = createBoundTextElement(
DEFAULT_TEXT,
arrow,
);
expect(container.width).toBe(40);
const elementsMap = arrayToMap(h.elements);
expect(getBoundTextElementPosition(container, textElement, elementsMap))
.toMatchInlineSnapshot(`
{
"x": 25,
"y": 10,
}
`);
expect(textElement.text).toMatchSnapshot();
const points = LinearElementEditor.getPointsGlobalCoordinates(
container,
elementsMap,
);
// Drag from last point
drag(points[1], pointFrom(points[1][0] + 300, points[1][1]));
expect({ width: container.width, height: container.height })
.toMatchInlineSnapshot(`
{
"height": 0,
"width": 340,
}
`);
expect(getBoundTextElementPosition(container, textElement, elementsMap))
.toMatchInlineSnapshot(`
{
"x": 75,
"y": -5,
}
`);
expect(textElement.text).toMatchSnapshot();
});
it("should not render vertical align tool when element selected", () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
createBoundTextElement(DEFAULT_TEXT, arrow);
API.setSelectedElements([arrow] as NonDeletedExcalidrawElement[]);
expect(queryByTestId(container, "align-top")).toBeNull();
expect(queryByTestId(container, "align-middle")).toBeNull();
expect(queryByTestId(container, "align-bottom")).toBeNull();
});
it("should wrap the bound text when arrow bound container moves", async () => {
const rect = UI.createElement("rectangle", {
x: 400,
width: 200,
height: 500,
});
const arrow = UI.createElement("arrow", {
x: -10,
y: 250,
width: 410,
height: 1,
});
mouse.select(arrow);
Keyboard.keyPress(KEYS.ENTER);
const editor = await getTextEditor();
fireEvent.change(editor, { target: { value: DEFAULT_TEXT } });
Keyboard.exitTextEditor(editor);
const textElement = h.elements[2] as ExcalidrawTextElementWithContainer;
expect(arrow.endBinding?.elementId).toBe(rect.id);
expect(arrow.width).toBeCloseTo(404);
expect(rect.x).toBe(400);
expect(rect.y).toBe(0);
expect(
wrapText(
textElement.originalText,
font,
getBoundTextMaxWidth(arrow, null),
),
).toMatchSnapshot();
const handleBindTextResizeSpy = vi.spyOn(
textElementUtils,
"handleBindTextResize",
);
mouse.select(rect);
mouse.downAt(rect.x, rect.y);
mouse.moveTo(200, 0);
mouse.upAt(200, 0);
expect(arrow.width).toBeCloseTo(204);
expect(rect.x).toBe(200);
expect(rect.y).toBe(0);
expect(handleBindTextResizeSpy).toHaveBeenCalledWith(
h.elements[0],
h.app.scene,
"nw",
false,
false,
false,
h.app.renderEnvironment,
);
expect(
wrapText(
textElement.originalText,
font,
getBoundTextMaxWidth(arrow, null),
),
).toMatchSnapshot();
});
it("should not render horizontal align tool when element selected", () => {
createTwoPointerLinearElement("arrow");
const arrow = h.elements[0] as ExcalidrawLinearElement;
createBoundTextElement(DEFAULT_TEXT, arrow);
API.setSelectedElements([arrow] as NonDeletedExcalidrawElement[]);
expect(queryByTestId(container, "align-left")).toBeNull();
expect(queryByTestId(container, "align-horizontal-center")).toBeNull();
expect(queryByTestId(container, "align-right")).toBeNull();
});
it("should update label coords when a label binded via context menu is unbinded", async () => {
createTwoPointerLinearElement("arrow");
const text = API.createElement({
type: "text",
text: "Hello Excalidraw",
});
expect(text.x).toBe(0);
expect(text.y).toBe(0);
API.setElements([h.elements[0], text]);
const container = h.elements[0];
API.setSelectedElements([
container,
text,
] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 20,
clientY: 30,
});
let contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Bind text to the container")!,
);
expect(container.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(container.id);
expect(text.verticalAlign).toBe(VERTICAL_ALIGN.MIDDLE);
mouse.reset();
mouse.clickAt(
container.x + container.width / 2,
container.y + container.height / 2,
);
mouse.down();
mouse.up();
API.setSelectedElements([
h.elements[0],
h.elements[1],
] as NonDeletedExcalidrawElement[]);
fireEvent.contextMenu(GlobalTestState.interactiveCanvas, {
button: 2,
clientX: 20,
clientY: 30,
});
contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(container.boundElements).toEqual([]);
// the arrow is selected along with the freed label
expect(h.state.selectedLinearElement).toBe(null);
expect(text).toEqual(
expect.objectContaining({
containerId: null,
width: 160,
height: 25,
x: -40,
y: 7.5,
}),
);
});
it("should not update label position when arrow dragged", () => {
createTwoPointerLinearElement("arrow");
let arrow = h.elements[0] as ExcalidrawLinearElement;
createBoundTextElement(DEFAULT_TEXT, arrow);
let label = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(arrow.x).toBe(20);
expect(arrow.y).toBe(20);
expect(label.x).toBe(0);
expect(label.y).toBe(0);
mouse.reset();
mouse.select(arrow);
mouse.select(label);
mouse.downAt(arrow.x, arrow.y);
mouse.moveTo(arrow.x + 20, arrow.y + 30);
mouse.up(arrow.x + 20, arrow.y + 30);
arrow = h.elements[0] as ExcalidrawLinearElement;
label = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(arrow.x).toBe(80);
expect(arrow.y).toBe(100);
expect(label.x).toBe(0);
expect(label.y).toBe(0);
});
describe("dragging the label along the arrow", () => {
// a tall label, so its lower half is beyond the arrow's hit threshold:
// there the pointer is over the label but not over the arrow's path
const createArrowWithTallLabel = () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 60,
}),
labelPosition: 0.5,
} as ExcalidrawTextElementWithContainer;
return {
label,
arrow: {
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
};
};
// covers the label and the arrow's segment midpoint handle, but not the
// arrow's start point, so the arrow can still be selected by clicking it
const createOccluder = () =>
API.createElement({
type: "rectangle",
x: 30,
y: 5,
width: 30,
height: 50,
backgroundColor: "#ff0000",
fillStyle: "solid",
});
// inside the label, off the arrow's path
const labelOnlyPoint = pointFrom<GlobalPoint>(40, 45);
it("treats a point handle under the label as the handle, on hover and on pointer down", () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 30,
}),
// centered on the end point
labelPosition: 1,
} as ExcalidrawTextElementWithContainer;
API.setElements([
{
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
label,
]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// inside the label and within the end point's handle radius, but
// farther from the arrow's path than the arrow's own hit threshold
const point = pointFrom<GlobalPoint>(p2[0], p2[1] + 9);
mouse.moveTo(point[0], point[1]);
expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
expect(GlobalTestState.interactiveCanvas.style.cursor).toBe(
CURSOR_TYPE.POINTER,
);
drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(1);
expect(
(h.elements[0] as ExcalidrawLinearElement).points[1][0],
).toBeCloseTo(p2[0] - p1[0] + 40);
});
it("keeps the arrow selected when a point handle is grabbed beyond the arrow's tip", () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
API.setElements([arrow]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// past the end point along the arrow: inside the handle radius, but
// outside the arrow's own hit area
const point = pointFrom<GlobalPoint>(p2[0] + 9, p2[1]);
mouse.moveTo(point[0], point[1]);
expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
expect(h.state.selectionElement).toBeNull();
expect(h.state.selectedElementIds[arrow.id]).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect(
(h.elements[0] as ExcalidrawLinearElement).points[1][0],
).toBeCloseTo(p2[0] - p1[0] + 40);
});
it("grabs the label when the covering element is below the arrow", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([createOccluder(), arrow, label]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
expect(
(h.elements[2] as ExcalidrawTextElementWithContainer).labelPosition,
).toBeCloseTo(0.75);
});
it("does not grab the label when it is covered by an element above the arrow", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label, createOccluder()]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
it("grabs an elbow arrow's label lying over an intermediate route point", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 100,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 0),
pointFrom<LocalPoint>(100, 100),
],
elbowed: true,
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 30,
}),
// the arc-length middle of this symmetric elbow sits on the
// rounded corner, right next to the route point at (100, 0)
labelPosition: 0.5,
} as ExcalidrawTextElementWithContainer;
API.setElements([
{
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
label,
]);
mouse.reset();
// (not by a click, whose pointerup would normalize — reroute — this
// hand-built elbow arrow)
act(() => h.app.selection.select(arrow.id));
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// inside the label AND within the hit radius of the route point at
// (100, 0) — pre-fix the route point swallowed this pointerdown and
// the label never moved
const grabPoint = pointFrom<GlobalPoint>(97, 3);
drag(
grabPoint,
pointFrom<GlobalPoint>(grabPoint[0] - 40, grabPoint[1]),
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).not.toBe(0.5);
});
it("gives the segment midpoint handle precedence over the label on top of it", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
2,
);
// the label sits centered on the midpoint knob; dragging there must
// bend the arrow, not slide the label
drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
3,
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
it("leaves the segment midpoint handle grabbable under a covered label", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label, createOccluder()]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
2,
);
// the midpoint handle sits under the label, which is itself covered
drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
expect(
h.state.selectedLinearElement?.initialState.segmentMidpoint.value,
).not.toBeNull();
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
3,
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
});
});
describe("Test moving linear element points", () => {
it("should move the endpoint in the negative direction correctly when the start point is also moved in the positive direction", async () => {
const line = createThreePointerLinearElement("arrow");
const [origStartX, origStartY] = [line.x, line.y];
act(() => {
LinearElementEditor.movePoints(
line,
h.app.scene,
new Map([
[
0,
{
point: pointFrom(
line.points[0][0] + 10,
line.points[0][1] + 10,
),
},
],
[
line.points.length - 1,
{
point: pointFrom(
line.points[line.points.length - 1][0] - 10,
line.points[line.points.length - 1][1] - 10,
),
},
],
]),
);
});
expect(line.x).toBe(origStartX + 10);
expect(line.y).toBe(origStartY + 10);
expect(line.points[line.points.length - 1][0]).toBe(20);
expect(line.points[line.points.length - 1][1]).toBe(-20);
});
it("should move midpoints with the element via the `moveMidPointsWithElement` option without storing it", () => {
const line = createThreePointerLinearElement("arrow");
const [origX, origY] = [line.x, line.y];
const origMidPoint = line.points[1];
const origEndPoint = line.points[2];
act(() => {
LinearElementEditor.movePoints(
line,
h.app.scene,
new Map([
[0, { point: pointFrom<LocalPoint>(10, 10) }],
[
2,
{
point: pointFrom<LocalPoint>(
origEndPoint[0] + 10,
origEndPoint[1] + 10,
),
},
],
]),
undefined,
{ moveMidPointsWithElement: true },
);
});
expect(line.x).toBe(origX + 10);
expect(line.y).toBe(origY + 10);
// local coords unchanged => the midpoint moved along with the element
expect(line.points[1]).toEqual(origMidPoint);
expect(line.points[2]).toEqual(origEndPoint);
expect(line).not.toHaveProperty("moveMidPointsWithElement");
});
it("should preserve original angle when dragging endpoint with SHIFT key", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
enterLineEditingMode(line);
const elementsMap = arrayToMap(h.elements);
const points = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
// Calculate original angle between first and last point
const originalAngle = Math.atan2(
points[1][1] - points[0][1],
points[1][0] - points[0][0],
);
// Drag the second point (endpoint) with SHIFT key pressed
const startPoint = pointFrom<GlobalPoint>(points[1][0], points[1][1]);
const endPoint = pointFrom<GlobalPoint>(
startPoint[0] + 4,
startPoint[1] + 4,
);
// Perform drag with SHIFT key modifier
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.downAt(startPoint[0], startPoint[1]);
mouse.moveTo(endPoint[0], endPoint[1]);
mouse.upAt(endPoint[0], endPoint[1]);
});
// Get updated points after drag
const updatedPoints = LinearElementEditor.getPointsGlobalCoordinates(
line,
elementsMap,
);
// Calculate new angle
const newAngle = Math.atan2(
updatedPoints[1][1] - updatedPoints[0][1],
updatedPoints[1][0] - updatedPoints[0][0],
);
// The angle should be preserved (within a small tolerance for floating point precision)
const angleDifference = Math.abs(newAngle - originalAngle);
const tolerance = 0.01; // Small tolerance for floating point precision
expect(angleDifference).toBeLessThan(tolerance);
});
});
});