193 Commits
Author SHA1 Message Date
zsviczian 2c3dcc06ec fix(editor): prevent frame-drag lag when selecting large groups (#12692)
fix: avoid repeatedly selecting the same group during frame dragging
2026-11-19 20:01:22 +01:00
David Luzar c0a0ca348f feat(editor): pick the flowchart Alt+arrow target by a single distance score (#12646)
* fix(editor): Enter/Esc only close the shape switch popup

Esc no longer also deselects, and Enter no longer enters text/line editing.

* feat(editor): pick the flowchart Alt+arrow target by a single distance score

Replace the in-line/linked/cone/past-edge tiers with one score per node
(forward + (k * sideways)² / forward), so the nearest node that looks next in
the pressed direction wins; links only break near-ties.
2026-11-16 16:23:22 +01:00
David Luzar 82190fb28f feat(editor): w wrap tweaks: frame what's inside the selection, keep unbound containers (#12638)
* fix(editor): keep restored z-indices on undo/redo unless taken

Undo/redo generated a new fractional index for every element it moved in
the z-order, even when the restored index was still valid. Later history
entries refer to the original indices, so undoing several z-order changes
in a row could restore a different stacking order.

* fix(editor): frame deselected elements within the selection on `w`

Wrapping the selection in a frame now also takes in deselected elements
that are inside the selection's bounds, or overlap them while reaching out
by no more than the frame's padding (the frame grows to fit them; a frame
around an image keeps the image's size). Groups go in whole.

The frame takes the place of its lowest child in the z-order instead of
going on top, so that it stays below the elements overlapping it.

* feat(editor): `w` keeps the containers it unbinds texts from

Unwrapping a labeled container with `w` now unbinds its text and keeps
both selected, as the "unbind text" action does. Only a container that
`w` itself wrapped a text in is removed, while the selection stands.

The next `w` puts the unbound texts back into their containers as they
sat in them.
2026-11-15 17:23:19 +01:00
David Luzar 9e9621b873 feat(editor): text auto-resize: resize from the editor, Alt+W toggle, wider wrap when zoomed out (#12634)
* fix(editor): keep the text auto-resize toggle on the box while typing

The toggle was positioned from `appState.editingTextElement`, the element
as it was when editing started, so it stayed put as lines were added or
removed. Resolve the current element instead, for the hit test too.

* feat(editor): resize a text from its sides while editing it

Dragging the left or right side of the free text being edited sets the
width it wraps at, without leaving the editor (a mere click there still
submits). The edited text isn't reliably the selection, so the drag is
handled by the editor rather than the selection's transform handles —
with grid and object snapping, as when resizing on the canvas.

* feat(editor): let a typed or pasted text grow wider when zoomed out

Below 100% zoom, the width a text wraps at is TEXT_MAX_WRAP_WIDTH on
screen rather than in scene units, up to TEXT_MAX_WRAP_WIDTH_ZOOMED_OUT.

* feat(editor): toggle text auto-resizing with Alt+W

On the selected free texts (on if any of them wraps, else off) and on the
text being edited. Turning it off keeps the text's width, wrapping at it —
at the width a typed text stops growing at, if wider.

Zen mode (Alt+Z) now goes by the key's letter too where the layout gives
one, as on AZERTY both would otherwise claim the key labelled W.

* feat(editor): hint at Alt+W for a wrapped text and while editing a text

The hint for editing now also takes precedence over the one for a selected
text: a text just created is selected while it's edited.

* feat(editor): show the side of an edited text that can be dragged to wrap it

A text that doesn't wrap yet has no box showing its sides while it's
edited: the side under the pointer is now drawn (dashed, as the box of a
wrapped text), along with the resize cursor.

* fix(editor): no stale cursor or hidden transform handles around a text being edited

- the canvas kept the cursor of what was hovered before editing (the
  selected text's move cursor, a resize handle's), which flashed once the
  pointer left the editor: it's reset as editing starts
- a text just created is selected while it's edited, so its transform
  handles, which aren't drawn then, still resized it (ending the edit)

* fix(editor): no gap or cursor flash between a text's editor and its side handles

- the side handles of the text being edited get a hit test of their own:
  the selection's left the pixel at the text's right edge to neither the
  editor nor the handle
- the canvas is given, from over the editor, the cursor of what the pointer
  would leave the editor onto: the browser shows the canvas' cursor as it is
  when the pointer gets there, and what the canvas then sets a frame later

* fix(editor): give a text made to keep its width a pixel to spare

A text exactly as wide as its longest line is on the verge of wrapping:
Chrome lays the editor's text out in 1/64px steps, rounding each run of it
up (a line being split into more runs as it's edited), so the line could
wrap in the editor alone.
2026-11-15 13:10:59 +01:00
David Luzar 3a317b55f5 fix(editor): stop centered text lines jittering while typing (#12623)
* fix(editor): stop centered text lines jittering while typing

The text editor was placed by `left`/`top` and zoomed by a scale
transform. Browsers round a scaled element's layout offset to whole
pixels, so as a center- or right-aligned text grows (moving the editor
by fractions of a pixel) its other lines shifted by up to 1px per
keystroke at any zoom other than 100%. Place the editor by the
transform's translate instead, which is kept exact.

* fix(editor): stop the other lines' glyphs shimmering while typing

- Anchor the editor's transform at the text's alignment point (origin
  0 0), so it doesn't move while typing; only the box's own anchor
  (a whole or half px) changes.
- Give non-wrapping editors a whole-px width, so the browser's rounding
  of each line's centering offset stays constant. Wrapping editors keep
  their exact width, where the canvas wraps the text too.
- Grow the editor's box to its text when a font's glyphs overflow it,
  so the browser doesn't scroll the text to reveal the caret on each
  keystroke (which shifted the other lines).

* test(editor): update the text editor style snapshot for its new placement
2026-11-14 13:47:03 +01:00
Dan DekkerandMark Tolmacs 609f0f2fff perf(editor): avoid redundant canvas transforms for cached elements (#12489)
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
2026-11-12 17:46:09 +01:00
David Luzar 1440f2d2f8 feat(editor): minimap + zoom menu (#12605)
* feat(editor): add a toggleable minimap

- bottom-left above the canvas actions; toggled via the footer button,
  Alt+M, the context menu, command palette and Preferences
  (`appState.minimapEnabled`, browser-persisted)
- elements drawn as single-color blocks (polylines for lines/arrows/
  freedraw, outlines for frames), rendered in a web worker on an
  OffscreenCanvas with a main-thread fallback; the controller, renderer and
  worker are lazy-loaded chunks
- drag the viewport (or press outside of it to center it), limited to one
  viewport size past the content, with edge auto-pan; wheel zooms around
  the viewport center
- locked viewports keep the minimap scale frozen while rubberbanding and
  snapping back; `viewport.beginGesture()` holds the overscroll during the
  drag
- the viewport rect turns opaque when small; the styles panel stays clear
  of the minimap (and the tablet pen-mode button); unavailable in editors
  shorter than 500px
- theme class is now applied before state-change listeners run
- `Scene.onUpdate` unsubscribe no longer throws after the scene is destroyed

Claude Fable 5.2 + Claude Opus 5.5 (xhigh)

* feat(editor): zoom menu in place of the zoom buttons

- the zoom island holds the zoom level and the minimap toggle (sharp where
  they meet); the -/+ buttons are gone
- clicking the zoom level opens a menu: zoom in/out, reset zoom, and the
  three zoom-to-fit actions, each with its shortcut
- zoom level's pressed/focus rings are inset, so the toggle can't cover them
- smaller gap between the styles panel and the minimap
- zoom in/out/reset actions no longer render their own buttons

Claude Fable 5.2 + Claude Opus 5.5 (xhigh)

* feat(editor): zoom menu fit items, no minimap shortcut, announcement dot

- zoom menu: zoom in/out, then "Zoom to fit" (Shift+1), "Zoom to
  selection" (Shift+2) and "Reset zoom" (Shift+0, which it already
  accepted); "Zoom to fit selection" (Shift+3) is no longer listed
- minimap: drop the Alt+M shortcut (action, help dialog, tooltip, menus)
- TEMPORARY pulsing dot on the minimap toggle announcing the minimap,
  until 2026-11-19, for editors that loaded with content; dismissed for
  good once the minimap is opened
- "Show hints" preference renamed "Toolbar hints"

Claude Opus 5.5 (xhigh)

* chore(repo): remove the minimap scroll-lock demo button

The dev-only "Scroll lock demo" button and the commented-out initialState
in excalidraw-app were for testing the minimap against a locked viewport
and aren't meant to ship.

Claude Opus 5.5 (xhigh)
2026-11-12 17:01:41 +01:00
David Luzar dd2f8fc32b fix(editor): don't clip arrows to their frames (#12516)
* fix(editor): don't clip arrows to their frames

Arrows (and their labels) are no longer clipped to the frame they belong
to, so they can connect elements across and out of frames. They stay
members of their frame, so they're still moved, copied, deleted and
exported with it.

- Not clipped on the canvas or in SVG, and hit (click, hover, box and
  lasso selection) outside their frame too.
- Exporting a frame includes other frames' arrows reaching into it, as it
  does other non-children overlapping it.
- Moving a frame (dragging it, with the arrow keys or from the stats
  panel) keeps its arrows bound to the elements that don't move with it,
  instead of unbinding them. Their free points move with the frame, elbow
  arrows are routed once per move and keep their fixed segments.
- mutateElement no longer ignores an elbow arrow's x/y update to 0.

Fixes #6749
Fixes #7827

Claude Opus 5.5 (xhigh reasoning)

* docs(changelog): arrows aren't clipped to frames

Claude Opus 5.5 (xhigh reasoning)

* fix(editor): take arrows out of frames once neither of their ends is in them

An arrow belongs to its frame only while one of its ends is in it: bound to
an element in the frame, or, unbound, inside it. Checked when an arrow is
finished (drawn, or an end dragged), when a drag ends (the dragged arrows and
those bound to the dragged elements), and when a frame's children are
recomputed (resize, grouping). An arrow bound only to elements outside its
frame thus no longer gets cut, duplicated or exported with it.

Claude Opus 5.5 (xhigh reasoning)

* fix(editor): take arrows out of frames when nudged or moved from the stats panel

The arrow keys and the stats panel move arrows too, so check there as well
whether a moved arrow still has an end in its frame.

Claude Opus 5.5 (xhigh reasoning)
2026-11-03 09:20:50 +01:00
David Luzar 8bcdca4526 fix(editor): ignore deleted elements when inserting frame children (#12510)
fix(editor): place new frame children below the frame despite deleted children

Deleted frame children keep their frameId and index, so one left above the
frame made new children of that frame (created or dragged in) go above it,
up to the top of the canvas, until a reload dropped the deleted elements.
Only live children count now.

Claude Opus 5.5 (xhigh)
2026-10-31 17:48:47 +01:00
David Luzar 2610ebae0c feat(editor): Alt+arrows move to the flowchart node that's visually next (#12502)
* feat(editor): Alt+arrows move to the flowchart node that's visually next

Alt+arrow navigation used to follow only the arrows bound to the pressed
side of the selected node, cycled through siblings on repeated presses,
and fell back to any linked node when nothing was that way.

It now picks, among the nodes of the selected node's flowchart, the
nearest node of the first non-empty tier:
1. nodes in line (sharing the row for left/right, the column for up/down)
2. linked nodes whose center lies past the selected node's edge
3. nodes whose center lies in the 45° cone of the pressed direction
4. any other node whose center lies past that edge

Near-ties (within 10%) go to linked nodes, successors first, then
reading order. Pressing the opposite of the last move goes back where it
came from, also after releasing Alt.

Claude Opus 5.5 (xhigh)

* docs(packages/excalidraw): changelog for visual flowchart navigation

Claude Opus 5.5 (xhigh)

* feat(editor): forget the way back when Alt is released

Going back where the last Alt+arrow move came from only applies while Alt
is still held; a new Alt session navigates from scratch.

Claude Opus 5.5 (xhigh)

* feat(editor): drop the Alt+arrow way back

Pressing the opposite of the last move no longer returns to the node it
came from. As an override it beat even nodes in line (B ← went back down
to A instead of to C in B's row); navigation is now stateless, so a key
from a given node always goes to the same place.

Claude Opus 5.5 (xhigh)

* feat(editor): link flowchart nodes through non-elbow arrows too

Any arrow bound at both ends now links its nodes, for Alt+arrow
navigation and for the nodes Ctrl+arrows keeps new nodes clear of.

Claude Opus 5.5 (xhigh)

* fix(editor): break flowchart navigation ties by alignment before reading order

Of two equally near in-line nodes, both linked, Alt+arrow went to the
upper one even when the other was level with the selected node's center.
Offsets within a pixel still tie, so float noise in fanned-out siblings
doesn't decide between them.

Claude Opus 5.5 (xhigh)

* perf(editor): walk flowchart links in one pass over the scene

Collecting a node's flowchart rescanned every arrow in the scene for each
node visited, so Alt+arrow and Ctrl+arrow in a large chart paid chart
nodes × all arrows (~10 ms per press at 1,000 nodes). A neighbour map
built in one pass makes it linear.

Claude Opus 5.5 (xhigh)
2026-10-31 11:51:48 +00:00
David Luzar a758e93d6a fix(editor): restore centered flowchart node creation (#12500) 2026-10-30 20:19:53 +01:00
David LuzarandMark Tolmacs c711e80ec5 fix(editor): route elbow arrows with a single corner where one fits (#12458)
* fix(editor): route elbow arrows with a single corner where one fits

Elbow arrows keep a padding around the elements they connect, and enter
the end element from the edge of it. When the end element is closer to the
start's side than that (e.g. just below it), the route stepped aside to that
edge first, with a few pixels' jog.

When the elements can be connected with a single corner instead (leaving the
start and entering the end the way they head, both legs clear of both
elements, the legs with arrowheads long enough to fit them), that route is
used, before (and instead of) routing on the grid.

As a leg without an arrowhead can be short now, changing the arrowheads of
an elbow arrow (from the picker, by flipping it, or by pasting styles)
routes it again, to make room for them.

Claude Opus 5.5 (xhigh)

* fix(editor): route elbow arrows with two corners where they fit

When the arrow leaves the start element and enters the end one heading the
same way (e.g. from the bottom of one to the top of another below and to the
side of it), and they're closer than the padding the arrow keeps around
them, the route had a few pixels' jog between the two paddings.

Such arrows are now routed with two corners, the same way as with a single
one: turning halfway, as on the grid when there's room. When only one end
has an arrowhead, and halfway would leave it a shorter leg than the
padding, the turn moves toward the other end (keeping enough of that leg to
round its corner).

Claude Opus 5.5 (xhigh)

* fix(editor): keep elbow arrows' simple routes when their fixed segments go

When an element moves so that an elbow arrow's segment lines up with its
fixed one (e.g. moving the start element a grid step, onto the fixed
segment's level), they're merged and the fixed segment dropped, and the
arrow re-routed, as when a fixed segment is released. That re-route went
straight to the grid, without trying the one or two corner route first,
which left the jog that route avoids until the arrow was routed again.

Any route on the grid now tries the simple route first.

Claude Opus 5.5 (xhigh)

* refactor(editor): route and clean elbow arrows in one place

routeElbowArrow() now tries the one or two corner route, falls back to the
grid, and removes short segments and points between collinear ones, so its
three callers don't repeat that. They also pass getElbowArrowData()'s result
through, rather than destructuring and rebuilding it.

Claude Opus 5.5 (xhigh)

* refactor(editor): name elbow arrow route getters and updates apart

routeElbowArrow() returns a route's points, and rerouteElbowArrow() an
element update routing the arrow again, so they're getElbowArrowRoute() and
updateElbowArrowRoute() now (and the grid routing getElbowArrowGridRoute()).

Claude Opus 5.5 (xhigh)

* fix(editor): draw elbow arrows' jogs too short to see straight

While an element bound to an elbow arrow is moved so that a fixed segment
lines up with the ones around it, the arrow keeps a zero-length jog between
them until it's released, and rough.js drew the jog's two corners as a knot.

A segment shorter than 1px between two longer ones heading the same way is
now drawn straight. Corners of short segments in a row, and short U-turns,
keep their corners.

Claude Opus 5.5 (xhigh)

* fix(editor): keep elbow arrows' simple route legs long enough to round

A leg of the one or two corner route without an arrowhead only had to
outlast the cleanup of short segments (1px), so the route could leave stubs
a few pixels long (e.g. from the side of one element to the facing side of
another just below and beside it, with no arrowheads). Their corners lost
their rounding, and the arrow looked like a line hugging the element,
coming from the wrong side.

Every leg is now longer than half the corner radius, keeping at least a
quarter of the rounding, and one with an arrowhead also fits it. Shorter
legs go to the grid routing instead.

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix(editor): keep elbow arrows' simple routes clear by the binding gap

The one or two corner route kept a fixed 5px from the elements it connects,
rather than the binding gap the arrow keeps at its ends (which grows with
the element's stroke). Where an element's bounds reach past the point the
arrow binds to (e.g. an ellipse or a diamond entered below its top), a leg
could pass closer to it than that, and over a thick stroke.

The route now keeps clear of each element by its binding gap.

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* refactor(editor): check elbow arrow route legs with doBoundsIntersect()

segmentCrossesBounds() repeated doBoundsIntersect()'s overlap check, so it
now passes it the segment's bounds instead.

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* refactor(editor): tidy up the elbow arrow route getters

getSimpleRoute() worked out the last leg of a one corner route also for two
corner ones, which then replaced it, and took a Pick<> of the data its only
caller passes whole. getElbowArrowGridRoute()'s doc listed parameters it
doesn't take.

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:49:38 +01:00
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
David Luzar b7de45e881 feat(editor): fit arrowheads to short last segments & fill them along their outline (#12439)
* feat(editor): fit arrowheads to short last segments

Arrowheads used to shrink to half of the last segment, so multi-segment
arrows ending in a short segment got near-invisible heads. They now use
the whole last segment, or extend past its start where the shape allows:

- triangle: grows until its base reaches the previous segment
- arrow: widens as it shrinks (20° -> 30°), grows to half its size
  while its sides stay a stroke width off the previous segment
- circle: grows freely (no direction), also on curved arrows
- bar: ends stay closer to the tip than to the previous segment
- diamond: back vertex reaches the corner
- cardinality markers: scaled as a whole to fit the last segment
- elbow arrows: the corner rounding is taken into account

Single-segment and curved arrows keep the old sizing, except circles.

Claude Opus 5.5 (xhigh)

* fix(editor): fill arrowheads along their outline

rough.js jitters a solid fill separately from the outline (by up to 2px),
which on shapes as small as arrowheads made the fill stick out, and the
repeated closing point of triangles/diamonds drew a stray hair at the tip.

- triangle, diamond and circle arrowheads are drawn as a single rough
  stroke, and filled along that stroke
- polygon arrowheads keep their corners in place, only edges bow
- fewer ops: faster to generate and draw

Claude Opus 5.5 (xhigh)
2026-10-23 12:48:01 +02:00
David Luzar a3fdf471ee feat(editor): support Instagram embeds (#12373)
* feat(editor): support Instagram embeds

Instagram post and reel links (/p/, /reel/, /reels/, /tv/, also
username-prefixed) embed via instagram.com/<type>/<code>/embed/.
Uncaptioned so the height only depends on the media; 400x720 fits
portrait posts and reels.

Pasting Instagram's embed code works too: its loader <script> sits on a
separate line, which made the paste fall back to text.

Claude Opus 5.5 (1M context), reasoning: xhigh

* fix(editor): match loose script end tags in embed code paste

Addresses CodeQL "Bad HTML filtering regexp".

Claude Opus 5.5 (1M context), reasoning: xhigh
2026-10-20 10:06:36 +02:00
d3a9c2a195 fix(packages/excalidraw): complete cross-document runtime ownership (#11997)
* fix: complete cross-document runtime ownership

* fix: schedule cross-document animations in owner window

* fix: Prewarm the right font even if it's not Excalifont

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Hyperlink and tooltip host staleness issues

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Various hyperlink fixes

* feat: Host abstraction

* fix: exportToSvg support for document override

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Remove caches

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Refactor tests (cut non-critical)

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Break out host from App

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: hold after release fixes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: repaint when link image decode is complete per app

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Font loading per-doc test

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Lint

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: draw SVG frame labels without text measurement

Frame labels were baked into exports as measured, ellipsis-truncated text
elements, which made `exportToSvg` depend on a canvas (through the render
environment) for the only text it ever measures.

- add `getFrameLabel` (element package): a measurement-free label spec --
  position, font, color, arithmetic height, the frame's width as max width
- SVG: draw labels from the spec in the frame branch, full title clipped to
  the frame's width; extract `appendSvgTextLines` so text elements and
  labels produce identical markup
- canvas: unchanged output (measured, truncated text elements), now built
  from the same spec
- fit label boxes into the SVG export bounds explicitly (`extraBounds`)
- test: SVG export of a named frame succeeds with a render environment
  whose `createCanvas` throws and creates no canvas through `document`

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: measurement-free embed placeholders; no render environment in SVG export

The placeholder drawn for an embed that isn't rendered live was the last
text `exportToSvg` measured, which kept a canvas (via the render
environment) in the SVG path and made headless SVG export throw on any
scene with an embed unless the process had been polyfilled.

- show the placeholder as a single line capped at 30 characters
  (`getPlaceholderLinkText`: scheme and `www.` dropped, ellipsis) instead
  of wrapping the whole link: at or below that length the existing
  `width / length` font size fits the box by construction, so nothing is
  measured, wrapped or clipped, and output is identical on every host. The
  full link stays on the element's `<a href>` in SVG
- `newTextElement` accepts pre-computed `metrics` to skip measuring
- drop `renderEnvironment` from `SVGRenderConfig`, `exportToSvg` and the
  `@excalidraw/utils` signature: SVG export's only host dependency is its
  owner document
- throw a guided error from the default canvas/image factories when there
  is no `document`/`Image`, instead of a bare ReferenceError
- tests: placeholder text capping and layout; SVG export of an iframe and
  a long-link embed with a render environment whose `createCanvas` throws

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix: scope top picks drag to source window

* feat: StickyNotes support

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* Revert "fix: measurement-free embed placeholders; no render environment in SVG export"

This reverts commit 886bea142. Rich text makes SVG export measure text
anyway (explicit x per line, run boundaries, baselines), so placeholder
labels go back to being measured and wrapped like on canvas, through the
render environment.

Kept: the guided errors thrown by the default canvas/image factories when
there is no `document`/`Image`.

Claude Opus 5.5 (xhigh)

* Revert "fix: draw SVG frame labels without text measurement"

This reverts commit 295e7d88b. SVG export measures text again (rich text
needs it regardless), so both formats go back to master's single path:
frame labels baked in as measured, truncated text elements, measured
through the export's render environment. Drops `getFrameLabel` and the
SVG label renderer.

Claude Opus 5.5 (xhigh)

* export: one `config.environment` for every format, `document` for SVG

SVG exports take the same environment as canvas ones: they measure text
(frame labels, embed placeholders) through its `createCanvas`, and are
built in its `document` (was the SVG-only `ownerDocument`).

Claude Opus 5.5 (xhigh)

* RenderEnvironment: carry the `document`

The environment is the one host parameter: its `document` is what SVG
exports are built in (the editor's owner document by default), so export
call sites pass a single environment instead of an environment plus an
`ownerDocument`. `exportCanvas` drops its `ownerDocument` option, and
`config.environment.document` defaults to the environment's.

Rich text's DOM layout will read the same member, rather than threading
`ownerDocument` through the measuring functions next to the environment.

Claude Opus 5.5 (xhigh)

* drop the process-wide `setRenderEnvironment` / `resetRenderEnvironment`

Every render and export now takes its environment explicitly: exports
through `config.environment`, the editor through its `renderEnvironment`
prop. Text measured outside both (e.g. creating elements on a server) has
`setCustomTextMetricsProvider`. A second, global way to configure the same
thing would be state shared by every job in the process, which is what
per-call export environments avoid. The default is now a constant
(the browser's).

Claude Opus 5.5 (xhigh)

* render: log per-element failures on export too, rather than throwing

As in the editor (and on master): one element that fails to render is
logged and skipped, so the rest of the exported scene survives it rather
than the whole export failing.

Claude Opus 5.5 (xhigh)

* RenderEnvironment: carry the text metrics provider

`textMetrics` replaces the per-environment registry of
`setCustomTextMetricsProvider(provider, env)`, which looked providers up
by the environment's identity, so any rebuilt environment (as exports
build one from `config.environment`) silently lost them. It now travels
with the environment, and `config.environment.textMetrics` measures an
export's text. The global `setCustomTextMetricsProvider(provider)` stays
for text measured outside both (e.g. elements created on a server).

Exports use a complete `config.environment` as-is (the editor's keeps its
caches warm), and document that it needn't be the same object across
exports. Frame label truncation measures through the environment too,
rather than on a canvas of its own.

Claude Opus 5.5 (xhigh)

* render: restore the canvas state when an element fails to draw

The scene renderer logs a failing element and carries on, but the
`save()`s it had made were never restored: its transforms and frame clip
stayed on the context for every element after it (a failing freedraw at
(80, 30) moved the next rectangle from (10, 10) to (90, 40)). Every
`save()` around drawing now restores in a `finally` (`withSavedContext`).
Pre-existing on master, in the editor and on export.

Claude Opus 5.5 (xhigh)

* export: truncate frame names down to "...", or none, to fit the frame

When not even one character plus the ellipsis fit, the frame name kept
its full title (overflowing narrow frames into their neighbors) while
reporting the frame's width. It now shrinks to just "...", and is dropped
where even that doesn't fit. Pre-existing on master.

Claude Opus 5.5 (xhigh)

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 05:53:27 +02:00
David Luzar e1b7aacb35 feat(packages/excalidraw): replace the export functions with exportScene (#12347)
* [export] rewrite - init

* restore elements + filter deleted in export API (restores #11470 behavior)

* fix snaps

* port export callers added on master to the new API + snaps

- renderOverrides (#12100), sticky notes (#12064) and arrow-label hole
  (#10947) tests called the old positional exportToSvg/exportToCanvas
- embedded-scene snapshots gain master's new element fields (created,
  baseFontSize, labelPosition); decoded payloads match master's

Claude Opus 5.5 (xhigh)

* restore elements in embedded scene + json clipboard export (restores #12060 behavior)

- master's #12060 made every public export entry point restore its input
  (legacy elements reach lower-level code with `created: null`), incl. the
  PNG metadata embed and the json clipboard copy in the removed
  @excalidraw/utils wrappers
- SVG embed now serializes the restored, non-deleted elements (same as
  master's utils path), PNG embed serializes restoreElements(data.elements)
  and json clipboard copies the non-deleted restored elements
- port #12060's utils tests to the new API, observing renderers/serializer
  instead of the (now identical) scene export functions

Claude Opus 5.5 (xhigh)

* make config.canvasBackgroundColor the single export background knob

- background resolved once in configExportDimension; exportToSvg no longer
  reads appState.exportBackground (now omitted from ExportSceneData's
  appState type), and honors `canvasBackgroundColor: false`
- outline arrowheads (circle/triangle/diamond_outline, cardinality_zero_*)
  are filled with the resolved background color, also when the background
  isn't painted (as on master) — the canvas path filled them transparent,
  showing the arrow's shaft through them; SVG ignored the config color
- JPEG: `canvasBackgroundColor: false` falls back to the default background
  (+ warning) instead of rendering black; no more warning for the default
- callers (exportCanvas, ImageExportDialog, library/chart/publish previews,
  AI) pass the background via config only

Claude Opus 5.5 (xhigh)

* resolve export theme before creating frame labels

- frame labels were colored by appState.exportWithDarkMode, ignoring
  config.theme (export dialog's dark toggle), and in dark exports the
  dark-theme label color got dark-filtered again by the renderer
  (#7a7a7a -> #848484)
- theme is now resolved once in configExportDimension; dark labels are
  pre-reverted so they render with the editor's frame name color

Claude Opus 5.5 (xhigh)

* drop appState.exportWithDarkMode theme fallback in export

- `config.theme` is the only theme input (defaults to light); the type
  already omitted `exportWithDarkMode` from `data.appState`
- callers that relied on the fallback (PublishLibrary item preview, AI
  frame export) pass `theme` explicitly, keeping their behavior

Claude Opus 5.5 (xhigh)

* exportToClipboard: don't restore appState before exportToSvg (already restored there)

Claude Opus 5.5 (xhigh)

* remove unused getExportSize, type getCanvasSize's [x, y, width, height] (not Bounds)

Claude Opus 5.5 (xhigh)

* fix typos in export comments/JSDoc

Claude Opus 5.5 (xhigh)

* port with-script-in-browser example to the new export API

- exportToSvg/Blob/Canvas/Clipboard take `{ data, config }`; theme via
  `config.theme`, padding 10 kept explicit (new default is 0)
- dropped the no-op `width`/`height` appState overrides from the SVG export

Claude Opus 5.5 (xhigh)

* call getDimensions once, ignore it when widthOrHeight is set

- with an explicit `fit: "contain"`, getDimensions ran twice (the second
  time on its own output); it now supplies width/height (+ scale) once,
  and `contain` scales the content into that frame
- getDimensions + widthOrHeight both applied; widthOrHeight now wins (with
  a warning), like width/height/maxWidthOrHeight already did
- `fit: "none"` (the E+ export server path) renders identically

Claude Opus 5.5 (xhigh)

* type the export size options as mutually exclusive

- `width`/`height`, `maxWidthOrHeight`, `widthOrHeight` and `getDimensions`
  are now a union where the unused options are `?: never`, so combining
  them is a type error (runtime still ignores/warns for JS callers)
- the `never` keys are remapped over `keyof`, so every option keeps its
  JSDoc in completions & hovers (verified via the TS language service)

Claude Opus 5.5 (xhigh)

* replace getDimensions with a `scale` function, round the canvas size

- `config.scale` also accepts `(width, height) => number`, called with the
  export dimensions at scale 1 (padding included) — covers content-dependent
  scaling (e.g. E+'s pixel budgets) without the getDimensions round trip
- remove `getDimensions`: its returned `scale` replaced `config.scale` and
  multiplied the returned size, so callers thinking in output pixels had
  to divide it back out
- exportToCanvas rounds the canvas size instead of letting the canvas
  truncate it (float noise like 28.999999999999996 lost a pixel); half
  pixels now round up (frame label area 20.5px, mermaid preview 89.5px)

Claude Opus 5.5 (xhigh)

* align fit/padding/position export docs with the code

- `fit` defaults to "contain" when `width`/`height` is set, otherwise
  "none" (the doc said the opposite); dropped the unimplemented
  "x/y force none" claim
- padding is always subtracted for `maxWidthOrHeight`/`widthOrHeight`
  (they ignore `fit`), not added
- `position` values are "center" | "topLeft" (doc listed "none")

Claude Opus 5.5 (xhigh)

* derive a missing export width/height from the aspect ratio

- with `fit: "contain"` (the default when a size is given), passing only
  `width` or `height` now derives the other from the content's aspect
  ratio, as documented — it defaulted to the content's unscaled size,
  e.g. `{ height: 50 }` of 200x100 content gave a 200x50 canvas with
  60x30 content in wide empty bands (now 80x50 with padding 10)
- with `fit: "none"` the missing side stays the content extent

Claude Opus 5.5 (xhigh)

* default export `fit` to "none" when x/y is set

- `{ x, y, width, height }` was scaled to fit with `x`/`y` silently
  ignored (`fit` defaulted to "contain" whenever a size was given); an
  explicit region now crops by default, `fit: "contain"` still opts in
  (and ignores `x`/`y`, as now documented)

Claude Opus 5.5 (xhigh)

* ignore export x/y when the content is scaled to fit

- with `fit: "contain"`, `maxWidthOrHeight` or `widthOrHeight`, `x`/`y`
  shifted the fitted content by a mix of scene units and pixels; they're
  now dropped with a warning, which the previous commit already
  documented (its "ignored" claim was based on a coincidental probe)

Claude Opus 5.5 (xhigh)

* pad an export x/y region on all sides

- with `position: "center"` (the default), the centering adjustment also
  ran on axes pinned by `x`/`y`, shifting the region by the padding: the
  canvas started exactly at `x`/`y` with all padding on the right/bottom
  (`position: "topLeft"` padded all sides); `position` now only applies to
  unpinned axes, as documented

Claude Opus 5.5 (xhigh)

* consolidate exportToCanvas/Blob/Svg into exportScene({ type, data, config })

- `type: "canvas" | "png" | "jpeg" | "svg"`, return type per `type`
  (overloads, plus a union overload for dynamic callers); per-type options
  are type-checked: `quality` only for jpeg, `embedScene` for png/svg,
  `renderEmbeddables`/`skipInliningFonts`/`reuseImages` for svg
- the format replaces `mimeType` (and its "image/jpg" typo handling)
- `appState.exportEmbedScene` -> `config.embedScene` (no longer read
  from `data.appState`); `data.files` is optional
- `config.createCanvas` -> `config.environment.createCanvas` (where
  #11997's render environment and richtext's text metrics will go)
- exportToCanvas/Blob/Svg are no longer exported (no aliases);
  exportToClipboard stays, routed through exportScene
- callers, the with-script-in-browser example and tests ported

Claude Opus 5.5 (xhigh)

* export: take only scene settings from data.appState, frameRendering -> config.frames

- `data.appState` is typed as (and stripped at runtime to) the scene
  settings a .excalidraw file stores; the renderer state is built from
  those + defaults, so editor state passed in (a live AppState: open
  dialog, cropping, frame highlight…) can't affect the output. It only
  supplies the default background and what `embedScene` embeds
- `appState.frameRendering` -> `config.frames: { name, outline, clip }`
- editor callers translate their export settings via one internal
  `getExportConfigFromAppState`; `exportCanvas` drops its redundant
  exportBackground/viewBackgroundColor options
- fixes the editor's SVG export ignoring `exportScale` (the branch's
  exportCanvas SVG path had dropped it; master passed it)

Claude Opus 5.5 (xhigh)

* type export positioning options as width/height-only

- `fit`, `position`, `x`, `y`, `origin` move into the size-option union's
  `width`/`height` member, so combining them with `maxWidthOrHeight` /
  `widthOrHeight` (which ignore them) is a type error; runtime unchanged
  (still ignores/warns for JS callers)
- docs stay visible in completions (same `keyof` remap as the size options)

Claude Opus 5.5 (xhigh)

* move export `loadFonts` into `config.environment`

- font loading is a host capability, next to `createCanvas` (svg gets
  `environment: { loadFonts }` only, as it creates no canvas)

Claude Opus 5.5 (xhigh)

* changelog: export API (exportScene, config, migration table)

Claude Opus 5.5 (xhigh)

* export: default padding back to 10, canvas at least 1px

- export bounds are geometric (no stroke width), so padding 0 cut half
  of the strokes on the content's edge and made flat content (a line)
  zero-height — the library/chart/publish previews, which inherited
  master's default of 10, rendered blank thumbnails for lines
- canvas dimensions never go below 1px (a 0-sized canvas can't be
  encoded); SVG snapshot sizes are back to master's

Claude Opus 5.5 (xhigh)

* export: clamp padding against the fitted size, before deriving from it

- the padding clamp used the content's unpadded size, so flat content (a
  horizontal line) lost its padding with maxWidthOrHeight/widthOrHeight
  (`{ padding: 10, maxWidthOrHeight: 400 }` → 200x0); it now only
  considers the target being fitted into
- a missing width/height was derived before clamping
  (`{ height: 10, padding: 10 }` → 0x10, SVG viewBox NaN/Infinity)
- a zero-extent content axis no longer yields a NaN scale under contain

Claude Opus 5.5 (xhigh)

* export: clip frame exports to the frame

- frame clipping was off for exportingFrame (to avoid the rounded
  per-element clip), relying on the canvas/SVG edge — which only crops
  when the export is exactly the frame; a larger export (size options)
  painted children and overlapping elements into the margins, and SVG
  frame exports had stopped clipping (master clipped them)
- everything drawn is now clipped to the frame with square corners: a
  canvas clip after the background (`renderConfig.clipToFrame`), and an
  SVG group with the frame's clip path; the background isn't clipped

Claude Opus 5.5 (xhigh)

* changelog: fill in PR numbers for the placeholder links

Claude Opus 5.5 (xhigh)
2026-10-18 20:24:17 +02:00
David Luzar 541653c7c9 fix(editor): frame membership, clipping and cut fixes (#12270)
* fix(editor): a frame snapped to an element's edges takes it in

A new or resized frame takes the elements (and groups) within it by their
outlines (not counting the stroke), to a hair beyond its edges, which
snapping leaves them at.

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): a frame always clips its children

As in SVG exports — a child inside the frame may still reach out of it with
its stroke — without checking geometry, but for children being dragged,
which are clipped only while still in it, as their drop decides. The
outline check remains for elements dragged into a frame.

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): cutting a frame takes its children along

Unlike deleting it, which leaves them: they're on the clipboard with the
frame, so pasting it back would duplicate them.

Claude Opus 5.5 (1M context), effort: medium
2026-10-12 14:33:19 +02:00
David Luzar 704db6803c feat(editor): w to wrap/unwrap selection (#12264)
* fix(editor): keep the text selected along with its container after unbinding

Claude Opus 5.5 (1M context), effort: medium

* feat(editor): `w` wraps or unwraps the selection

- a text and an empty container: binds the text
- texts (with any labeled containers): wraps each text in a container
- labeled containers: unwraps the texts and removes the containers,
  moving their arrows onto the texts; the next `w` on the untouched
  selection brings the same containers back where the texts are now
- a frame with its children, or all of a frame's children: removes the frame
- anything else without a frame: wraps it in a frame

"Wrap selection in frame" frames an image (and what lies on it) edge to
edge, and removes the frame when all of its children are selected.

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): unwrapping an arrow drops its point editor

The selection unwrapping (and rewrapping, and removing a frame) leaves is
resolved with its line editor, so a deleted arrow's editor doesn't linger.

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): rewrapping a note keeps the label's font size and color

A font size picked while the label was unwrapped becomes its base size, and
the note takes the label's ink (shared with binding via `getStickyNoteInk`).

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): resizing an unwrapped text doesn't move its rewrapped container

A font size change keeps the text's alignment edge and middle in place, so
the move is measured there rather than at the top left.

Claude Opus 5.5 (1M context), effort: medium

* fix(editor): binding, unbinding and framing resolve the arrow point editor

Binding text to an arrow selects it with its point editor; wrapping a lone
arrow in a frame, or unbinding an arrow's label (selecting both), drops it.

Claude Opus 5.5 (1M context), effort: medium

* feat(editor): wrapping a text draws a default rectangle in the text's color

Not the current item's style — a wrapped text is a label, and the rectangle
matches it.

Claude Opus 5.5 (1M context), effort: medium

* feat(editor): unbinding keeps the text as it rendered, at a fixed width

The freed text keeps its wrapping, width and position (not auto-resizing);
rewrapping it restores auto-resize. A fixed-width text keeps its top left
through font size changes, so a rewrapped container measures the text's
move there.

Claude Opus 5.5 (1M context), effort: medium
2026-10-12 11:35:45 +02:00
David Luzar 2df993fb39 fix(editor): resizing text by a corner follows the cursor on the axis it grows most (#12262)
Text scaled by the height alone, so a corner dragged sideways didn't follow
the cursor; it now scales as resizing keeping the aspect ratio does (which
text always does), by the axis that grows most.

Claude Opus 5.5 (1M), xhigh effort
2026-10-11 16:48:34 +02:00
David Luzar ef53e5417b feat(editor): crop editor modifiers as resizing, and double-click a handle to uncrop (#12260)
* fix(editor): shift in the crop editor: shift-click keeps it open, shift-drag moves the image along one axis

- shift-clicking the image being cropped no longer toggles it out of the
  selection (which ended cropping)
- dragging the image within its crop follows the drag offset, axis-locked
  with shift as dragging elements is, applied by its change since the
  previous pointer move (pointerDownState.drag.lastOffset) so the image
  still moves back right away after being dragged past its edge
- drops App.previousPointerMoveCoords, which only the crop drag used

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): alt-drag a crop handle to crop from the center

- cropElementFromCenter crops the opposite side by as much as the dragged
  one, keeping the element's center, as far as the image reaches on the
  nearer side; with shift, keeping the aspect ratio
- no alt drag threshold in the crop editor: alt-clicks don't cycle the
  selection there

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): clicking a crop handle no longer leaves the crop editor

A press on a crop handle hits no element, so a click on one without a move
in between counted as a click outside the image.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): double-click a crop handle to uncrop its sides

- in the crop editor, double-clicking a side's handle uncrops that side, a
  corner's its two sides, as dragging the handle out as far as the image
  reaches does (uncropElementSides)
- with alt, the opposite side(s) too, so alt on a corner uncrops it all;
  alt double-clicks aren't ignored in the crop editor, which doesn't cycle
  the selection

Claude Opus 5.5 (1M), xhigh effort

* refactor(element): uncrop and crop from the center through one bounds helper

- cropElementToBounds crops the image to bounds relative to the element
  (rotated and flipped with it); uncropElementSides and cropElementFromCenter
  only compute those bounds
- uncropElementSides no longer drives cropElement with a pointer past the
  image's edge, copying the crop it mutates, nor recurses for the mirrored
  side
- maybeUncropSides takes the selected image, and the pointer type from
  appState.lastPointerDownWith

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): arrows bound to an image follow the sides uncropped by a double-click

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): crop from the drag's start, as resizing does, so alt and shift apply mid-drag

- maybeHandleCrop crops the image as it was at pointer down
  (pointerDownState.originalElements) rather than as of the previous pointer
  move, and maybeHandleResize crops in the crop editor, so pressing or
  releasing alt or shift mid-drag re-crops right away, as resizing does
- cropElement no longer mutates the crop of the element it's given (which is
  now the drag's start state)

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): no invisible rotation handle in the crop editor

The crop editor draws no rotation handle, but pressing where it would be hit
it, and dragging it cropped the image ("rotation" includes "n"). A press
there is now one outside the image, which leaves the editor.

Claude Opus 5.5 (1M), xhigh effort

* refactor(element): crop an image as resizing it would resize it

- cropElement sizes the crop from the pointer as resizing does
  (getNextSingleWidthAndHeightFromPointer, from the center too), keeps it
  within the image from what stays put (the opposite side, or the center),
  and crops through cropElementToBounds; it replaces the per-handle cases,
  recomputeOrigin and cropElementFromCenter
- options as resizing's: { shouldMaintainAspectRatio, shouldResizeFromCenter }
  rather than a width aspect ratio (the element's, which is the drag's start)
- keeping the aspect ratio, a corner crops by the axis it grows most,
  relatively, as resizing does (rather than by pixels), and an axis dragged
  past what stays put has the minimal size rather than flipping
- an image already smaller than the minimal size crops no smaller, rather
  than jumping to it

Claude Opus 5.5 (1M), xhigh effort

* fix(element): the image no longer shifts by a pixel while cropping it

The crop editor drew the cropped image from its own bitmap, snapped to whole
pixels by its own corner, over the faded uncropped image's: as the corner
moved by fractions of a pixel (cropping from the center, or keeping the
aspect ratio along a side), the image within the crop shifted by a pixel
against the faded rest. Within the crop, it now draws the uncropped image's
bitmap at full opacity, clipped to the crop.

Claude Opus 5.5 (1M), xhigh effort
2026-10-11 16:37:37 +02:00
David Luzar e65eca999e refactor(editor): app.selection, and the rest of the selection tool out of App (#12258)
* refactor(editor): add AppSelection (app.selection) to select, add to, remove from and clear the selection

- select(element) for click-select, the alt-click cycle and the context menu;
  add(element) for the selection tool and the lasso's touch select (was a
  near-copy); remove(element) for shift-click; clear() replaces
  App.deselectElements and three inline copies
- isASelectedElement / isHittingCommonBoundingBoxOfSelectedElements move from
  the selection tool
- select() drops a stale line editor of a no longer selected arrow; the
  context menu no longer spreads all of this.state into its setState
- tests for the selection's frame, link selector and line editor rules

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): make the app.selection API generic over elements or ids, one or many

- select / add / remove take elements or ids, one or many (missing and
  deleted ones skipped)
- their rules become pure functions in App.selection.ts, for callers that
  need the next selection state rather than a setState (actions,
  duplication): getSelectionStateForElements (moved from @excalidraw/element,
  now keeping the current line editor), getSelectionStateAddingElements,
  getSelectionStateRemovingElements — one pass over the elements however
  many are added or removed
- remove() recomputes selectedGroupIds (it put element ids into it and lost
  the other selected groups' flags), and leaves group editing once nothing
  is selected
- the link popup on adding an element is the pointer's, not add()'s

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): move selectGroupsForSelectedElements from @excalidraw/element into App.selection.ts

- editor state (selected group ids, the edited group), used by the editor
  only; moved as is
- also ends the groups.ts <-> selection.ts import cycle in @excalidraw/element

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): move dragging the selection and box selection out of App into AppSelectionTool

- handleSelectionDragOnPointerMove: dragging the selection (or the image
  within its crop), alt-drag duplicating past the threshold
- handleBoxSelectionOnPointerMove: box selection (and of the line editor's
  points)
- handleSelectionDragOnPointerUp: frame membership of the dragged selection
- pure moves, verified mechanically
- tests for shift-dragging along one axis and moving the image within its
  crop (both untested through the pointer)

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): one check for the selection's transform handle under the pointer

- selectionTool.getTransformHandleAt() replaces the two copies in the hover
  cursor and on pointer down (line editor, elbow arrows, two-point lines,
  mobile lines, hovered line points; a lone element's or the selection's
  common bounds)
- pointer down now also ignores the handles in the element link selector,
  as the hover cursor did
- test for the resize cursor over the handles (untested)

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): app.selection shows the link popup of what it selects

- select / add / remove show the link popup of a lone selected element with
  a link (or an embeddable) and hide it otherwise; clear hides it — it was
  left as is, so select() showed it only if a previous selection had
- the link editor stays open when its element is selected again
- the pointer and lasso call sites no longer set it themselves

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): app.selection ends what hangs on the deselected elements and skips locked ones

- cropping ends unless the cropped image stays the selection, and an active
  embed is deactivated once deselected (the line editor already ended once
  its line is deselected)
- select / add skip locked elements, unless includeLocked — which the
  context menu passes, to offer unlocking them
- captureUpdate option, as updateScene's, to record the change for undo
- deep option on select (the elements themselves, editing their shared
  group), which Ctrl+click now goes through
- text editing isn't ended here: the editor ends itself on blur, and
  submitting it mid pointer event would commit half the event's state

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): app.selection ends text editing, and add / remove / clear always end cropping

- select / add of anything but the edited text (or its container) submit
  the text editor — after the current event (it submits with a flushSync),
  and only if that editing session is still open; clear / remove leave it
  (starting text editing clears the selection)
- add / remove / clear end cropping; select keeps it only when selecting the
  cropped image again (a click inside it in the crop editor)

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): app.selection derives the line editor from the final selection, and frame / deep fixes

- the line editor is set from the selection once groups are expanded: an
  arrow selected with its group (e.g. by alt-click cycling) gets none, so
  dragging from its point moves the group rather than reshaping the arrow;
  add() sets it too (adding a lone arrow left Edit / Cmd+Enter throwing)
- children of frames selected through the groups of the selected (or added)
  elements are left out, also ones selected in the same call — and adding
  within an edited group no longer deselects as if the edited group's frames
  were selected
- deep selection never expands groups (it did for elements not sharing one)
- a click-selected elbow arrow now gets its line editor on pointerdown, so
  that click's pointerup normalizes a hand-built route one gesture earlier

Claude Opus 5.5 (1M), xhigh effort

* feat(packages/excalidraw): excalidrawAPI.selection

- app.selection on the imperative API — select / add / remove / clear,
  taking elements or ids, one or many, with the deep / includeLocked /
  captureUpdate options; the type exposes only those four
- they're arrow properties, so they keep `this` when taken off the object
- changelog entry

Claude Opus 5.5 (1M), xhigh effort
2026-10-10 23:34:00 +02:00
David Luzar 53973c3a42 feat(editor): alt-click to cycle the selection through overlapping elements (#12237)
* feat(editor): alt-click to cycle selection through overlapping elements

- alt+click on the selected element (or group) selects the one below it
  under the pointer, wrapping around to the topmost
- inside an edited group, cycles through that group's elements only
- alt+drag duplicates only past a 10px threshold, so alt-clicks don't
- alt+double-click no longer creates/edits text (except with autoshape)

Claude Opus 5.5 (xhigh)

* refactor(editor): move the selection tool out of App into AppSelectionTool (app.selectionTool)

- handleSelectionOnPointerDown, clearSelection(IfNotUsingSelection),
  isASelectedElement, isHittingCommonBoundingBoxOfSelectedElements and the
  alt-click cycle target move as is
- the click selection of the pointer up handler (alt-click cycle, shift
  toggle, click select, bbox-only deselect) becomes
  handleSelectionOnPointerUp
- the selection's transform handles, maybeHandleResize / maybeHandleCrop,
  move as is
- tests for alt-click cycling, and for cropping by dragging a crop handle

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): alt-click cycles the selection on its resize handles too

- alt-resizing starts only past the 10px drag threshold, as alt-drag
  duplicating does, so an alt-click on a resize handle can cycle
- an alt-click on the selected element's resize handle (over the element)
  cycles the selection, but not once a resize happened

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): hint at alt-click cycling while Alt is held

- holding Alt over a single selected element (or group) with the selection
  or lasso tool shows "Alt-click to cycle selection, or drag to duplicate"
- app.modifiers tracks the held Alt, Shift and Ctrl/Cmd outside appState,
  synced from key and pointer events and reset on blur;
  app.modifiers.useHeld(modifier?) re-renders only on the given one
- the hover refresh after a pointer up replays the held modifiers, so it no
  longer releases them (the hint flickered on every alt-click)
- selectionTool.canCycleSelection() shares the cycle rules between the
  hint and the click

Claude Opus 5.5 (1M), xhigh effort
2026-10-06 17:31:23 +02:00
David Luzar ed10ac7dca feat(editor): alt-drag the text being edited to duplicate it (#12219)
* feat(editor): alt-drag the text being edited to duplicate it

- alt-pressing the text editor ends the editing and hands the press over
  to the canvas, so the drag duplicates the text (or its container)
- the handed-over press always moves what was edited, never resize
  handles or an arrow's points, midpoint or label beneath the editor
- on drop, the duplicate is edited with all of its text selected (a list
  item's text only, as when alt-dragged on the canvas)

Claude Opus 5.5 (xhigh)

* fix(editor): no arrow hover highlights while editing its label

- starting to edit text clears the hover state of the arrow's editor
  (kept up for the submit), so a midpoint hovered before the double-click
  doesn't stay highlighted
- the arrow's hover affordances don't apply while editing text

Claude Opus 5.5 (xhigh)

* fix(editor): don't drop arrow hover updates on the same pointer move

- the hovered point, midpoint and focus point were each set from
  `this.state`, so when one move changed several of them (e.g. from the
  midpoint straight onto an endpoint), only the last update survived

Claude Opus 5.5 (xhigh)
2026-10-01 16:39:40 +02:00
David Luzar 9ba66ed9b5 feat(editor): auto increment numbers/lists on duplicate (#12189)
* feat(editor): auto increment numbers/lists on duplicate

- duplicating a text or a label (shape, arrow, sticky note) that starts with a list marker advances it: `1.` `1)` `(1)` `[1]`, `a.` `a)` `(a)` (`a`–`h`, then roman numerals `i`–`xcix`), and lone numbers (`1`)
- markers must be followed by whitespace (`1.5`, `e.g.` aren't lists); whole lists are left as they are
- numbers count up to 42, letters up to `i`
- only if nothing but list items is duplicated (a label goes with its container); several items only if they're just markers (`1.` `2.`), continuing from the highest of them (`1.`, `3.`, `5.` -> `6.`, `7.`, `8.`)
- the increment is a separate undo step after the duplication; alt-drag shows it from the start of the drag

Opus 5.5 (1M context), xhigh

* feat(editor): edit the text of an alt-duplicated list item

- on alt-drag drop, a single list item with text after its marker enters the text editor with that text selected (`2. |foo|`)
- not when duplicated along with other elements, nor when the drag doesn't end with a genuine pointerup (pointercancel, missing-pointerup cleanup)
- `textWysiwyg` / `startTextEditing` take an `initialSelection`

Opus 5.5 (1M context), xhigh
2026-10-01 15:08:33 +02:00
David Luzar 1919728724 fix(editor): reach text containers below transparent ones (#12210)
The text tool (hover and click), and a double-click with nothing
selected, took the top-most shape whose bounds held the pointer. A
transparent shape stacked above a nested one kept the inner one out of
reach at its center, and an arrow below a transparent shape couldn't get
a label.

- only a filled element or an image (the rule arrow binding uses, now
  exported as isOpaqueForBinding) or an arrow ends the search
- of the containers found, the innermost one whose center is at the
  pointer wins, else the top-most as before
- an arrow counts only where its path is hit, not anywhere in its bounds
- a frame's children aren't hit outside the frame, where they're clipped
  (App.isClippedByFrameAt, shared with getElementsAtPosition)

Claude Opus 5.5 (1M), xhigh effort
2026-09-30 23:26:42 +02:00
David Luzar 74423812ec perf(editor): avoid rebuilding id sets on every drag (#12183)
perf(element): reuse one moved-element ID set when dragging

dragSelectedElements passed a fresh Array.from(elementsToUpdate) to every
element's updateBoundElements call. Each call missed the per-array ID-set
cache and rebuilt a selection-sized set, so a drag step was quadratic in the
number of dragged elements.

Build the array once per drag step, pass it to every call, and reuse its
cached set (getSimultaneouslyUpdatedElementIds, now exported) for the
unbinding checks too. Document that callers must pass one array instance
per operation and must not change its membership afterwards.

Dragging 1K / 2K / 4K selected rectangles in the app went from 45 / 160 /
643 ms to 18.5 / 31 / 54 ms per frame (same tab, same window, dev build).

Add coverage for the shared array, grouped labels across z-order, frames
with their children, bound arrows, bindings, unbinding, and unchanged
coordinates.

Claude Opus 5.5 (1M context), reasoning effort 40
2026-09-27 18:45:39 +02:00
Nicolas OgaandClaude Opus 5.5 84e3f5a40c perf(editor): avoid rebuilding id sets on every resize (#12180)
perf: avoid rebuilding simultaneously-updated id set per element on multi-element resize

updateBoundElements() rebuilt a Set of all simultaneouslyUpdated ids on
every call. Multi-element resize/rotate call it once per selected element
with the same array, making each pointer move O(n^2). Cache the set per
array in a WeakMap.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 09:01:38 +00:00
Alexandre Kohler 974f054baf fix(editor): embed YouTube live links (#12178) 2026-09-27 07:49:24 +00:00
David Luzar f3d99c42e9 fix(editor): pan the canvas to follow the caret instead of shifting the UI (#12175)
* fix(editor): keep the text editor flush with the canvas when a click places the caret in a tall text

Editing a text that reaches past the viewport with the text tool (a click
places the caret) scrolled the editor's content: the textarea is clamped to
the viewport, focus() reveals the caret — which sits at the end of the value
until the initial selection is applied — and the deferred refocus after the
pointerdown's blur did that on an unfocused textarea, so the text moved up by
the overflow while the box stayed put. The selection tool's single-click edit
starts on pointerup, with no blur, so it never refocused and looked fine.

After placing the initial caret — inside the visible box by construction —
the textarea's own scroll goes back to zero.

Verified in the browser on a 49-line text hanging 250px below the viewport at
90% zoom: internal scroll was 278px, now 0, for the text tool with the
mousedown blur; the selection-tool path stays at 0. jsdom textareas don't
scroll, so there is no unit test for it.

Claude Fable 5.1, high effort

* fix(editor): place the editor of a rotated text where the text is

The editor's textarea was scaled and rotated about its own box's center,
while the canvas rotates a text about the text's center. The two only agree
when the box is the text's size — and it isn't once the box is clamped to
the viewport (a tall text reaching past it) or, slightly, through the 5%
height buffer. A rotated text scrolled partly off the viewport got its
editor displaced by the rotated pivot offset (36px for a 49-line text at
-18° and 130% zoom), and the clamp — a cut along the box's own edges —
removed lines that were still on screen on the side the rotation lifted.

Now the transform origin is the text's center whatever the box's size, with
the translate derived from the text's dimensions, so the editor lands on the
text in every case; the viewport clamps (right and bottom) apply only to an
unrotated box, whose edges are the viewport's, and a rotated box is left
whole. Since an unclamped box can reach past the viewport, both focus()
calls pass preventScroll so revealing the caret can never scroll the
container — the app owns scrolling.

Verified in the browser: all four corners of the rotated editor coincide
with the text's (they were off by up to 36px), typing at the off-screen end
leaves the container unscrolled, and the unrotated case is unchanged — still
clamped to the viewport bottom, top-left in place, no internal scroll on a
click caret, select-all on Enter.

Also updates the linear-editor style snapshot for the editor's explicit
transform origin.

Claude Fable 5.1, high effort
Claude Opus 5.5 (1M), xhigh effort (moved the snapshot update in)

* fix(editor): never let the browser scroll the editor container to reveal a caret

The root container is `overflow: hidden`, which still makes it a scroll
container the browser scrolls programmatically. Typing in a text editor
whose box reaches past the viewport — a rotated text's editor cannot be
clamped to the viewport without losing lines still on screen — made the
browser reveal the caret by scrolling the container, pushing the whole UI
out: two new lines below the viewport moved the toolbar up by 416px.

`overflow: clip` clips exactly like `hidden` but is not a scroll container,
so there is nothing for the caret reveal (or a focus) to scroll; `hidden`
stays as the fallback where `clip` is unknown. The editor never scrolled
this box itself.

Verified in the browser with real key input on a rotated 49-line text
hanging below the viewport at 130% zoom: the container stays at 0 and the
toolbar in place through new lines and characters typed past the viewport.

Claude Fable 5.1, high effort

* fix(editor): the canvas follows the caret instead of the page scrolling to reveal it

With the editor root at `overflow: clip` (previous commit), the browser's
caret reveal skips the root, since it is no longer a scroll container. Full
page, nothing moves, but the caret stays out of view. Embedded in a page
that scrolls (directly, or in a same-origin iframe), the reveal scrolls that
host page instead: 434px for a rotated text reaching past the editor's
bottom edge, 345px for a text scrolled below it while edited. Only a
cross-origin iframe stops it.

The root goes back to `overflow: hidden`, so it absorbs the reveal again.
While a text is being edited, the text editor hands any scroll of the root
to the canvas (`viewport.translate` by the same screen distance) and resets
the root. Scroll events fire before the frame is painted, so the root's
shift is never seen. Nothing moves, host page included, and the canvas pans
just far enough to bring the caret into view. The reveal is the browser's,
so this covers everything that moves the caret: typing, Enter, arrow keys,
paste, IME, and drag-selecting past the edge.

Measured with real key input in Chromium, full page and in a same-origin
iframe embed: host page and root unmoved, canvas panned 444px / 330-355px,
caret visible, the editor still on its text. Outside text editing, a root
scroll is left as it was.

Test: a root scroll while editing is reset and pans the canvas (at 200%
zoom, both axes) with the editor on it; with no text being edited, the root
is left alone.

Claude Opus 5.5 (1M), xhigh effort

* fix(editor): never cut the text editor to the viewport; the canvas follows the caret for every text

The editor of an unrotated text was cut to the viewport's right and bottom
edges (the width of unbound text, plus a max-height), so a caret past an
edge was revealed by scrolling the textarea's content inside the cut box.
The canvas stood still, and the editor's text left its place on the canvas
while typing. Rotated texts were already left whole, and their caret reveal
panned the canvas (previous commit).

Now no editor box is cut: rotated or not, it is the text's own box, and a
caret past the viewport's edge is revealed by panning the canvas. Typing
past the bottom edge, or a long line past the right edge, moves the view
along; the editor stays on its text.

What only existed for the cut goes with it: the `maxWidth` bookkeeping, and
the reset of the textarea's internal scroll after placing a click's caret
(a whole box never scrolls inside).

Measured with real input in Chromium: 455px vertical pan for a 30-line text
crossing the bottom edge, 454px horizontal pan for a line crossing the right
edge, root and textarea unscrolled, editor on its text. A text-tool click on
line 3 of a text taller than the viewport places the caret there without any
pan or internal scroll.

Tests: the max-width test now checks the editor isn't cut at either edge
(it fails with the cut in place); the linear-editor style snapshot loses its
max-height.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): leave room past the caret when the canvas follows it

The browser reveals a caret only as far as it has to, so text typed past
the viewport's edge came into view flush against the edge. The canvas now
pans a further CARET_FOLLOW_PADDING (5 screen px) along the axis it
follows, so the caret keeps a little room from the edge while the view
follows it.

Not done with the root's `scroll-padding`: the browser honors it only as
far as it can scroll, and the editor box ends at the text (5% below it,
nothing past a line's end). Measured in Chromium: `scroll-padding: 80px`
left 39px below the caret and none to its right.

Measured with real input: once the caret reaches the edge, every new line
or character pans the canvas and the caret stays 4-5px from the edge, both
typing down and along a long line.

Test: the pan includes the padding, and a reveal along one axis pans along
that axis only.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): the canvas follows a caret behind a docked sidebar; the reveal stays in the editor's box

A caret that went behind a docked sidebar stayed hidden: it was still
inside the editor root, so the browser had nothing to reveal and the canvas
never followed.

The text editor's container (`.excalidraw-textEditorContainer`) is now the
box a caret is revealed into: the canvas area, clipped, and inset off a
docked sidebar (measured from `.sidebar--docked` on every editor update, on
the right or the left for RTL; the editor's position is relative to the
box). A caret past its edge, or behind the sidebar, is revealed by
scrolling the box, which the text editor turns into a canvas pan (+
padding) and resets, as it did for the root before.

The reveal now never gets past the box, so the editor root is back to
master's CSS, and what a host does to the root's overflow no longer
matters: with the root forced to `overflow: visible` (as Excalidraw+ does,
inside a wrapper that resets its own scroll), the canvas follows the same
way and the wrapper never scrolls.

Measured with real input in Chromium, full page, with the root forced to
`visible`, in the Excalidraw+ arrangement, and in a same-origin iframe
embed: nothing scrolled (host page, root, box), the canvas panned 449 /
360 / 580px for texts past the bottom edge, and for a line typed in behind
the docked sidebar it panned 120px, leaving the caret 5px left of the
sidebar. Clicks inside the editor still place the caret; clicks on the
canvas still end editing.

Tests: the pan test scrolls the editor's box; a new test covers the insets
for a sidebar docked on either side, and their removal with the editor.

Claude Opus 5.5 (1M), xhigh effort

* refactor(editor): measure the sidebar through the viewport UI markers

The text editor's box was kept off a docked sidebar by querying the
`.sidebar--docked` class and measuring it inline in textWysiwyg. How far
viewport UI reaches into the canvas is AppViewport's concern:
`getOffsets` measures every UI marked `data-viewport-ui`, and the sidebar
is marked (`side` / `sidebar`, except on phones, where it's an overlay).

AppViewport gains `getSidebarInsets()`, which measures just the sidebar
through those markers, with a `measureSide()` that `getOffsets` now shares.
The text editor asks the viewport for the insets. An open sidebar that
isn't docked covers the canvas the same way and now counts too; it closes
when the canvas is clicked to start a text, so this rarely matters.

`getOffsets` isn't used for the box: it gives one band per side for all
marked UI, so the top toolbar and the styles panel (open while a text is
edited) would pan the canvas as soon as one typed below them.

Test: the docked-sidebar test's fake sidebar carries the markers.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): a text stops growing at the view's width, and is brought into view when it wraps

Closes #8855. Typing a long line grew a free text past the view's edge.
The canvas followed the caret, so the start of the text went out of view
on the other side, and the box had to be resized by hand afterwards.

A free text that grows with its content (`autoResize`) now stops at the
view's width: the canvas minus the sidebar, less TEXT_VIEWPORT_PADDING
(20px, in @excalidraw/common) at each side, in scene units, so it follows
the zoom. On the keystroke that would cross it, the text becomes fixed
width at exactly that width and wraps from then on (`autoResize: false`),
anchored the way it grew, so a right-aligned or centered text keeps its
edge or center. The editor switches to wrapping with it. A text that is
already wider keeps growing; nothing shrinks. The rule is an optional
`maxWidth` on `refreshTextDimensions`, which the editor's per-keystroke
update passes.

When a text starts wrapping in the editor, while typed or pasted into it,
it is scrolled into view with the same room at the edges. Being exactly
the padded view's width, it then fills it. That happens horizontally
always, and vertically only if all of it fits; a taller text leaves the
vertical to the caret-follow, so the view doesn't jump away from the caret.

Pasting onto the canvas keeps its wrap width (half the view, 200-800),
capped by the same limit, so that the 200 minimum can't outgrow a narrow
or zoomed-in view. A paste that wrapped is scrolled fully into view; if
it is taller than the view, its top is brought in.

Scrolling into view is computed by a pure `scrollBoundsIntoView` in
viewport.ts, next to `centerScrollOn` and `constrainScrollState`. It moves
by the least amount, keeps the zoom, takes the usable area as `Offsets`,
and returns null when nothing needs to move. The move itself goes through
`viewport.translate`, as a user pan does: it respects scroll locks, yields
to a host's pending locked navigation, and stops following a
collaborator. No move, no translate.

Measured with real input in Chromium on a 2560px view: typing
character by character at 400% from 100px in, and a sentence inserted at
once, both end as a wrapped text from 20 to 2540; with the docked sidebar
the limit is 2226 (2560 - 294 - 40) and the text sits 20px left of it; a
paste near the bottom-right corner ends 20px inside the right and bottom
edges. Nothing scrolled the page or the editor box.

Tests: the text stops and wraps at the view's width, and keeps that width;
the limit follows the zoom and a docked sidebar; a right-aligned text keeps
its right edge; a text already wider keeps growing (the not-cut-off test,
reworked); starting to wrap scrolls it into view with room at its right
edge, but not vertically when it's taller than the view; a paste isn't
wider than the view at 800% and, wrapped, ends fully in view;
`scrollBoundsIntoView` unit tests.

Claude Opus 5.5 (1M), xhigh effort
2026-09-26 23:00:28 +02:00
c10499eebb feat(editor): text tool edits what you click, shows what a click will do, drags out free text in shapes (#12082)
* fix(editor): do not inherit groupIds/angle from container if not binding the text to it

* fix(editor): text tool edits a label only when clicking the label itself

Clicking elsewhere inside a labeled container creates an independent text at
the clicked position, with no modifier needed (so also on touch/pen), instead
of warping to the label center and editing the existing label.

* feat(editor): highlight what the text tool would act on when hovering

Mirror the click logic on hover: the text element a click would edit gets
a box highlight, and an empty text-bindable container the click would bind
into gets the same binding highlight arrows use (box for arrow containers,
which the binding outline renderer can't draw). Cleared on pointerdown and
managed only while the text tool owns the interaction, so the frame flows
sharing elementsToHighlight are untouched.

Also documents suggestedBinding, isMidpointSnappingEnabled and
elementsToHighlight in AppState.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): hit-test arrow labels at their derived position

An arrow label's stored coords aren't updated when the arrow moves
(dragging deliberately skips them — the position is derived at render
time), which left hitElementItself internally inconsistent: its bounds
pre-check derives the position, but the precise shape test read the stale
stored coords, so a moved arrow's label was only hittable where its old
and new rects overlap. Substitute the derived coords for the precise test,
and skip the version-keyed point cache for container-bound labels (their
position can change without a version bump, mirroring ElementBounds).

Pass the elements map through renderElementsBoxHighlight so the highlight
box is also drawn at the label's derived position.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): dashed text box for the text-tool hover, cleared when the tool is left

The text a click would edit gets the same subtle dashed box as a wrapped text
being edited (at the label's derived position for arrows), instead of the
frame-style bounding box. The hover highlights are cleared whichever way the
text tool is left — Esc/finalize paths bypass setActiveTool.

* refactor(editor): dedupe container-bound label position derivation

An arrow label's accurate position is derived from the arrow rather than
stored on the element (dragging deliberately skips updating it), and three
call sites hand-rolled the same clone-with-derived-coords dance. Extract it
into getTextElementWithAccuratePosition next to the existing position
helpers.

Also routes the text-tool dashed hover highlight through the helper, so it
renders at the label's actual position instead of its stale stored coords.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): defer text-tool hover highlights to arrow text anchors

The arrow-endpoint text binding (#11777) added its own text-tool hover
affordance (hoveredArrowTextAnchor) covering arrow endpoints and midpoint
label anchors, and gave endpoints precedence on click. Mirror that in the
text-tool highlight updater: skip positions where a bindable endpoint would
take the click, and leave arrow anchors (endpoint & midpoint label) entirely
to the anchor affordance — the highlights now only cover editing an existing
text and binding into an empty non-arrow container.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(editor): make endpoint-vs-text preference z-aware to prevent affordance flicker

The endpoint offer was suppressed by any text element under the cursor,
regardless of stacking order. With an arrow drawn over an existing text,
the text's bbox edge cut into the endpoint's hit circle, and slow pointer
movement flickered between the endpoint anchor and text editing.

Drop the z-blind text check and let the existing z-order occlusion rule
decide: whatever is stacked above owns its hit area. A text above the
arrow keeps its edit behavior; when the arrow is on top, its endpoint has
full preference over the whole hit circle, matching the drawn highlight.
Container-bound labels need no special casing — a labeled container is
interior-hittable, so the occlusion rule already yields to labels whose
container sits above the arrow.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(editor): defer a text-tool center click so a drag creates free text

A click on an empty container's center still binds a label, but the decision
now waits for pointerup: dragging horizontally past the autowrap threshold
instead creates an independent fixed-width text at the pointer origin, and
small shapes are no longer provisionally enlarged while dragging. Tool
changes and the missing-pointerup cleanup cancel the pending click.

Shape hover and pointerdown share the empty-container / center-snap / Alt
eligibility via getTextCreationContainerAtPosition, and the hover indicators
are cleared when deferred creation starts (stale outline under a locked tool
at 200% zoom).

Also: a direct collision-cache regression for labels of moved arrows, exact
width/position assertions for drag creation across mouse/pen/touch,
labelPosition coverage at 25/50/75%, and stale AppState comments fixed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): redraw the dragged text box under a locked text tool

Drag-sizing a new text mutates it in place without informing the scene, so
sceneNonce never moves and the interactive canvas — which draws the dashed
text box from the live element but memoizes on canvasNonce — kept the first
size. Unlocked drags only repainted by accident: the tool had already
reverted to selection, whose box-selection branch churns state every move.

Fold the new text's versionNonce into canvasNonce, as is already done for
framed new elements. Four rendering regressions cover successive drag widths
on empty canvas and from a container's center, locked and unlocked.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(editor): extract the text tool's pointer interaction into AppTextTool

Pure move of handleTextOnPointerDown, resetTextTool, maybeStartPendingText,
maybeUpdateTextToolHighlightOnPointerMove and getTextCreationContainerAtPosition
into App.textTool.ts — only `this.` became `this.app.` and the names lost
their "Text" prefix. maybeDragNewGenericElement is now public so the pending
center-drag can re-dispatch to it. No behavior change.

Text editing itself (startTextEditing / handleTextWysiwyg and the hit
helpers) is shared with Enter, double-click and the other entry points and
stays in App.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): resolve text-tool targets once; single textToolHover state

What a text-tool click would do at a position was computed in three places
— the text/container highlight, the arrow-anchor hover and the pointerdown —
with different modifier awareness, and shown through three AppState fields
(elementsToHighlight, suggestedBinding, hoveredArrowTextAnchor) cleared from
seven sites. The affordance could promise what the click wouldn't deliver:

- pressing or releasing Alt without moving left the container outline stale
  (and Ctrl/Cmd left the text box stale)
- Alt-hovering an empty arrow's midpoint advertised a label while the click
  created free text
- Ctrl/Cmd hid the container outline (the renderer gates suggestedBinding on
  isBindingEnabled) while the click still bound a label
- over a shape's or arrow's label the cursor was a crosshair while the box
  promised an edit

AppTextTool.getTargetAt now answers the question once — endpoint → text →
empty centered container (unless Alt) → free — and feeds the hover, the
cursor and the pointerdown. The hover lives in one field, textToolHover
(replacing hoveredArrowTextAnchor), drawn by one renderTextToolHover branch;
it is cleared on pointerdown and when the tool is left, nowhere else. Alt and
Ctrl/Cmd keydown/keyup refresh it at the last pointer position. The scene is
hit-tested once per pointermove instead of twice.

Also drops AppArrowText's anchor-state members (the resolver covers them) and
getLabelCenter, dead since the label-center warp was removed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(editor): let AppTextTool own the pending center click; explicit textElement

The deferred center click was threaded through PointerDownState.text and a
textCreation parameter that made startTextEditing — the entry point shared
with Enter, double-click, sticky-note drops and autoshape — re-derive what the
text tool's pointerdown had already established, then bail. The helper now
arms `pending` itself (like AppBucketFill), decides it on pointermove/up, and
PointerDownState loses its text slot. The affordance armed at pointerdown now
stays up until the click resolves instead of being cleared and re-shown.

startTextEditing takes an explicit `textElement` instead: the tool passes
the text it resolved, or null to create — so a text selected through the
host API can no longer hijack a text-tool click elsewhere (the Enter and
double-click paths, which leave it undefined, resolve as before). The same
selection shortcut leaves getTextBindableContainerAtPosition, which is now
purely positional; the double-click path keeps it inline.

Also: a pending container deleted mid-press (collab) now still ends the
tool's turn, and the drag threshold's choices are documented in place.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): ctrl/cmd, not alt, opts out of labeling a container with the text tool

Ctrl/cmd already turns off arrow-endpoint binding for the text tool; it now
also keeps a center click from binding a label to an empty container, so one
key means "no binding" throughout the tool, as elsewhere in the editor. It is
read off the event rather than the arrow-binding preference — a label is not
an arrow binding. Alt no longer plays a part in the text tool, so its hover
refresh hooks go (alt keeps its generic drag meaning: resize from center).
The double-click path is unchanged.

Ported from #11210.

Co-authored-by: Loric Brevet <loric.brevet@gmail.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): cancel a pending text-tool click on tool exit and pointer cancel; refresh hover and cursor when the viewport moves

Three lifecycle gaps in the text tool's hover and pending center click:

- A pending center click only checked the active tool at the next pointer
  event, so leaving the tool (Esc) and picking it again before releasing
  revived the old press: moving then created free text at the original
  position. And with no pointerup after a pointercancel (scroll, palm
  rejection), the pending click stayed armed for unrelated movement. The
  helper now has an explicit cancel, called when the tool is left and on
  pointercancel next to the bucket fill's.
  The cancel also clears the outline the armed click had set, which no
  hovering pointer would clear otherwise — including when a second finger
  turns the press into a pinch/pan (that discard goes through the same
  cancel).
- The hover was refreshed on pointer moves and modifier keys, but not when
  the viewport scrolled or zoomed under a still pointer, so an outline stayed
  on a shape that had moved away. The refresh now re-derives the scene point
  from the pointer's last viewport position, remembers the last modifiers,
  and runs from the viewport-change lifecycle.
- A modifier press changed the target without updating the cursor (an
  endpoint's pointer cursor survived Ctrl). The refresh sets the cursor from
  the same target, mirroring the pointermove path and leaving a panning or
  scrollbar gesture its own cursor.

Also fixes a stale renderer comment about the container outline's binding
gate.

Tests: tool exit and re-pick mid-press, pointercancel, wheel scroll and zoom
under a still pointer for container and text targets, cursor on modifier
press and release. Verified in Chromium as well.

Claude Fable 5.1, high effort
Claude Opus 5.5 (1M), xhigh effort (moved the snapshot update to the caret-overflow branch)
Claude Opus 5.5 (1M), xhigh effort (the cancel clears the armed outline, from the 2026-09-26 review)

* fix(editor): tear a gesture down on pointercancel; a replayed cleanup no longer counts as a click

A canceled press (the browser taking the pointer for a scroll, a pinch or
palm rejection) left the gesture's window listeners and its missing-pointerup
cleanup subscription in place. The next pointerdown then replayed the old up
handler, whose end-of-gesture revert switched the tool to selection while the
new press was being armed — so after a canceled center press with the text
tool, the next center click switched tools and created nothing.

pointercancel now runs the missing-pointerup cleanup immediately, so nothing
of the canceled gesture lies in wait. And the up handler's tool revert is
gated on a genuine pointerup: a replay by the cleanup — a second finger
landing, a pointercancel, the next press after a lost pointerup — only tears
the gesture down and leaves the tool to the press that follows, instead of
reverting it under that press.

The pointercancel regression no longer sends a synthetic mouse-up that hid
this: after the cancel the tool must still be the text tool and the next
center click must bind a label. It fails without the fix.

Claude Fable 5.1, high effort

* refactor(editor): cursor from the text-tool target alone; a hover refresh needs a hovering pointer

Follow-ups from the whole-branch simplification review (simplification.md),
narrowed with the reviewer:

- The cursor is derived from the resolved target only. The old fallback to
  the plain hit under the pointer kept a text cursor over other texts while
  editing or drag-sizing — where a click has nothing to point at — and forced
  a second hit test and a coordinate recomputation on every modifier press
  and viewport change. Both go. With a locked text tool, editing or dragging
  now shows the crosshair everywhere; hover, endpoint and label cursors are
  unchanged.
- The hover refresh takes the pointer's last viewport position only. The
  fallback to the last *scene* coordinates was reachable when a tap preceded
  any pointer movement, and after a viewport change it resolved at a position
  nothing hovers — a phantom affordance. A tap leaves nothing to refresh,
  pinned by a test that fails with the fallback in place. Nor does a finger
  ever hover: a touch's last move is where it lifted, so touch input doesn't
  count as a hovering pointer (mouse and pen still refresh). The test drives
  real touches — a tap with jitter on a text, a short drag from a center —
  instead of clearing the pointer bookkeeping by hand. The pointercancel
  test now checks the armed outline is gone right after the cancel, and a
  second-finger test covers the missing-pointerup discard.
- The explicit pending-click cancel on pointercancel stays, and its reason is
  written down: the gesture teardown that follows flushes a queued
  pointermove, which would otherwise find the click still pending and resolve
  it as a drag. Verified in Chromium by the reviewer; the test harness runs
  the throttle synchronously, so it cannot be reproduced there.
- Two duplicated test scenarios removed: the arrow-anchor hover test the
  endpoint suite already covers, and a repeated Ctrl assertion.

Claude Fable 5.1, high effort
Claude Opus 5.5 (1M), xhigh effort (touch input never hovers; tests, from the 2026-09-26 review)

* refactor(editor): the text tool refreshes its own hover and cursor; viewport navigation check lives in AppPan

App's `refreshTextToolHover` was text-tool logic kept in App only because
its cursor gate read App-private state. It moves into `AppTextTool` as
`refresh(modifiers?)`, which re-resolves the hover and sets the cursor that
goes with it, taking the place of `refreshHover`.

The gate — space held, a pan in progress, a scrollbar drag, the hand tool —
is the same check the canvas pointermove makes before touching hover or
cursor. It becomes `AppPan.isNavigating()`, used by both. The scrollbar drag
stays App's own and reaches AppPan as a dependency, like the pointer count.

No behavior change.

Claude Opus 5.5 (1M), xhigh effort

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Loric Brevet <loric.brevet@gmail.com>
2026-09-26 12:38:23 +02:00
David Luzar dc2c16d9e2 fix(editor): Binding follow-ups to #10753 (#12156)
* fix: Midpoint highlight color in dark mode

The highlighted binding midpoint hardcoded rgba(3, 93, 161) for dark mode,
the pre-filter color from when the interactive canvas was inverted by a
CSS filter. The canvas now draws post-filter colors directly, so it
rendered dark blue. Use BINDING_HIGHLIGHT_RGB like the rest of the binding
highlight.

Claude Opus 5.5 (1M context), high reasoning effort

* fix: Show binding midpoints like before the hit test rework

The binding highlight drew all four midpoints for any suggested binding,
including simple arrows with the cursor deep inside the element. Restore
the previous visibility: simple arrows show no midpoints from inside, and
from outside only the one nearest the cursor once it gets near; elbow
arrows show all of them. The highlighted midpoint still comes from the
suggested binding, so it sits where the arrow actually snaps.

Claude Opus 5.5 (1M context), high reasoning effort

* fix: Images and locked opaque elements occlude binding

Only filled shapes hid the elements behind them from binding. Images now
count as opaque, and locked opaque elements hide what is behind them too
(they still can't be bound to). Frames are future-proofed: once they get
a background, an opaque frame hides the non-children behind it without
ending the search, as its children sit just below it in z-order.

Claude Opus 5.5 (1M context), high reasoning effort

* refactor: Add DEFAULT_ZOOM for computations without an editor zoom

Replace the scattered { value: 1 } as Zoom / AppState["zoom"] casts used
as a zoom fallback (elbow arrow routing, transform, element rendering,
binding repair on restore, tests) with a shared frozen constant.

Claude Opus 5.5 (1M context), high reasoning effort
2026-09-24 13:06:56 +02:00
Márk Tolmácsanddwelle 4850bf336f fix(editor): Binding hit test based on distance (#10753)
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-23 22:10:02 +02:00
Márk Tolmácsanddwelle 2b9da96100 fix(editor): Freedraw hit test precision (#11550)
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-22 22:02:13 +02:00
Márk Tolmács 31df3e6ef2 fix(editor): Tab convert bound arrow update (#12143)
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-09-22 10:26:19 +02:00
David Luzar 14e1c614d4 feat(packages/excalidraw): support onDuplicate replacements, vetoes and lookups (#12124)
feat(packages/excalidraw): make `onDuplicate` changes stick, support veto & lookups

The editor kept working with the duplicates it created after calling
`props.onDuplicate`, so a host returning new objects for them detached
them from the frame assignment and bound text redraw on paste, and from
the alt-drag handover.

- Add `reconcileDuplicatedElements()` and use it in all three duplication
  paths (paste/library insert, duplicate action, alt-drag). Elements the
  host returns for duplicates are shallow-merged into the editor's own
  objects (omitted properties are kept), invalidating what may have been
  cached for them by then (shape, bounds). Other returned elements keep
  the replace semantics.
- Omitting a duplicate (or returning it as deleted) vetoes it. So does
  returning `false` for the duplication as a whole. Bound text goes with
  its vetoed container, and references to vetoed duplicates are cleared
  from the remaining ones (as in `fixDuplicatedBindingsAfterDuplication`).
  If no duplicate remains the duplication is cancelled: paste and the
  action do nothing, alt-drag keeps moving the originals. On a partial
  veto during alt-drag the vetoed originals are left behind.
- On paste, resolve the target frame (and the z-order under it) before the
  callback, so that the host sees the duplicates the way they end up in
  the scene, and a vetoed duplicate isn't brought back.
- Pass lookups covering just the participating elements as a third
  argument: `duplicateElements`, `originalElements`, `origIdToDuplicateId`
  and `duplicateIdToOrigId`.

Claude Fable 5.1
2026-09-19 10:00:47 +02:00
David Luzar a918648012 feat(packages/excalidraw): add renderOverrides to allow overriding of element rendering (#12100)
* feat(packages/excalidraw): add renderOverrides to allow overriding rendering of elements

* refactor(renderer): centralize overrides and inherit label offsets

* fix(renderer): preserve frame-name editing during visual overrides

* perf(renderer): limit override culling to translated elements

* fix(renderer): keep frame-title hit bounds at document positions

* fix(renderer): skip clearing an already clear override snapshot

`setElementRenderOverrides(null)` (or an empty map) on an editor whose
snapshot is already empty no longer copies, derives offsets or schedules a
render. Every other submission still repaints, equivalent ones included:
a value comparison would cost about as much as the copy it saves on every
changing frame, so hosts are told to submit only on change and to dedupe
at their own level, where the snapshot's structure is known.

Fable 5.1, medium reasoning

* refactor(renderer): drop two override edge cases

Culling no longer keeps an off-screen container alive because its bound
label alone would be in view: the label follows its container, as it does
for document culling, and the case needed a label wider than its (short
arrow) container at the viewport edge during a translation.

Frame clipping no longer tracks whether an element carries an explicit
offset entry (`hasPositionOverride`); a non-zero offset is what matters.
An explicit zero offset leaves the element at rest, where the ordinary
overlap check already decides correctly.

Fable 5.1, medium reasoning

* perf(renderer): leave bound-label entries out of override culling

A bound label is drawn with its container and its own entry in the visible
list is skipped by the static renderer, so override culling has no reason
to adjust that entry. Doing so made a visible container whose label is
document-off-screen (a long arrow with its label past the viewport) report
the label as newly visible on every translation, which rebuilt the visible
set from the whole scene each frame. Translated elements now update only
their own membership; the label lookup per translated element goes too.

Fable 5.1, medium reasoning
2026-09-15 14:12:53 +02:00
David LuzarandClaude Fable 5.1 afa3a653fc feat(editor): sticky notes (#12064)
* feat(editor): sticky notes

* clamp sticky note font size

* [dragInput] reject non-finite values

* chore: prettier formatting after rebase

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(editor): sticky notes cleanup (plan §7.1)

- hide `transparent` in the sticky stroke picker through master's
  `excludedColors` (#11872) instead of the branch's own
  `hiddenPaletteColorNames`; the swatch becomes a grid-preserving
  placeholder, its hotkey stays dead, and arrow-key navigation steps over
  it in the arrow's direction (unit + integration tests)
- move the text pixel-snap change out to `dwelle/text-pixel-snap`
  (705e497e2): it affects every text element at every zoom and is not
  zoom-aware, so it lands separately
- rename `STICKY_NOTE_DEFAULT_FONT_SIZE` → `STICKY_NOTE_FALLBACK_FONT_SIZE`:
  it is only the non-finite fallback; new sticky text seeds its ceiling from
  `currentItemFontSize` (decision D3)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): one sticky note layout core + resize intents (plan §7.2, 1/2)

- `getStickyNoteLayout` is the single fit/grow/position calculation (pure;
  ceiling-anchored size grid, warm-started binary search instead of the
  linear descent); `updateStickyNoteLayout` applies it to a scene and runs
  the bound-arrow pass by default (callers forward `simultaneouslyUpdated`
  or opt out when they own a pass); `relayoutStickyNotes` applies it inside
  immutable element arrays, identity- and version-preserving
- resize intents are absolute values recomputed from the gesture-start
  snapshot on every pointer-move (`getStickyNoteResizeIntent`): width-only
  gestures keep the base height, height gestures set it, proportional
  gestures (Shift on any handle, aspect-locked multi-select, Stats group)
  also scale the font ceiling, flips preserve everything; the content
  correction anchors at the held edge (n* → bottom, Alt → center,
  Shift+E/W → center). The corner pre-fit clamp and the multi-resize
  sentinel/veto are gone: one fit per pointer-move
- arrows bound to a note follow text-driven growth, and multi-resize /
  Stats group update them after the content correction, not before
- `fontSizeMax` is `number | null`; every read/write goes through the
  container-aware `getUserFontSize` / `getUserFontSizeUpdate` (a detached
  label with a stale ceiling neither shows nor keeps writing it); unbind
  clears it and returns an empty note to its base height; restore seeds or
  clears it after binding repair and normalizes a sticky label's stroke
- paste styles lays out a restyled note and its label together in a
  post-pass (no phantom-container mismatch) and reads the source ceiling
  from the copied snapshot rather than the fitted size
- `redrawTextBoundingBox` / `handleBindTextResize` delegate sticky notes up
  front (no wasted generic wrap); the `refreshTextDimensions` sticky arm and
  the wysiwyg duplicate arm are gone; `clampStickyNoteProps` becomes the
  identity-preserving `normalizeStickyNote`

Tests: content-pinned corner drag keeps the requested base, Shift+E scales
note/base/ceiling, width-only drag preserves the base of a grown note,
Shift released mid-gesture restores gesture-start values, flipping a rotated
grown note keeps base/ceiling/label angle, multi-resize syncs an empty
note's base.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): sticky note invariants in changeProperty + regression tests (plan §7.2, 2/2)

- `changeProperty` normalizes sticky notes after any property write
  (identity-preserving `normalizeStickyNote`), replacing the three per-action
  wraps in the background, sloppiness and roundness actions
- tests (new `tests/stickyNotes.test.tsx` + restore): arrows bound to a
  note follow text-driven growth while typing; binding free text seeds the
  ceiling and unbinding clears it (`null`) and returns the note to its base
  height; pasting styles copies the user's ceiling and lays out the note
  together with its label; unselected notes keep object identity through
  property actions; a transparent background write is normalized; restore
  clears a stale ceiling on unbound text and seeds ceiling + visible stroke
  on a sticky label

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): sticky note creation feel + sticky color domain (plan §7.3)

Creation
- a note starts as a 0×0 draft inserted like every other tool and is
  previewed at its true dragged size (no jump to 40px on the first move);
  a gesture under the drag threshold is a click → the default 250×250
  square centered on the pointer; a longer drag snaps to the 40×40 minimum
  only on release, growing away from the origin corner. The preview
  suppression flag and the pointer-move sticky arm are gone
- `normalizeStickyNote` splits into style (constructor + every pass) and
  geometry (finalize, restore, action passes) so a draft is legal

Colors — sticky notes are their own color domain (decision D2)
- new `currentItemStickynoteBackgroundColor` default (yellow) next to the
  stroke one; both persisted/restored non-transparent; new notes and their
  labels seed from the sticky defaults (a label takes the note's stroke)
- own top-pick slots (`colorTopPicks.stickyNoteStroke/Background`) and
  classic note picks; transparent excluded like bucket fill
- one `resolveColorTarget` (regular / sticky / mixed, incl. the text being
  edited) resolved at execution time in the stroke and background actions'
  `perform`; the panel only sends `{ color }`, so the memoized picker's
  stale closure can no longer write the wrong tool's default (A1)
- one `getColorUpdate` policy used by the actions, both eyedroppers (which
  now include bound labels, so a stroke pick colors a note's visible text —
  1.12), paste styles and bind-existing-text (a transparent label bound to
  a note takes the note's text color — A3); the per-surface forks and
  `isStickyNoteStrokeColorElement` are gone

Tests: click under the threshold, 20px drag previews at 20 and snaps to 40
with the origin corner fixed (both directions); closed-popup top pick after
a tool switch writes the sticky default; mixed selection writes both
domains; notes are created from the sticky defaults; bind normalizes a
transparent label; the keyboard eyedropper colors a note's label. App-state
snapshots gain the three new keys.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): font-aware minimum sticky note size

The 40×40 floor let a freshly placed note grow on the very first keystroke:
one line at the default 20px ceiling plus the 16px padding needs 57px.

- `STICKY_NOTE_MIN_SIZE = 75` replaces the width/height pair as the data
  floor (normalization, layout, restore)
- `getStickyNoteMinSize({ fontSize, fontFamily })` =
  max(75, round(ceiling × lineHeight) + 2 × padding) is the UI floor: the
  creation snap on release uses the current font size/family, the single
  resize floor uses the label's ceiling (constant floor for an empty note).
  Excalifont: 75 up to the L ceiling, 77 at 36px, 92 at 48px

Tests: the 20px drag now snaps to 75; a 48px ceiling yields a 92px note
that keeps its height on the first character.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(editor): sticky note regression matrix (plan §7.4) + two Stats fixes

Tests (27 new): Alt/center resize keeps the center of a content-pinned
note; proportional multi-select scales the label's ceiling, a free
multi-select of an empty note uses the requested height; a proportional
gesture returning to scale 1 restores everything; rotated growth keeps the
top edge; the fit takes ≤ 2 measurements on a warm keystroke and ≤ 12 on a
cold search from a 512 ceiling; a lowered ceiling wins over a still-fitting
old size; odd/fractional ceilings stay reachable on the ceiling-anchored
grid; the font-aware minimum size. Bound arrows follow the note on unbind,
after a content-constrained resize and after a font-size action, and are
not moved twice when resized as part of the same selection. A top pick
while editing a note's label targets the label and the sticky default; the
preview eyedropper colors a selected note's label; paste styles resolves a
since-deleted source's ceiling from the copied snapshot; a detached label
with a stale ceiling neither shows nor writes it; duplication keeps the
ceiling and base height; an empty note escaped from editing stays and is
removed by undo; Stats W keeps the base height and a group W edit scales
the ceiling; restore normalizes both sticky defaults, keeps the new
top-pick slots and refits note + label under `refreshDimensions`; unit
tests for `resolveColorTarget` (regular / sticky / mixed / editing) and the
default normalization.

Source fixes the tests surfaced:
- Stats `DragInput`: the typed-value path handed callbacks the live
  elements map as "original", so gesture-start values (a note's width, its
  label's ceiling) read as the already-applied values; it now snapshots the
  scene like the pointer-drag path does
- Stats group resize (`MultiDimension`): a group unit lists the note's
  label too and scaled it as a standalone element after the note, wiping
  the fitted size; the note's layout owns its label

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): sticky note skeleton API, tool hint, help row, docs (plan §7.5)

- `convertToExcalidrawElements` accepts `{ type: "stickynote", x, y, label?,
  ... }` (new `ValidStickyNote` skeleton member): the note is constructed
  through `newStickyNoteElement` + `normalizeStickyNoteGeometry` (250×250
  default, `baseHeight` finalized, sticky color invariants), and a label is
  bound through the sticky fit so its `fontSize` becomes the ceiling and the
  note grows only if the text overflows at the minimum size (decision D7)
- tool hint for the sticky note tool ("Click to place a note, or drag to
  size it") and the `N` shortcut row in the help dialog
- dev-docs: "Sticky Notes" section in the element-skeleton page; CHANGELOG
  entry (PR number placeholder)

Tests: skeleton defaults, invariant enforcement on given props, label
binding with the ceiling and the note's text color, growth for an
overflowing label.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor: move the seeded PRNG (mulberry32) to @excalidraw/common

Pure utility next to `randomInteger`/`reseed`; the sticky note corner
jitter imports it from there.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(editor): drop the dead roughjs Drawable for sticky notes

Nothing ever generated or drew it: both renderers paint a note directly from
`getStickyNoteRenderPoints`, and every `ShapeCache` consumer is type-gated
to the rectangle family or linear elements. It also disagreed with the
rendered outline (generic corner radius, no jitter). Sticky notes now sit
with text/image/frame in the `null`-shape group, which the cache treats
as a valid value.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): sticky note creation-date footer

Every note reserves a 32px band under its label body and paints the
note's `created` date there, on canvas and in SVG export: "7 Sep" while
the year is the current one, "7 Sep 2025" otherwise, nothing for an
unknown timestamp (the band stays reserved so geometry never depends on
data availability). The label form is chosen by width bucket, never
measured, so painting stays measurement-free — server-side SVG export has
no text measurer — and an absolute date means exports never go stale.

- `STICKY_NOTE_FOOTER` and `STICKY_NOTE_BODY_INSET_Y` in @excalidraw/common;
  `getStickyNoteDateLabel` / `getStickyNoteFooter` in stickyNote.ts
- the layout, `getBoundTextMaxHeight`, the text editor and both renderers
  share the one inset; a rotated label rotates about the note center, not
  the now-asymmetric body center
- `getStickyNoteMinSize` returns `{ width, height }`; creation and resize
  clamp each axis to its own floor (a Shift drag stays square)
- tests: date label, width buckets, body height, resize floor, SVG + canvas
  export, creation minimums

Plan: sticky_notes_review_final.md §9.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): image tool into "More tools", letter shortcut badges

With the sticky tool on N between text (8) and eraser (0), the numbered
badge row no longer reads as a sequence. On desktop and tablet, move the
image tool into the "More tools" menu (first entry, still `9`,
`UIOptions.tools.image` keeps hiding it) and badge the toolbar tools
with their letter shortcuts (V R D O A L P T N E) instead of numbers.
The number keys keep working; tooltips and the help dialog are unchanged.
The mobile toolbar keeps its image slot.

- Toolbar.tsx: image item in `ExtraToolsDropdown` (trigger highlight and
  icon while active), `UIOptions` passed through for the gate
- Tools.tsx: `keyBindingLabel` prefers the letter
- tests: `UI.clickExtraTool`, image test uses it, toolbar describe in
  tool.test.tsx (menu placement, UIOptions gate, letter badges)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): a sticky note and its label share one ink

The creation-date footer paints from the note's `strokeColor`, the label
from its own, and three writes let them drift: coloring the label while
editing it (the wysiwyg clears the selection, so `changeProperty` targets
only the edited text), binding an already-colored text (only transparent
was rewritten), and paste styles from a source whose container and label
carry two colors. Red text under a black date.

The note's `strokeColor` is its ink — the seed for a new label and what
the footer paints with — and the label always mirrors it:

- `syncStickyNoteInk(elements, prevElementsMap)`: after a write, copies
  the side that changed onto the other; when both changed or the data
  drifted, the label wins (it is the text the user styled); a transparent
  label takes the note's color; identity-preserving when nothing changes
- entrances: the stroke action (after `changeProperty`, which covers edit
  mode), paste styles (before the relayout), bind text (the text's color
  wins, transparent falls back), the skeleton path (a label that sets its
  own color gives it to the note), restore (label wins over a drifted note)
- the stroke picker reads "Text color" for notes (`labels.textColor`)
- tests for the helper and for every entrance

Plan: sticky_notes_review_final.md §12.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* make footer opacity=1

* chore: fix sticky note test import order

* feat(editor): drag a tool out of the toolbar to drop a default-sized element

Press a tool button and drag onto the canvas: a default-sized element
follows the pointer as a translucent preview and is placed where the
pointer is released. Sticky notes opt in; the mechanism is generic.

`App.toolDrag.ts` owns the gesture. `DRAGGABLE_TOOLS` is the registry —
a tool provides `createElement(app, center)` (the element it drops,
centered on the pointer, from the same `currentItem*` defaults a click
uses) and an optional `onDrop` (a sticky note starts editing its label).
Adding a tool is one entry.

The preview exists only on the unit until the drop: not in the scene, the
store or the history, so collaborators never see it and Escape,
pointercancel, window blur or a release outside the canvas leave nothing
behind. It is painted by the existing `NewElementCanvas`, drawn exactly as
it will land, with the canvas itself made translucent (a CSS opacity on
the canvas — per-draw-call alpha would darken where a shadow and a fill
overlap).

The button arms on pointerdown (a new `onPointerDown` hook on the toggle
`IconButton`) and the drag starts once the pointer has moved
`DRAGGING_THRESHOLD`, so a plain click still selects the tool. Listeners
live on the owner window like the other pointer gestures. The drop is
`insertNewElement` + one store capture (one undo entry), selects the
element and switches to the preferred selection tool — whatever tool was
active (an arrow, say) must not stay armed under the dropped element or
its editor. The hit test prefers `elementFromPoint` (sees through a
touch's implicit capture on the button) and falls back to the event
target where it is missing (jsdom).

Made public on App for the unit: `store`, `startTextEditing`,
`getCurrentItemRoundness`, `getCurrentItemStrokeWidth`.

Tests: drag → preview with an untouched scene and history → drop centered
at the pointer with one history entry, the editor open and the selection
tool active, undo removes it; Escape mid-drag leaves nothing and a late
pointerup is inert; a release outside the canvas drops nothing; a plain
click still selects.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): default a text element's fontSizeMax to null

`newTextElement` left `fontSizeMax` undefined while restore normalizes it
to `null`. `Delta.distinctKeysIterator` compares with `!==`, so a
restored copy of a locally created text element reported a phantom
`fontSizeMax` change — today only in collab reconciliation deltas, which
are not undoable, but a latent source of spurious version bumps.

Normalize to `null` in the constructor, like `labelPosition`. Snapshots
change accordingly (`undefined` → `null`), including the embedded scene
payload in the SVG export snapshot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(editor): drop a duplicated scheduleCapture in the sticky note finalize

A paste error: the two calls in one tick set the same flag.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): decide history visibility from the applied result

Creating a sticky note and abandoning its editor by clicking out left two
history entries: the note's creation, and one that only deleted the empty
label and dropped the note's reference to it — nothing a user can see, so
the first undo appeared to do nothing. (Escape left the same deletion
pending instead, folded into the next entry.) The text tool's own
click-create-and-abandon had the same invisible entry.

History already skips entries with no visible change, but visibility was
decided per property patch, before binding repair and layout ran: an
`isDeleted` flip or a `boundElements` edit always counted, and anything
layout moved afterwards never did.

`ElementsDelta.applyTo` now decides it from the applied result. After the
deltas, reordering, binding repair and text/arrow layout, the "before"
and "after" of every affected element are compared:

- `idsToCheck` = the changed elements plus what layout can move for them:
  a text's container and everything in `boundElements` (a container's
  label and arrows); the set is walked as it grows, so an arrow brings in
  its own label.
- Unchanged elements are shared between the incoming map and the result
  and layout mutates them in place, so their "before" is a shallow copy;
  changed elements already have a fresh instance. The whole scene is
  never copied.
- An element counts as visible only if it is not deleted and, for text,
  not empty — except an empty label carrying arrow bindings or sitting on
  an arrow, where it cuts the gap. `version`, `versionNonce`, `updated`,
  `created` are metadata and `index` is covered by the z-order check;
  `boundElements` is compared as `type:id` strings with references to
  empty labels dropped, so binding repair that rebuilds equal objects
  reads as unchanged. Everything else counts.

A dev/test-only assertion records every element's version before layout
and throws if layout bumped one outside `idsToCheck`, so a new layout
dependency fails a test instead of letting undo silently skip a real
change. For that to work the `return` had to leave the `finally` block: a
return in `finally` overrides a thrown exception, so the existing
dev/test rethrow for failures in reordering and layout never actually
propagated. Production behavior is unchanged — the catch still returns
with the flag forced to visible.

Cost, production build, median per `applyTo`: sparse changes at parity
through 50k elements; 10k visible bulk updates +13%; 10k metadata-only
updates 44 → 95 ms, because proving "nothing visible" cannot stop at the
first element — the case the old code answered wrongly. `applyTo` runs
on undo/redo and the version slider, both user-paced.

Creation and typing still undo separately, and a drop from the toolbar
still records at the drop. Tests: delta-level (empty-label deletion and
restoration on a rectangle and a sticky note ignored; a non-empty label,
an arrow's label gap, a container resized by a restored label, arrow
bindings on empty text, a label and an arrow repositioned by a container
redraw all visible; excluded or already-applied properties and a
metadata-only update invisible; snapshot restoration visible) and the
sticky note flows (Escape, click-out, font change on an empty label,
typing).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): snap sticky note placement to the grid

* perf(editor): ignore arrow bindings in sticky layout input check

* feat(editor): center a sticky note's label in the whole note, tighten the footer

A middle-aligned label was centered in the body above the creation-date
footer, so it sat visibly high — half a footer above the note's center.
It is now centered in the whole padded note (`height − 2·padding`), the
footer ignored, and only pushed up against the body's bottom once
centering would run it into the footer. The fit and the growth rule are
unchanged: the note still grows at the same label height, no vertical
budget is lost, and top and bottom alignment are as before. Rotation
already turned the label about the note's center.

The footer takes less room: its band shrinks from 32px to 20px and the
date's baseline is defined from the note's bottom edge (14px) rather than
from the padding, so the glyphs sit ~11px from the edge (was 17) with
~13px to the label body above (was 19). The vertical inset follows
(64 → 52), and with it the font-aware minimum note sizes.

Tests: a middle-aligned label is centered on the note's center at three
angles; centering is clamped only once it would overlap the footer;
existing sizes derive from the inset constant.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): resize sticky notes proportionally by default

* fix(editor): preserve resize flips and text container anchors

Apply minimum sizes and proportional font scaling to dimension magnitudes, then restore their signs for shared flip geometry.

Share rotation-aware positioning for text-driven height changes and pass vertical flip state through single and multiple-element resizing.

Add regression coverage for mirrored resizing, proportional minimum sizes, and text growth after crossing the resize anchor.

* feat(editor): lift a seeded sticky note corner at high roughness

Curve one corner at roughness 2, chosen from the note seed so it stays consistent through redraws and resizes. Pull its shadow inward by half the bend while retaining the existing down-right offset.

Share the generated paper and shadow paths between Canvas and SVG rendering.

* fix(editor): share the default sticky note color with its quick pick

* refactor(editor): rename a label's `fontSizeMax` to `baseFontSize`

The field holds the font size the user picked, from which the sticky note
layout derives the fitted `fontSize`. "Max" described today's fitter (it
only shrinks); "base" names the intent and pairs with the note's
`baseHeight`, the other user-set value the layout derives from. Renamed
before the field ships, since it is persisted in scene files.

The type is now required (`number | null`): the constructor and restore
already always write it, and history deltas compare with strict
inequality, so an omitted key against `null` would record a spurious
change. Making it required lets tsc catch producers that omit it (one test
fixture did). Helpers follow: `getBaseFontSize`, `getBaseFontSizeUpdate`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): slightly strengthen sticky note edges

* feat(editor): color a sticky note's background while editing its label

While editing a note's label the styles panel targets the label, which has
no fill, so the background picker was gone and the note's color could only
be changed after leaving the editor. The picker now stays available while
editing, shows the note's fill, and a pick colors the note — text color and
background in one editing pass.

One helper, `getColorTargetElement`, decides where a color pick on an
element lands (a background pick on a note's label goes to the note); the
target resolver, the panel predicate, the panel value and the action all
use it, so the picker also gets the sticky domain (sticky picks, no
transparent, the sticky default written).

Also fixes a latent bug in the background action: with nothing selected,
`selectedElements.every(isLine…)` was vacuously true, so the action took
the polygon branch and did nothing. Unreachable before, since no background
picker was available without a selection.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix changelog

* fix snaps

* more snap

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 16:45:37 +02:00
David LuzarandClaude Fable 5.1 6574de60b3 feat(editor): snap element bitmaps, scroll and grid to whole device pixels (#12063)
* feat(editor): blit cached element bitmaps on whole device pixels

Elements are painted from cached bitmaps, blitted 1:1 with smoothing
disabled for unrotated and right-angle elements. Nearest-neighbor at a
fractional offset is then a pixel-exact copy shifted to the nearest
pixel — except at an exact half pixel, where a GPU-accelerated canvas
decides the rounding per scanline by float precision: a few rows sample
the neighboring row and glyph strokes come out doubled or broken, varying
with scroll and position. A centered label lands on a half pixel
routinely (odd free space ÷ 2), which is how it showed up on sticky notes.

Measured in Chrome: a label blitted at y = 639.5 had 3 of 82 scanlines
taken from the adjacent row; rounded to 640 it was clean.

Round the blit position to whole device pixels for those elements. The
context is scaled at the blit (canvas scale × zoom ÷ devicePixelRatio),
so the rounding goes through `context.getTransform()`: rounding the
pre-zoom value only lands on device pixels at 100% zoom. Rotated
elements are resampled regardless and are left alone; export draws
directly and is unaffected.

Tests: the static canvas's `drawImage` events, with their CTM, land on
whole device pixels for text and a rectangle at zoom 1, 1.5, 0.73 and
2.2 under fractional scroll; a rotated element keeps its offset.

Extracted from dwelle/sticky-notes-2 (originally eddb67ca0).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): draw the canvases at a whole-device-pixel scroll

Panning writes a fractional scroll (pointer delta ÷ zoom). With every
bitmap landing on its nearest device pixel, a fractional scroll means
elements with different sub-pixel phases jump on different frames — a
one-pixel wobble between neighbors, a label shifting against its box —
and one scroll value in every pixel puts every integer-positioned
element on the half-pixel boundary at once.

Round the scroll to whole device pixels at render time, in all three
renderers with the same formula so overlays sit on the content — the way
a browser scrolls a page: each element keeps its own constant sub-pixel
phase and the scene moves rigidly. The real scroll in state is untouched,
so hit-testing and DOM overlays are unaffected; the difference stays
under half a device pixel. Export is excluded (it draws vectors).

Tests: the helper rounds to device pixels and is identity when already
whole; a rectangle at integer coordinates blits on whole device pixels at
zoom 1 and 1.5 under fractional scroll, and a scroll a tenth of a pixel
further lands on the same pixels.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(editor): draw grid lines on whole device pixels at every zoom

The grid was nudged onto the pixel grid only at 100% zoom, and only when
the scroll happened to be whole; at any other zoom its one-pixel lines
landed on fractional device pixels and rendered as two lighter pixels.

Draw each line a whole number of device pixels wide, centered to cover
them exactly (on the half pixel when the count is odd), computed from the
zoom and the canvas scale — which also makes "one pixel" one device pixel
group at devicePixelRatio 2 instead of a fractional pair. Lines thinner
than a device pixel (zoomed far out) keep their sub-pixel width: their
lightness is the point. The zoom-1-only nudge is subsumed.

Test: with grid mode on, every grid path start on the static canvas has
its across-axis coordinate on a half device pixel at zoom 1, 1.5 and 2.2
under fractional scroll.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): snap right-angle blits via the transform origin; grid width in device pixels

Two review findings.

Elements rotated by 90° or 270° enter the snapping branch (smoothing is
off for right angles too), but their transform has near-zero `a` and `d`
with the scale in `b`/`c`. Dividing by the diagonal sent the bitmap far
offscreen — a rectangle at (110.37, 120.61) vanished at both angles.
The snap now moves the transform's origin onto the rounded device
position of the blit and draws at (0, 0): rotation, mirroring and scale
stay in `a`–`d`, no inverse is needed, and the origin is an exact integer
even in the canvas's float32 matrix (mapping a rounded position back
through user space left it ~1e-5 off).

The grid's "at least one device pixel wide" test compared
`(1 / zoom) × zoom × scale` against 1 exactly; at 190% that product is
0.9999999999999999, so those lines skipped snapping and stayed blurry
while neighboring zooms were crisp. The width is now computed straight
in device pixels, `min(scale, max × zoom × scale)`, so there is no round
trip to tolerate.

Tests: rectangles at π/2 and 3π/2 blit on whole device pixels and stay
next to the element; the grid test includes 190%. The blit helper in the
test maps positions through the full matrix. The CHANGELOG bullets link
the PR.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(editor): one devicePixelRatio read for the blit, no-op padding scaling dropped

`drawElementFromCanvas` read `window.devicePixelRatio` eleven times; it
reads it once. That read stays the global one on purpose: the cached
bitmap was generated with it (`generateElementCanvas`) and the blit's
size math needs the same value, so switching this path to the owner
window's ratio is a separate change that has to include bitmap
generation. `(padding × scale) / scale` is `padding`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): snap blits only where smoothing is off, through one predicate

The snap ran during zoom gestures too, where the cached bitmaps stay at
the old scale and are resampled with smoothing on: rounding there could
only make elements twitch as the scale changes.

The smoothing switch and the snap now share `canSnapElement` — unrotated
or at a right angle, and not mid-gesture — so the two cannot drift
apart. It is eligibility, not a guarantee of a 1:1 copy: freedraw is
blitted with smoothing on and a size-capped cache is rescaled; snapping
is harmless for both.

Test: with `shouldCacheIgnoreZoom` set, the blit keeps its fractional
position.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(editor): snap a label relative to its container, tie-safe

Each bitmap rounding its own origin lets a label shift by a pixel against
its box as a drag crosses half pixels (nearest-neighbor sampling did the
same implicitly before the explicit snap). A label under an unrotated
container now anchors to the container's rounded origin and rounds its
offset from it separately, so both land on whole pixels and their
distance never changes; every other element anchors to itself with a
zero offset, through the same code path.

The offset is formed from scene coordinates before the scroll is added,
and a tiny bias breaks an exact half-pixel tie the same way every frame.
Ties are common — any odd scene offset at 150% — and the float noise of
a fractional drag otherwise flips `Math.round` between the two neighbors:
a 200-wide box with a centered label went 92 → 91 → 92 device pixels
across drags of 0, 0.3 and 0.4.

Tests: a plain fractional offset and the half-pixel tie keep a constant
device offset across five fractional drags at 150%.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 14:39:59 +02:00
David LuzarandMárk Tolmács 854d00c31b feat(editor): track element creation timestamps (#12060)
feat(editor): element creation timestamp tracking

Co-authored-by: Márk Tolmács <mark@lazycat.hu>
2026-09-08 15:26:14 +02:00
David LuzarandClaude Fable 5.1 f1a79b73df perf(editor): stop inverting the interactive canvas via CSS filter in dark mode (#12050)
The interactive canvas (selection outlines, transform handles, binding
highlights, collaborator cursors, snap lines, scrollbars) was still
composited through `filter: invert(93%) hue-rotate(180deg)` in dark mode
(#10578 only de-filtered the static canvas). The canvas covers the whole
viewport and repaints on nearly every pointer move, so browsers that
composite in software (Firefox/Zen on software WebRender or with hardware
acceleration disabled) paid for a full-viewport color-matrix pass per frame
and dropped from 120fps to ~40fps during marquee/drag. Light mode was
unaffected.

Colors are now mapped in JS via `applyDarkModeFilter`, like the static
canvas. Hardcoded dark-mode values are the exact post-filter equivalents of
the previous ones, so rendering is unchanged, with two intentional
exceptions:

- collaborator cursors and remote selection outlines render in the
  collaborators' actual colors (matching their avatars) instead of inverted
  ones (per the existing TODO in clients.ts)
- the lasso trail now uses the theme's `--color-selection` like the marquee
  selection, instead of a hardcoded light-theme purple that never matched in
  dark mode

`--color-selection` for the dark theme now holds the actual rendered color
(#b4b0ff); hosts overriding it no longer need to pre-invert.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 11:52:22 +02:00
214cd6e6e8 feat(editor): allow for dragging bound text along an arrow's path (#10947)
Arrow labels can be dragged along their arrow. A label's place is stored on the text element as labelPosition, a normalized arc-length parameter (0–1) over the arrow's whole path, and the label's x/y is derived from it. Because the parameter covers the whole path rather than one segment, the label keeps its place when points are dragged, when midpoints are inserted or removed, and when the arrow is resized. (An earlier iteration anchored labels to a segment; that approach is gone.)

Closes #9338.
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-03 17:21:13 +02:00
David Luzar 5e375b4331 fix(editor): do not flicker bbox when drag-creating line midpoint (#11834) 2026-08-05 10:52:10 +02:00
David Luzar c9c96f619c fix(editor): normalize container + bound text order on restore (#11827) 2026-08-04 23:32:15 +02:00
nihaarsirikonda ab0255f21e fix(editor): prevent crash when editing arrow with bound text (#11814) 2026-08-04 16:31:37 +02:00
792ea3a06c feat(editor): bucket fill (#11799)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
2026-08-04 16:25:16 +02:00
David Luzar f1aa8f86a9 feat(editor): disable arrowhead toggle via dblclick (#11822) 2026-08-04 16:25:00 +02:00
David Luzar 1acf66edab feat(editor): bind text to hovered arrow endpoint (#11777) 2026-07-28 18:12:33 +02:00
David Luzar b2e81e38a6 feat(editor): autoshape text + line improvements (#11752) 2026-07-24 16:10:00 +02:00
f179f7ffd2 feat(editor): draw to shape (auto-detection) (#9313)
* Initial commit

* Segments detection

* Remove aspect ratio

* Refactor

* Fix tests

* Toggle shapeSnap

* Fix linting

* debug: live preview

* Rebase fixes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* Bind to elements (no hover background)

* Shape closed

* Fix rad calc + rename segments

* Comments

* Fix binding highlighting + lints

* Rename to convert to shape

* fix: Binding

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Refactor spline simplification

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Remove unused doBoundsIntersect

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Restore type signature

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Propose new button shapes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Remove unused types

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Icon shapes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Element cloning

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Element cloning

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Remove unused

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Shape settings in recognition mode

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Remove debug

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Actions

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Lint

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Arrowheads for freedraw

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Draw shape tool instead of freedraw

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Test

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Lint

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Keyboard shortcut visibility

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Unique cursor for draw shape

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Remove selection

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Shape selection

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Improve shape recognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Further refine shape recognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Preview

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Add hint

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Refined shape recognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Less ellipse more rectanguloid

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Refined arrow recognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Refinerecognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* chore: Lower linear threshold

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Rectangle head arrow

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: More arrowhead sizes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Arrow remains an arrow

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Draw line between elements converts to arrow

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* remove pendingDrawShapeElement

* fix: Arrow start point binding

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Different arrow endpoint heuristic

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Point type

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Various small fixes

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Avoid recompute

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Type issues

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* test(editor): cover the drawShape (snap-to-shape) tool

The drawShape tool had no dedicated tests, which let master's toolbar /
active-tool rewrite silently break it during the merge: actionFinalize
reverted to the selection tool after every sketch, because the drawShape
flow finalizes without a `newElement` and so failed master's new
`&& element` guard.

Covers the behavior the merge had to preserve:
- sketch recognition (rectangle, ellipse) and the too-small no-op
- the tool stays active after finalizing, so shapes can be sketched
  consecutively (regression guard for the above)
- activation via the S shortcut and the extra-tools dropdown
- the tool's own cursor

Points are fed into the trail directly rather than through pointermove,
which is rAF-throttled and would drop all but one point per frame — the
same approach lasso.test.tsx uses.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: Add test

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: Breakout from App.tsx

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Shortcut is now Shift+X

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: No selecting arrows for shape recog

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* fix: Double history

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* feat: PCA + feature extraction recognition

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>

* reduce and normalize min-size gates

* never select newElement when shape recog tool active

* simplify lifecycle & remove double finalize

* make arrows bindings orbit

* funnel though actionFinalize & fix two unrelated cleanup cases

* use crosshair cursor

* show strokeWidth

* switch icons for drawShape & extraTools

* dedupe getBoundsFromPoints

* remove unused helpers

* jsdoc cleanup

* dynamic trail size

* improve rectangle recognition

* disallow linears to deviate too much from a straight line

* put under freedraw tool on tablet/mobile

* tweak label

* rename `drawShape` -> `autoshape`

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 18:42:42 +02:00