Compare commits

...
Author SHA1 Message Date
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
Arne ReiandMahiro Hirakawa 4c37956ba5 fix(editor): detect line height from the migrated font props on restore (#12033)
* fix(editor): detect line height from the migrated font props on restore

The text branch of `restoreElement` parses the legacy `font` prop into local
`fontSize` and `fontFamily`, but line-height detection kept reading
`element.fontSize` and `element.fontFamily`. A diagram old enough to carry
`font` has neither, so `detectLineHeight` divided by `undefined` and the
element was restored with `lineHeight: NaN`. A non-numeric `height` produced
the same result.

Move the detection into `restoreLineHeight`, pass it the already-migrated
values, and fall back to the font family's fixed line height when the
detected value isn't a usable number.

---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mahiro Hirakawa <mahirohirakawa@glovrex.com>
2026-10-14 18:29:25 +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
Milos Vetesnik 4f310b7996 feat(app): restyle Excalidraw+ upgrade button as stacked trial CTA (#12269)
* feat: restyle Excalidraw+ upgrade button as stacked trial CTA with sparkle

* feat: use gift icon instead of sparkle on Excalidraw+ button
2026-10-12 13:28:00 +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 4c00f31ddc feat(editor): autoplay Google Drive videos when the embed is activated (#12246)
- Drive's player has no postMessage API (unlike YouTube/Vimeo), but its
  /preview page honors `autoplay=1`, so the first activation reloads the
  embed with it: a single click plays the video in view mode
- reloaded via `contentWindow.location.replace` so it adds no history
  entry, and only once per iframe so re-activating doesn't restart it

Claude Opus 5.5 (1M), xhigh effort
2026-10-08 11:11:53 +02:00
David Luzar 2559257bb2 fix(editor): pan once and keep editing on a wheel-button drag over the text editor (#12244)
- the text editor's window pointerdown listener was added in capture mode
  but removed without it, so every past editing session kept panning too:
  the pan was multiplied by the number of texts edited since load
- the pan focuses the container, which blurred the editor while blur still
  submitted it; submit is now disabled before the pan starts, and the
  editor is refocused on release

Claude Opus 5.5 (1M), xhigh effort
2026-10-07 20:31:58 +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 35e854ecf7 feat(app): label E+ banner Upgrade / Sign in (#12204)
Claude Opus 5.5 (xhigh)
2026-09-29 17:44:41 +02:00
Renan-MouraN 5a406e5187 fix(app): correct typo in Mermaid input placeholder (#12186)
fix: correct typo in Mermaid input placeholder
2026-09-28 22:18:02 +00:00
David Luzar e283f724c8 refactor(editor): move the clipboard out of App into AppClipboard (app.clipboard) (#12197)
* refactor(editor): move the clipboard out of App into AppClipboard (app.clipboard)

A pure move of the clipboard handling out of App.tsx (13,478 → 12,942
lines) into App.clipboard.ts: onCut and onCopy (the document's cut/copy
events, through their actions), pasteFromClipboard (the paste event,
parsed, and handed to a host's onPaste first), insertClipboardContent
(inserting the pasted data as whatever it is: images or SVG code,
elements, a Mermaid definition, embeddable URLs, a spreadsheet as a
chart, mixed content, or text), addElementsFromMixedContentPaste and
addTextFromPaste. The plain-paste flags move along as module-level state;
Ctrl/Cmd+V's marking of a plain paste, and its reset, are App's former
lines behind app.clipboard.onPasteShortcut and clearPlainPaste.

Staying in App: addElementsFromPasteOrLibrary and insertImages, shared
with drop, the library and text-to-diagram (insertImages becomes public
for the clipboard), and onIframeSrcCopy, which belongs to the magic frame.

Callers go through `app.clipboard`: no delegate is left on App, and
AppClassProperties exposes `clipboard` (as it does `textTool`) instead of
`pasteFromClipboard`. Beyond the move, `this.` becomes `this.app.` for
what stays on App, onCut and onCopy become public, and the container ref
comes in as a dependency. The moved code is identical to the removed,
modulo those rewrites, whitespace and trailing commas (checked
mechanically).

Claude Opus 5.5 (1M), xhigh effort

* test(editor): cover copy/cut events and more paste routes

Only 80% of the clipboard code ran under the suite, and nothing went
through the document's copy and cut events, which is how Ctrl/Cmd+C/X
reach the editor in a browser. Now a copy event copies the selection and
a cut event cuts it; a host's onPaste returning false keeps the paste
from being inserted; a pasted spreadsheet opens the charts dialog; and
with the image tool off, a paste of mixed content inserts its text.

Claude Opus 5.5 (1M), xhigh effort
2026-09-28 23:51:36 +02:00
David Luzar 3947883063 refactor(editor): move text editing out of App into AppText (app.text) (#12195)
* refactor(editor): move text editing out of App into AppText (app.text)

A pure move of the text editing session, and of the text helpers around
it, out of App.tsx (14,250 → 13,478 lines) into App.text.ts. It sits next
to AppTextTool, which keeps the text tool's pointer interaction.

AppText holds:
- the session: startTextEditing (creates or picks the text to edit, and
  opens the editor), handleTextWysiwyg (the editor's lifecycle) and the
  open editor's submit handler
- the part of the canvas a typed or pasted text is kept within:
  getTextSidePanels, getTextViewportOffsets and getMaxTextWidth (paste,
  which stays in App for now, calls into them)
- where a new text goes: getTextCreationGridPoint and
  getTextWysiwygSnappedToCenterPosition
- the queries that find the text or container to edit:
  getTextElementAtPosition, getTextBindableContainerAtPosition,
  getSelectedTextElement, getSelectedTextEditingContainerAtPosition and
  isEditingTextContent
- the auto-resize handle: isHittingTextAutoResizeHandle and
  handleTextAutoResizeHandlePointerDown

Callers go through `app.text`, startTextEditing's included: no delegate
is left on App (no host or test used it). Beyond the move, `this.`
becomes `this.app.` for what stays on App, members called from outside
become public (App.deselectElements too), and the container ref and the
styles panel mode come in as dependencies, as AppViewport's do. The moved
code is identical to the removed, modulo those rewrites, whitespace and
trailing commas (checked mechanically).

Claude Opus 5.5 (1M), xhigh effort

* test(editor): click the text auto-resize handle through the pointer

The handle that turns a fixed-width text back into a growing one was only
covered through its action: nothing hovered or clicked it. Hovering it on
a selected wrapped text now shows the pointer cursor, and clicking it
unwraps the text, through AppText's hit test and pointerdown handler.

Claude Opus 5.5 (1M), xhigh effort
2026-09-28 22:18:13 +02:00
David Luzar 3d056dbc8a feat(editor): wrap text at 800 and keep it clear of the side panels (#12192)
* feat(editor): wrap typed & pasted text at 800, clear of the side panels

A free text growing as it's typed stopped only at the view's width
(#12175), so on a large screen it ran to 2000+ px before wrapping, and a
pasted text wrapped at half the view. Both now follow one rule, in
`getMaxTextWidth`:

- no wider than TEXT_MAX_WRAP_WIDTH (800, in @excalidraw/common) in scene
  units, at any zoom: the paste's former cap, now shared. A paste no
  longer wraps at half the view.
- nor wider than the canvas between the side panels, less
  TEXT_VIEWPORT_PADDING at each side: the docked sidebar, as before; the
  full styles panel (desktop), which shows next to a text while it's
  edited, and once it's pasted and selected (pasting with nothing
  selected, its room is reserved: as last measured, else approximately);
  and the stats panel, only for a text beside it, i.e. with rows within
  that padding of it, as it covers only the top of the canvas' side.

A text that starts wrapping is brought in between the same panels, as
before. A paste is laid out as if the stats panel weren't there, and
again, clear of it, only if it lands beside it. As the stats panel grows
to show a selection's properties, with it open the paste is rendered
selected first (not captured yet, via `flushSync`), so the panels are
measured as they'll be; laid out again, it stays the same elements, and
one undo step. A wrapped paste is then moved into view (as far as the view
would have scrolled), instead of scrolling the view.

The stats panel is marked as side viewport UI (`data-viewport-ui="side"`,
named "stats"), so the viewport offsets' other users (zoom to fit, scroll
to content, search, a host's `setViewport` with UI offsets) keep clear of
it too while it's open. `AppViewport` gains `getSideInsets(names,
{ reserve })`, generalizing `getSidebarInsets`, and `getSideUIRect(name)`;
`getOffsets` shares the reserve fallback through `getReservedSide`.

Tests: the cap at 50% and 200%; a typed text clear of the styles and the
stats panel, and of the stats panel only beside it; a paste wrapping as a
typed one, with the styles panel's room reserved; a paste clear of the
stats panel only where it lands beside it, and of the stats panel grown to
show it, as one undo step; a wrapped paste moved into view, the view not
scrolled.

Claude Opus 5.5 (1M), xhigh effort

* feat(editor): pan the canvas when the caret goes under the stats or styles panel

The canvas follows the caret past the view's edge, and behind the docked
sidebar, through the editor's box, which the browser scrolls to reveal a
caret (#12175). The stats and the full styles panel don't span the box's
height, so a caret typed in under them stayed out of sight.

After each input, once the update (and any scroll it made) is in the
app's state, the editor works out where the caret is: its line from
`getWrappedTextLines`, its x from the width of the line before it,
rotated with the text. In a line with RTL characters (`hasRTLChars`, new
in @excalidraw/common) the x comes from the browser's bidirectional
layout of the line instead, in its paragraph's direction (the editor's
`dir="auto"` makes it `unicode-bidi: plaintext`: each paragraph goes its
first strong character's way): with Hebrew then English, the caret after
the English is mid-line, not at the line's edge. That's measured through
a range in an off-screen mirror of the line, shared with the
click-to-caret lookup. If the caret's under one of those panels, the
canvas pans to bring it out on the canvas' side, with
CARET_FOLLOW_PADDING to spare. Only then: a text beside or below a panel
stays where it is.

Tests: typing past the stats panel's left edge pans the canvas under it,
but not below it; the caret in a bidirectional line, a paragraph after
one going the other way, is found where the browser lays it out.

Claude Opus 5.5 (1M), xhigh effort
2026-09-28 21:06:41 +02:00
2d3707b816 feat(editor): add showHints to command palette (#12187)
* feat(editor): route showHints through the action system (#12165 follow-up)

`showHints` was the only item in the Preferences submenu that flipped
appState directly instead of going through an action, so it was missing
everything the action system provides: no command palette entry, no
`trackEvent`, no `viewMode` declaration.

- add `actionToggleShowHints`, modelled on `actionToggleMidpointSnapping`
  (`viewMode: false` — hints live in the toolbar, which view mode hides)
- register it under `ActionName` and export it from `actions/index.ts`
- `PreferencesToggleShowHintsItem` now calls `executeAction`
- list it in the command palette's editor commands
- document `appState.showHints` /
  `MainMenu.DefaultItems.Preferences.ToggleShowHints` in the CHANGELOG,
  which the original commit never touched

No keyboard shortcut: like `arrowBinding` and `midpointSnapping`, this is
a set-once preference, and the natural mnemonic (`Alt+H`) is already
distribute-horizontally.

Adds `tests/showHints.test.tsx` — the preference previously had no
behavioural coverage at all, only incidental snapshot entries.

* chore(editor): drop showHints tests & changelog entry

Both will be rewritten in a follow-up PR.

Opus 5.5 (1M context), xhigh

---------

Co-authored-by: hiennd <hiennd@aidia.vn>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-28 09:17:05 +00:00
David Luzarandhiennd 834e5af631 fix(editor): follow-ups to zen mode polish & delayed tooltips (#12188)
* fix(editor): follow-ups to zen mode polish & delayed tooltips (#12165)

Tooltip state (timer + warm window) is shared by all instances, since they
share one tooltip node. Without an owner, any unrelated Tooltip unmounting
(a collaborator leaving, a sidebar breakpoint) cancelled or hid a tooltip
the user was still hovering. Track the owning item and only hide from the
paths that own it; `hideTooltip` no longer creates the tooltip node just to
hide it.

Zen mode hides or slides controls without the pointer moving, so nothing
fired pointerleave to retract their tooltips — markZenModeTransition now
hides the tooltip up front.

`:focus-visible` was not excluded from the chrome-less zen-mode rules, so
the keyboard focus ring (a box-shadow) disappeared for the main menu
trigger, scroll-back-to-content and exit-zen-mode buttons.

The zoom buttons lost their native `title`, which was the only channel
carrying their shortcut to keyboard/AT users — expose it via
`aria-keyshortcuts`, as Tools.tsx does.

Also: schedule the zen-mode timer on `ownerWindow` like every other
DOM-touching timer in App.tsx, re-read the container ref when unflagging
(and unflag on unmount), and drop the footer-left `--transition-left`
class, which never matched a selector.

Adds the missing coverage for the transition-attribute lifecycle, the
`openMenu`-across-view-mode fix, and the tooltip delay/warm window.

Split out of #12187 and ported onto the #12173 Tooltip rework: the owner
is set in `showTooltip`, and its MutationObserver already retracts a
tooltip whose wrapper got `disabled`, so that extra effect is dropped, as
is the delayed-show label ref (`showTooltip` takes the label by value).

Opus 5.5 (1M context), xhigh

* refactor(editor): drop tooltip owner tracking, trim tests

Since #12173, `showTooltip`'s MutationObserver retracts a visible tooltip
whose wrapper leaves the DOM, and its `isConnected` check drops a pending
one. That makes the Tooltip unmount effect, which hid whatever tooltip was
showing, redundant: removing it fixes the unrelated-unmount bug on its own,
without tracking an owner.

Also drop zenMode.test.tsx and the tooltip tests that duplicated others.

Opus 5.5 (1M context), xhigh

---------

Co-authored-by: hiennd <hiennd@aidia.vn>
2026-09-28 10:14:30 +02:00
Dinesh Yadavanddwelle 438d89861f docs(repo): remove obsolete CodeSandbox contribution workflow (#11908)
* docs: remove obsolete CodeSandbox contribution workflow

https://codesandbox.io/p/github/excalidraw/excalidraw (forking the
whole repo as an editable sandbox to submit PRs from) no longer works.
It was documented in two places — the Contributing guide and the
Development guide — as an alternative to the manual clone/fork setup.

This doesn't touch the other CodeSandbox links in the docs (README,
installation/integration/development guides for the @excalidraw/excalidraw
package), which point at the separate with-script-in-browser usage example
and are unrelated to this contribution workflow.

* chore: trigger CI

Claude Opus 5.5 (low)

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-27 20:53:17 +00:00
David Luzar 02fc9f3505 fix(packages/excalidraw): setViewport stops following a collaborator (#12184)
Navigating with `setViewport` takes the view over from the followed user,
as a user's pan or zoom does, so it now asks to stop following
(`requestUnfollow`: `onUserFollow` with `action: "UNFOLLOW"`, when
`userToFollow` is set). `setViewport(null)`, which only clears a lock, and
a target that doesn't resolve don't navigate and leave following alone.

Following itself doesn't go through `setViewport`: excalidraw-app and
Excalidraw+ both apply the followed user's viewport with `updateScene` +
`zoomToFitBounds`, so it's unaffected.

Tests: navigating emits the UNFOLLOW intent once; clearing a lock and an
unresolved target don't.

Claude Opus 5.5 (1M), xhigh effort
2026-09-27 19:47:29 +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
afed9e6e27 fix(editor): handle the save-as shortcut while editing text (#11922)
* fix(editor): handle the save-as shortcut while editing text

Cmd/Ctrl+Shift+S did nothing while a text editor was open — the editor stayed
open and no save happened. Plain Cmd/Ctrl+S worked.

The wysiwyg keydown handler only branches on `actionSaveToActiveFile`, whose
keyTest requires `!event.shiftKey`, so the shift variant matched nothing and was
swallowed. This adds the sibling branch for `actionSaveFileToDisk`, mirroring
what the plain shortcut already does: commit the text, then run the action.

Complements #9281, which fixed the plain shortcut in the same handler.

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

* test(editor): assert the save-as shortcut actually dispatches the save

Review feedback: the regression test only asserted that editing ended, which
`handleSubmit()` satisfies on its own — the test still passed with the
`executeAction(actionSaveFileToDisk)` call deleted, so half the fix was unpinned.

Now spies on `saveAsJSON`, which is what the action ultimately reaches, and
captures `editingTextElement` at the moment it runs so the ordering (commit,
then save) is pinned too. Verified: removing the dispatch now fails with
`expected "saveAsJSON" to be called 1 times, but got 0 times`.

Also adds a negative case — closing the editor with Escape must not save — so
the spy proves the save is tied to the shortcut rather than to teardown.

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

* fix(editor): dispatch text-editor save shortcuts as keyboard actions, trim tests

- pass the "keyboard" source for both save shortcuts in the wysiwyg keydown
  (was the default "api", which skipped the interaction gate and mistracked)
- drop the explanatory comment on the save-as branch
- fold the three save tests into one it.each in the existing container-unbound
  suite, covering both Cmd/Ctrl+S and Cmd/Ctrl+Shift+S and pinning that the
  text is committed before saveAsJSON runs

Claude Opus 5.5 (1M context), xhigh

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-26 22:38:03 +00:00
David Luzar d29d864884 feat(editor): file drop overlay & shift-to-merge imported scene (#12177)
* feat(editor): add file drop overlay and Shift-to-insert support

* fix(editor): report copy drop effect for file drags

Shift defaults a drag to "move" (and a "Move" cursor), but a dropped file
is only ever read in, never moved.

Opus 5.5 (xhigh)

* fix(editor): ignore file drops in view mode and when non-interactive

The dragover/drop cancel listeners were only registered in edit mode, so
elsewhere the browser opened a dropped file natively. Register them always,
show a no-drop cursor where drops are ignored, and don't handle the drop.

Opus 5.5 (xhigh)

* feat(editor): cross out the existing file in the drop overlay when replacing

Opus 5.5 (xhigh)

* fix(editor): note that library files won't replace content in the drop overlay

OS-dragged .excalidraw and .excalidrawlib files both report an empty MIME
type until dropped, so the overlay can't tell them apart. Keep the replace
copy for untyped files and add a secondary note for libraries.

Opus 5.5 (xhigh)

* fix(editor): use --overlay-bg-color for modal and file drop backdrops

Replaces color-mix() in the file drop overlay, which is newer than our
browserslist, with the (previously unused) --overlay-bg-color token, now
hardcoded per theme, and reuses it for the <Modal> backdrop.

Opus 5.5 (xhigh)

* fix(editor): scope image-scene drop try to parsing, drop redundant preventDefault

Only loadFromBlob is wrapped now, so an error while inserting or replacing
isn't reported as an invalid file or followed by a plain image insert.
App's dragover listener is always registered, so the overlay no longer needs
to call preventDefault itself.

Opus 5.5 (xhigh)

* fix(editor): don't let the browser open files dropped on modals

Modal portals live outside the editor container, so its dragover/drop
listeners didn't cover them. Cancel file drags on body-level portal
containers, leaving non-file drags (e.g. text into inputs) native.

Opus 5.5 (xhigh)

* chore(editor): move fileDrop locale strings next to overwriteConfirm

Opus 5.5 (xhigh)

* feat(editor): toast how to undo after a drop replaces the scene

Opus 5.5 (xhigh)
2026-09-27 00:18:02 +02: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 c12a8cd037 fix(editor): reduce cursor hint cooldown to 30s (#12174) 2026-09-26 11:19:00 +02:00
David Luzar 5feb2172d5 feat(editor): better library search + display names (#12173)
* feat(editor): delayed name tooltip on library items

- library items with a name show it in a tooltip above the item after
  the standard tooltip delay (500ms, or right away when moving over from
  another tooltip); hidden on leave and on press
- driven by pointer (not mouse) events so touch taps don't leave the
  tooltip behind, while the mouse-driven hover state (which reveals the
  checkbox on tablets) stays as is
- no per-item hooks: Tooltip exposes `showTooltip()` / `hideTooltip()`
  (plus a `position` option) for elements that can't be wrapped in
  <Tooltip>, and <Tooltip> itself now uses them
- a visible tooltip now hides once its item is removed from the DOM
  (e.g. filtered out by the library search, sidebar closed), which fires
  no pointerleave. A MutationObserver is active only while a tooltip is
  visible; a delayed tooltip whose item unmounted while pending no
  longer shows

Opus 5.5 (1M context), xhigh

* fix(editor): Escape in library search clears it instead of closing sidebar

With a search active in an undocked sidebar, Escape closed the sidebar:
the search relied on the browser's native clearing of search inputs, but
nothing stopped the event from reaching the Sidebar's document Escape
listener. Clear the search ourselves and stop the event on the input.
A second Escape (empty search) still closes the sidebar.

Also adds a test for Escape clearing the item selection without closing
the sidebar (already working).

Opus 5.5 (1M context), xhigh

* feat(editor): larger named items in library search results

- search results render in 2 columns with bigger previews and the item
  name below (ellipsified when it overflows); the whole card, name
  included, is clickable/draggable
- the name tooltip only shows when the name is truncated
- placeholders match the card size, and the grid is full width so it
  doesn't shrink to its content while only placeholders are rendered
- reserve the library scrollbar's space (scrollbar-gutter: stable) so
  the content doesn't shift when results start/stop overflowing

Opus 5.5 (1M context), xhigh
2026-09-26 11:03:47 +02:00
David LuzarandGitUserVivek 5db42c3ddb feat(editor): zen mode polish, hide toolbar hints preference & delayed canvas tooltips (#12165)
* feat(editor): preference to hide toolbar hints

Add a "Show hints" checkbox to the Preferences menu, backed by a new
browser-persisted `appState.showHints` (default true). When off,
HintViewer renders nothing. Also exposed as `Preferences.ToggleShowHints`
for hosts composing their own preferences list.

Opus 5.5 (1M context), low

* fix(editor): keep main menu open when toggling view mode

Entering view mode ran terminateActiveInteraction, which reset
`openMenu` and closed the main menu the user had just toggled view mode
from (Preferences submenu). The main menu stays available in view mode,
so only close it when interaction gets disabled.

Opus 5.5 (1M context), low

* feat(editor): chrome-less canvas controls & in-place fades in zen mode

- UI hidden in zen mode fades out in place (opacity + visibility) instead
  of sliding off the viewport, and is non-interactive from the start of
  the fade
- visible canvas controls (toolbar, main menu trigger, zoom, scroll back
  to content, exit zen mode) drop their background/border/shadow;
  hover/active states still apply, popups & dialogs are unaffected
- only the zoom level stays visible out of the zoom controls
- chrome fades are applied only while toggling (data-zen-mode-transition
  on the container, set before the DOM update) so hover transitions stay
  instant
- single ZEN_MODE_TRANSITION_DURATION, exposed to CSS as
  --zen-mode-transition-duration
- zoom & undo/redo button groups paint a single background (on the
  group) instead of one per button

Opus 5.5 (1M context), low

* feat(editor): shift zoom level into the zoom-out slot in zen mode

With the zoom +/- buttons hidden in zen mode, slide the zoom level over
to the left edge of the group. The shift is applied to the Tooltip
wrapper (new `className` prop) rather than the button, so the tooltip
(positioned off the wrapper) moves along.

Also give the reset-zoom button its own hover background: unlike the
+/- buttons it has no .ToolIcon__icon, and lost its (incidental) hover
once the per-button backgrounds were removed.

Opus 5.5 (1M context), low

* feat(editor): delayed tooltips on canvas buttons

- Tooltip gets a `delay` prop: shows after 500ms, or right away if a
  tooltip was visible within the last 300ms (moving across adjacent
  buttons); passing over a button quickly doesn't flash one
- enable it for the zoom, undo/redo & help buttons
- zoom +/- use our Tooltip instead of the native `title`, and the reset
  zoom button drops its native `title` (it was showing both)
- zen mode now hides the zoom +/- tooltip wrappers rather than the
  buttons, so the invisible wrappers don't show tooltips

Opus 5.5 (1M context), low

Co-authored-by: GitUserVivek <jagtapvs9832@gmail.com>
2026-09-25 00:42:59 +02:00
David Luzar e40d1cba95 feat(editor): compact styles panel (#12163)
* fix(editor): align buttons inflating styles panel intrinsic width

The flex-wrap row break (zero-height flex-basis: 100% spacer) only breaks
the line at layout time; for intrinsic sizing both rows were measured as
a single line. Render the two rows as separate flex rows instead.

Opus 5.5 (1M context), low

* fix(editor): position range slider value label and track via CSS

The label position and filled track were computed in JS from the input's
offsetWidth, and only when the value changed, so they went stale when the
container resized. Drive both from a --range-progress CSS variable, and
drop the UA default inline margin that offset the track from the label.

Opus 5.5 (1M context), low

* feat(editor): compact styles panel

Styles panel buttons are 32px regardless of screen size, rows are closer
together, top-pick swatches are packed tighter, and the panel sizes to its
content (up to the previous fixed width).

Opus 5.5 (1M context), low

* reduce large icon size on 1920px+ screens

* fix color picker border color on mobile
2026-09-24 22:18:52 +02:00
David LuzarandMark Tolmacs 1118751f3e feat(editor): customizable font picker top picks (#12160)
* feat(editor): customizable font picker top picks

Font families can be dragged from the font picker list onto the top-picks
strip to replace a pick, the strip can be reordered by dragging, and
right-clicking it resets to the default picks — same as the color picker
top picks. The drag ghost is only the font's icon (on a strip-button tile).

The color picker's drag & drop is generalized into
components/TopPicksDnD (value-agnostic hook, reorder preview, drop outline,
reset context menu, shared styles), with thin per-picker adapters
(colorTopPicksDnD / fontTopPicksDnD) supplying value equality and the
ghost visual.

Custom picks are kept in `appState.fontTopPicks` (browser-persisted only,
kept on canvas clear); restore drops unknown/internal/fallback families,
dedupes, and caps at the strip's 3 slots.

Claude Opus 5.5 (1M context), reasoning effort: 40

* feat(editor): reset link in top picks tips

The "drag to pin" tip in the font picker and color picker popups now ends
with a plain-text "Reset" link while that picker's top picks are
customized, restoring the defaults without leaving the popup.

Shared as TopPicksTip (tip text styles merged into it). The link never
takes focus on click and hands it back to the picker when activated by
keyboard, since it unmounts on reset; Enter/Space are kept from the
pickers' key handlers.

Claude Opus 5.5 (1M context), reasoning effort: 15

* fix(editor): don't clip or overlap font list item focus/pressed rings

The font list scrolls (clipping outer box-shadows at its edges) and each
item paints over the previous one's bottom edge, so the focus-visible and
:active rings are drawn inset there. Pressing and holding items became
common with dragging fonts onto the top picks.

Claude Opus 5.5 (1M context), reasoning effort: 15

* fix(editor): cancelled top picks drag flying to viewport top-left

The ghost (and its home rect) was built on drag activation, by which time
the source could have been re-rendered away — the font list re-renders
on hover — and a detached element measures as a zero rect. Build and
measure it on pointerdown instead, while the source is mounted.

Claude Opus 5.5 (1M context), reasoning effort: 15

* fix: Always show 3 slots to reorder

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

* fix: Cleanup

Inconsistent state updates. Font picks go through useExcalidrawSetAppState directly, while color picks go through the action's updateData.

Duplicate icons in the strip. Virgil and Excalifont both use FreedrawIcon, so pinning both shows two identical tiles that can only be told apart by their tooltips.

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

* fix: remove useMemo

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-09-24 15:06:17 +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 97c68dd371 refactor(editor): split out duplication logic into App.duplicate.ts (#12125) 2026-09-19 11:53:31 +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 c0ad61c674 feat(editor): rightclick to pan canvas (#12110)
* refactor(editor): move the drag-pan out of App.tsx into App.pan.ts

`handleCanvasPanUsingWheelOrSpaceDrag` — gating, the Linux middle-click
paste guard, the throttled move and the teardown — moves as-is into an
`AppPan` helper (`app.pan`), in the shape of `App.cursor` and
`App.viewport`. The session state it ran on was module-level in App.tsx
(`isHoldingSpace`, `isPanning`, `flushPanMove`), shared by every `App`
instance in the page: with two editors mounted, a wheel-button pan in one
made the other ignore wheel input. It is instance state now — `spaceHeld`,
`active`, the pending move flush and the teardown — behind `start`,
`isActive`, `flushMove`, `end` and the space accessors. Only the pointer
count is injected; `gesture` stays where it is.

`AppWheel` asks `app.pan` directly instead of taking those two callbacks
as dependencies, the wysiwyg's wheel-button pan calls `app.pan.start`,
and `maybeCleanupAfterMissingPointerUp` ends the pan explicitly, which
leaves `lastPointerUp` to the scrollbar drag alone. `savePointer` becomes
public for the teardown. No behavior change.

Claude Fable 5.1, high effort

* feat(editor): pan by dragging with the secondary mouse button

A secondary-button press starts a pan session like the wheel button
does, except that it stays a right-click until the pointer travels past
the drag threshold: nothing moves and the cursor stays put before that;
past it the canvas follows the pointer (from that point, the threshold
distance is not caught up) and no menu opens. Released before the
threshold, the session opens the context menu itself at the release
point, through the same `openContextMenu` the `contextmenu` handler now
delegates to.

That handler ignores the platform's `contextmenu` event while a
secondary-button session is active — macOS and Linux fire it on
mousedown, before a drag can be told from a click — and once after the
session ends if it has not fired yet, which is Windows firing it on
mouseup. Touch long-press, pen barrel taps and keyboard-triggered menus
never go through a session, so they open as before. On macOS and Linux
the menu now opens on release rather than on press.

View mode already let any button pan; a right-click there opens the
view-mode menu on release the same way. With interaction disabled the
drag still pans (when navigation is enabled) and no menu opens.

Tests: the threshold, the menu on release, both platform orders of the
native event, no menu after a drag, element selection under the pointer,
and the non-interactive editor.

Claude Fable 5.1, high effort

* fix(editor): let the contextmenu after mouseup open the menu for a right-click, as before

The secondary-button session opened the menu on release everywhere. On
Windows the platform's `contextmenu` fires after mouseup, by which time
our menu was rendered under the pointer; the event then targeted the
popover instead of the canvas, the canvas handler that prevented the
native menu never ran, and the native menu opened on top of ours.

The session now opens the menu on release only where the platform's
`contextmenu` already came with the press (macOS, Linux) and was
swallowed because a drag could not be told from a click yet. Where it
follows the release, it opens the menu itself, exactly as before this
branch, and lands on the canvas as there is nothing under the pointer.
After a drag that event is swallowed once, as it was.

Tests: after mouseup, nothing is open at release and the platform's event
opens the menu; the mousedown-order and drag cases are unchanged.

Claude Fable 5.1, high effort

* reintroduce: ctrl+wheel should always zoom for both input devices

* fix(editor): lower right-button pan threshold to 5px

* fix(editor): broadcast the final pointer position after panning

* fix(editor): suppress cursor broadcasts while panning
2026-09-16 19:50:39 +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 Luzar 4e758db17e feat(editor): wheel-button zoom and "zoom with scroll wheel" preference (#12099)
* refactor(editor): move wheel handling out of App.tsx into App.wheel.ts

The wheel handler (pan, ctrl/cmd zoom, shift horizontal pan) and the
non-interactive browser-zoom guard move as-is into a new `AppWheel`
helper (`app.wheel`), in the same shape as `App.cursor` / `App.viewport`.
The zoom math becomes a private `zoomBy(deltaY)` so the upcoming wheel
features (wheel-button zoom, zoom-with-scroll-wheel preference) only add
branches to the dispatch instead of another copy of it.

`isPanning` is module state in App.tsx, so it is handed in as a
dependency the way `AppViewport` gets `isGestureActive`; the debounced
`shouldCacheIgnoreZoom` reset is shared with the touch pinch handler and
becomes public. No behavior change.

Claude Fable 5.1, high effort

* feat(editor): zoom by scrolling with the wheel button held down

Scrolling while the wheel (middle) mouse button is held zooms the canvas
around the pointer, exactly like ctrl/cmd+wheel. The button is what
starts a drag-pan and the wheel sits under the same finger, so a pan can
be zoomed one-handed without reaching for a modifier. It wins over the
modifiers (shift included) and over the drag-pan's own wheel gate, which
until now swallowed all wheel input mid-pan. It is read off
`event.buttons`, so no extra state is tracked.

Zooming mid-pan exposed three ways the point grabbed by the pan could
drift from under the cursor, compounding with every tick while the
pointer moves between zooms:

- The drag-pan wrote its scroll as a plain object computed from
  `this.state`. Under React 19 a wheel zoom is flushed asynchronously,
  and the pan's animation frame runs before that flush, so the pan
  overwrote the zoom's anchoring scroll with a pre-zoom value — the zoom
  then happened around the viewport origin instead of the cursor. The pan
  is now a state updater.
- A pointer move still waiting for its frame landed after the zoom, which
  had anchored on a viewport that didn't include it. The wheel handler
  flushes the pending move first.
- The zoom updater read `viewport.lastPosition` when React evaluated it,
  by which time the pointer had moved on; it also started from
  `app.state.zoom`, so ticks queued before a flush collapsed into one.
  Both are now taken at wheel time / from the updater's own state.

Tests: plain wheel pans, shift pans horizontally and ctrl/cmd zooms
(pinning the baseline); with the button held, scrolling zooms in and out
regardless of shift; during a wheel-button drag-pan, plain wheel input is
still swallowed while wheel-button scrolling zooms, and panning is back
after release. Two regression tests pin the grabbed point under the
cursor: one batches the zoom with a pan landing in the same React flush,
one holds the pan's frame back until after the wheel fires (through a
file-level `withBatchedUpdatesThrottled` mock, since the test setup makes
the throttle synchronous). Both fail on the previous code by 11.8 and
2.7 scene units respectively.

Claude Fable 5.1, high effort

* feat(editor): "zoom with scroll wheel" preference

Adds `appState.zoomWithScrollWheel` (default `false`, persisted to
browser storage like the other preferences), for mouse users who would
rather scroll to zoom: a plain wheel zooms around the pointer, and
ctrl/cmd+wheel pans vertically instead — the two roles swap, the way
tldraw's wheel-behavior preference does it. Shift+wheel keeps panning
horizontally, and the wheel-button zoom keeps winning over everything.
One consequence to be aware of: a trackpad pinch arrives as ctrl+wheel,
so with the preference on it pans.

The toggle lives in the main menu's preferences submenu ("Zoom with
scroll wheel", right under "Select on"), exposed as
`MainMenu.DefaultItems.Preferences.ToggleZoomWithScrollWheel` and backed
by the `zoomWithScrollWheel` action, allowed in view mode since it only
concerns navigation.

Tests: the preference is off by default and its action toggles it; with
it on, plain wheel zooms while ctrl and cmd wheel pan vertically, shift
still pans horizontally and the wheel button still zooms. Snapshots pick
up the new default.

Claude Fable 5.1, high effort

* perf(editor): keep the zoom bitmap cache across pan frames during a wheel zoom

`viewport.translate` cleared `shouldCacheIgnoreZoom` on every call. Wheel
zoom sets the flag so elements draw from zoom-scaled cached bitmaps, but
a drag-pan frame landing between two ticks cleared it again, and the
static renderer then re-rasterized every element at a zoom the next tick
was about to change. Wheel-button zoom-while-panning interleaves the two
by design (the old `isPanning` gate made the combination impossible with
a mouse); trackpad pan-plus-pinch has always alternated plain and ctrl
wheel events the same way.

Measured with 1,200 rough shapes on screen, a 12-tick zoom with a small
pointer move on every frame: 10,434 / 8,774 bitmaps regenerated in two
runs, longest frame 242 / 283 ms, gesture 2.9 / 2.3 s. With the pointer
still: 0 bitmaps, 9 ms, 0.39 s.

The reset now happens only when a gesture interrupts an animated
`setViewport`, whose frames set the flag and whose completion handler
would have cleared it. Everywhere else the flag is left to the zoom paths
and their 300 ms debounce. After the change the moving-pointer run
regenerates 0 bitmaps, longest frame 25–33 ms, gesture 0.7–0.8 s. A
plain wheel pan within 300 ms of a zoom now draws from scaled bitmaps
until the debounce fires instead of re-rasterizing on its first frame.

Tests: pan frames between wheel-button zoom ticks keep the flag until the
gesture is idle (fails on the previous code); the interrupted-animation
test also pins the reset, with a 60 s animation and a polling assertion
so a saturated machine cannot finish the animation before the check.

Claude Fable 5.1, high effort

* fix(editor): handle wheel input over a frame label once

The frame label had a React `onWheel` handler while also sitting inside
the editor container, whose native wheel listener already accepts
`.frame-name` targets. Both received the same event, so every wheel tick
over a label panned or zoomed twice (measured: −140 px of scroll for a
tick that moves the canvas −70 px elsewhere). React registers `wheel`
as passive, so the React path could not even preventDefault. Predates
this branch; with the zoom-with-scroll-wheel preference it became a
two-step zoom per tick over labels.

Drop the prop. With no React path left, the wheel handler's event type
narrows to the native `WheelEvent`.

Test: a wheel event on a frame label pans one step; it fails on the
previous code by exactly one extra step.

Claude Fable 5.1, high effort

* refactor(editor): model the wheel preference as an input device

    `appState.zoomWithScrollWheel` becomes `appState.inputDevice:
    "auto" | "mouse" | "trackpad"`.

    Claude Fable 5.1, high effort

* fix(editor): decide whether a translate zoomed against the state it applies to

`viewport.translate` captured `prevZoom` from `app.state` before queuing
its update, then a second updater compared it with the zoom it found in
`prevState` to tell a zoom apart from a pan — a zoom drops the rubberband
overscroll to 0, a pan keeps it. With a zoom queued in the same React
flush, `app.state` still holds the pre-zoom value, so a pan applied on
top of that zoom read as a zoom of its own and hard-clamped the
overscroll away in one frame instead of easing it back. Two wheel events
in one flush could already do this; the wheel-button zoom makes it
routine, as the handler applies the pending pan move on every tick.

The two `setState` calls become one updater: the update is applied to
`prevState`, the zoom comparison is between that state and the result,
and the constrained viewport is merged into it. No captured state, no
ordering to get wrong.

Test: rubberbanded past the box edge, a ctrl+wheel zoom tick and a wheel
pan batched into one flush keep the overscroll; on the previous code it
lands exactly on the edge.

Claude Fable 5.1, high effort

* fix(editor): pan sideways on a horizontal-only wheel; no-op zoom ticks at the limit

In mouse mode a wheel event with only a horizontal delta — a tilt wheel,
a sideways two-finger scroll — took the zoom branch with `deltaY` 0: no
viewport change, but every such event flipped the bitmap-cache flag,
cancelled collab follow and re-armed the cache debounce, and the sideways
scroll itself went nowhere. A wheel with no vertical delta never zooms
now; it falls through to the pan, which moves the canvas by `deltaX`. A
wheel with no delta at all is ignored outright.

The zoom updater also returns early when the tick lands on the zoom it
started from — at MIN or MAX zoom — instead of setting the cache flag and
redrawing the scene on every tick. This predates the branch. To make
that a real no-op, `viewport.translate` treats a `null` update as nothing
to do rather than re-constraining and re-setting the whole state.

Tests: in mouse mode a horizontal-only wheel pans sideways and leaves the
cache flag alone; a zoom-out tick at MIN_ZOOM changes nothing. Both fail
on the previous code.

Claude Fable 5.1, high effort
2026-09-14 16:17:41 +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
Excalidraw Botanddwelle 0361bdd9cb chore(editor): Update translations from Crowdin (#11942)
* New translations en.json (Italian)

[ci skip]

* New translations en.json (Persian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* Auto commit: Calculate translation coverage

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-09-07 22:32:05 +02:00
David Luzar 2b1c2a9fbf fix(editor): dismiss dropdown menus on outside clicks (#12053)
fix: dismiss dropdown menus on outside clicks
2026-09-07 17:28:20 +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
zsvicziananddwelle e1bb9ff8f8 feat(packages/excalidraw): support rendering into another document (#11974)
* feat: support rendering into another document

* add missed places

* tweak jsdoc

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-08-26 15:33:04 +02:00
David Luzar 4a6f4e7a32 feat(app): d2c streaming (#11960)
* support d2c streaming

* render status spinner while streaming

* enable analytics for ai
2026-08-25 16:08:37 +02:00
Excalidraw Botanddwelle e160ff7ba0 chore(editor): Update translations from Crowdin (#11815)
* New translations en.json (Romanian)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Arabic)

[ci skip]

* New translations en.json (Bulgarian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Kurdish)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Punjabi)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Slovak)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Chinese Traditional)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Galician)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Persian)

[ci skip]

* New translations en.json (Khmer)

[ci skip]

* New translations en.json (Tamil)

[ci skip]

* New translations en.json (Bengali)

[ci skip]

* New translations en.json (Marathi)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Norwegian Nynorsk)

[ci skip]

* New translations en.json (Kazakh)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Azerbaijani)

[ci skip]

* New translations en.json (Hindi)

[ci skip]

* New translations en.json (Burmese)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Sinhala)

[ci skip]

* New translations en.json (Uzbek)

[ci skip]

* New translations en.json (Norwegian Bokmal)

[ci skip]

* New translations en.json (Occitan)

[ci skip]

* New translations en.json (German, Switzerland)

[ci skip]

* New translations en.json (Bengali, India)

[ci skip]

* New translations en.json (Kabyle)

[ci skip]

* New translations en.json (Karakalpak)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Arabic)

[ci skip]

* New translations en.json (Bulgarian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Kurdish)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Punjabi)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Slovak)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Chinese Traditional)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Galician)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Persian)

[ci skip]

* New translations en.json (Khmer)

[ci skip]

* New translations en.json (Tamil)

[ci skip]

* New translations en.json (Bengali)

[ci skip]

* New translations en.json (Marathi)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Norwegian Nynorsk)

[ci skip]

* New translations en.json (Kazakh)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Azerbaijani)

[ci skip]

* New translations en.json (Hindi)

[ci skip]

* New translations en.json (Burmese)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Sinhala)

[ci skip]

* New translations en.json (Uzbek)

[ci skip]

* New translations en.json (Norwegian Bokmal)

[ci skip]

* New translations en.json (Occitan)

[ci skip]

* New translations en.json (German, Switzerland)

[ci skip]

* New translations en.json (Bengali, India)

[ci skip]

* New translations en.json (Kabyle)

[ci skip]

* New translations en.json (Karakalpak)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Arabic)

[ci skip]

* New translations en.json (Bulgarian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Kurdish)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Punjabi)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Slovak)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Chinese Traditional)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Galician)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Persian)

[ci skip]

* New translations en.json (Khmer)

[ci skip]

* New translations en.json (Tamil)

[ci skip]

* New translations en.json (Bengali)

[ci skip]

* New translations en.json (Marathi)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Norwegian Nynorsk)

[ci skip]

* New translations en.json (Kazakh)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Azerbaijani)

[ci skip]

* New translations en.json (Hindi)

[ci skip]

* New translations en.json (Burmese)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Sinhala)

[ci skip]

* New translations en.json (Uzbek)

[ci skip]

* New translations en.json (Norwegian Bokmal)

[ci skip]

* New translations en.json (Occitan)

[ci skip]

* New translations en.json (German, Switzerland)

[ci skip]

* New translations en.json (Bengali, India)

[ci skip]

* New translations en.json (Kabyle)

[ci skip]

* New translations en.json (Karakalpak)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Chinese Traditional)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* New translations en.json (French)

[ci skip]

* New translations en.json (Spanish)

[ci skip]

* New translations en.json (Arabic)

[ci skip]

* New translations en.json (Bulgarian)

[ci skip]

* New translations en.json (Catalan)

[ci skip]

* New translations en.json (Czech)

[ci skip]

* New translations en.json (Danish)

[ci skip]

* New translations en.json (German)

[ci skip]

* New translations en.json (Greek)

[ci skip]

* New translations en.json (Basque)

[ci skip]

* New translations en.json (Finnish)

[ci skip]

* New translations en.json (Hebrew)

[ci skip]

* New translations en.json (Hungarian)

[ci skip]

* New translations en.json (Italian)

[ci skip]

* New translations en.json (Japanese)

[ci skip]

* New translations en.json (Korean)

[ci skip]

* New translations en.json (Kurdish)

[ci skip]

* New translations en.json (Lithuanian)

[ci skip]

* New translations en.json (Dutch)

[ci skip]

* New translations en.json (Punjabi)

[ci skip]

* New translations en.json (Polish)

[ci skip]

* New translations en.json (Portuguese)

[ci skip]

* New translations en.json (Russian)

[ci skip]

* New translations en.json (Slovak)

[ci skip]

* New translations en.json (Slovenian)

[ci skip]

* New translations en.json (Swedish)

[ci skip]

* New translations en.json (Turkish)

[ci skip]

* New translations en.json (Ukrainian)

[ci skip]

* New translations en.json (Chinese Simplified)

[ci skip]

* New translations en.json (Chinese Traditional)

[ci skip]

* New translations en.json (Vietnamese)

[ci skip]

* New translations en.json (Galician)

[ci skip]

* New translations en.json (Portuguese, Brazilian)

[ci skip]

* New translations en.json (Indonesian)

[ci skip]

* New translations en.json (Persian)

[ci skip]

* New translations en.json (Khmer)

[ci skip]

* New translations en.json (Tamil)

[ci skip]

* New translations en.json (Bengali)

[ci skip]

* New translations en.json (Marathi)

[ci skip]

* New translations en.json (Thai)

[ci skip]

* New translations en.json (Norwegian Nynorsk)

[ci skip]

* New translations en.json (Kazakh)

[ci skip]

* New translations en.json (Latvian)

[ci skip]

* New translations en.json (Azerbaijani)

[ci skip]

* New translations en.json (Hindi)

[ci skip]

* New translations en.json (Burmese)

[ci skip]

* New translations en.json (Chinese Traditional, Hong Kong)

[ci skip]

* New translations en.json (Sinhala)

[ci skip]

* New translations en.json (Uzbek)

[ci skip]

* New translations en.json (Norwegian Bokmal)

[ci skip]

* New translations en.json (Occitan)

[ci skip]

* New translations en.json (German, Switzerland)

[ci skip]

* New translations en.json (Bengali, India)

[ci skip]

* New translations en.json (Kabyle)

[ci skip]

* New translations en.json (Karakalpak)

[ci skip]

* New translations en.json (Romanian)

[ci skip]

* Auto commit: Calculate translation coverage

---------

Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
2026-08-16 17:30:01 +02:00
Vishnu RkandVishRk 884225b1c7 fix(app): localize hardcoded "Sign up"/"Sign in" menu labels (#11893)
fix(localization): update signup and signin labels for localization

Co-authored-by: VishRk <VishRk@users.noreply.github.com>
2026-08-16 13:20:15 +00:00
David Luzar abeeaeba21 feat(editor): customizing color top picks (#11872) 2026-08-11 15:59:35 +02:00
JayeshandMark Tolmacs c5a50d223f fix(editor): respect boxSelectionMode ('contain' vs 'overlap') in lasso tool (#11862)
---------

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
Co-authored-by: Mark Tolmacs <mark@lazycat.hu>
2026-08-10 13:09:43 +02:00
David Luzarandrafa cf212b2f33 feat(editor): eyedropper fixes and improvements (#11859)
Co-authored-by: rafa <rafaondjango@gmail.com>
2026-08-08 23:17:26 +02:00
David Luzar 4872083c04 feat(editor): bucketfill cursor + eyedropper support (#11849) 2026-08-07 14:07:53 +02:00
David Luzar ea74787447 fix(app): remove ViewportStatusFrame debug (#11848) 2026-08-07 12:53:21 +02:00
David Luzar 219571a718 fix(editor): viewportportStatusFrame UI fixes (#11841) 2026-08-06 22:01:48 +02:00
337 changed files with 39403 additions and 8776 deletions
+4
View File
@@ -0,0 +1,4 @@
# Guidelines
- For new DOM/browser API usage, use `app.ownerDocument` and `app.ownerWindow` instead of globals; without `app`, derive them from the mounted node's `ownerDocument` and its `defaultView`.
- When overriding properties of an existing type, prefer `Merge<Base, Overrides>` from `@excalidraw/common/utility-types` over `Omit<Base, keyof Overrides> & Overrides`.
@@ -274,6 +274,35 @@ convertToExcalidrawElements([
![image](https://github.com/excalidraw/excalidraw/assets/11256141/f8123cd1-c9aa-452d-b96b-05c846c5030d)
### Sticky Notes
A sticky note is an always-filled note whose label auto-fits: the font shrinks from the label's `fontSize` (the note's font ceiling) down to a minimum, and only then does the note grow in height. Only `type`, `x` and `y` are required; `width`/`height` default to a 250×250 square and `label` is optional. The note's `strokeColor` is its ink — its text and creation-date footer are always one color; a label that sets its own `strokeColor` gives it to the note. A footer band below the label shows the note's creation date (`created`); pass `created: null` for a note without one (the band stays reserved, but empty).
```js
convertToExcalidrawElements([
{
type: "stickynote",
x: 100,
y: 100,
label: {
text: "Remember to ship it",
fontSize: 28,
},
},
{
type: "stickynote",
x: 400,
y: 100,
width: 200,
height: 200,
backgroundColor: "#fcc2d7",
strokeColor: "#c2255c",
},
]);
```
Notes keep their invariants regardless of the properties you pass: the background is never transparent (it falls back to the default yellow), the fill is solid, and the size is at least 75×75. The height you pass is kept as the note's `baseHeight`; if a label needs more room at the minimum font size, the created note is taller.
### Labelled Arrows
Similar to Text Containers, you can create labelled arrows as well.
+12
View File
@@ -62,6 +62,18 @@ When saving an Excalidraw scene locally to a file, the JSON file (`.excalidraw`)
}
```
### Element creation time
Every normalized element has a `created: number | null` field. A number is the client's wall-clock time in epoch milliseconds when this element instance was created. `null` means the creation time is unknown; restoring an older file does not substitute its load time or last-update time.
| Operation | `created` |
| --- | --- |
| Construct a new element | Current time, unless explicitly supplied (including `null`) |
| Duplicate, paste, or insert from a library | New time for the new instance |
| Convert element skeletons with ID regeneration | New time for each resulting instance |
| Restore/open/import an existing scene | Preserve the carried value; missing values become `null` |
| Edit, change type while retaining the ID, capture, undo, or redo | Preserve the value |
## Excalidraw clipboard format
When copying selected excalidraw elements to clipboard, the JSON schema is similar to `.excalidraw` format, except it differs in attributes.
@@ -9,8 +9,6 @@ In case you want to pick up something from the roadmap, comment on that issue an
## Setup
### Option 1 - Manual
1. Fork and clone the repo
1. Run `yarn` to install dependencies
1. Create a branch for your PR with `git checkout -b your-branch-name`
@@ -23,15 +21,6 @@ In case you want to pick up something from the roadmap, comment on that issue an
> git branch --set-upstream-to=upstream/master master
> ```
### Option 2 - CodeSandbox
1. Go to https://codesandbox.io/p/github/excalidraw/excalidraw
1. Connect your GitHub account
1. Go to Git tab on left side
1. Tap on `Fork Sandbox`
1. Write your code
1. Commit and PR automatically
## Pull Request Guidelines
Don't worry if you get any of the below wrong, or if you don't know how. We'll gladly help out.
@@ -1,11 +1,5 @@
# Development
## Code Sandbox
- Go to https://codesandbox.io/p/github/excalidraw/excalidraw
- You may need to sign in with GitHub and reload the page
- You can start coding instantly, and even send PRs from there!
## Local Installation
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
@@ -80,9 +80,7 @@ export default function ExampleApp({
excalidrawLib,
}: AppProps) {
const {
exportToCanvas,
exportToSvg,
exportToBlob,
exportScene,
exportToClipboard,
useHandleLibrary,
MIME_TYPES,
@@ -115,6 +113,10 @@ export default function ExampleApp({
const [canvasUrl, setCanvasUrl] = useState<string>("");
const [exportWithDarkMode, setExportWithDarkMode] = useState(false);
const [exportEmbedScene, setExportEmbedScene] = useState(false);
const exportConfig = {
theme: exportWithDarkMode ? "dark" : "light",
padding: 10,
} as const;
const [theme, setTheme] = useState<Theme>("light");
const [disableImageTool, setDisableImageTool] = useState(false);
const [isCollaborating, setIsCollaborating] = useState(false);
@@ -387,10 +389,12 @@ export default function ExampleApp({
return false;
}
await exportToClipboard({
elements: excalidrawAPI.getSceneElements(),
appState: excalidrawAPI.getAppState(),
files: excalidrawAPI.getFiles(),
type,
data: {
elements: excalidrawAPI.getSceneElements(),
appState: excalidrawAPI.getAppState(),
files: excalidrawAPI.getFiles(),
},
});
window.alert(`Copied to clipboard as ${type} successfully`);
};
@@ -888,16 +892,14 @@ export default function ExampleApp({
if (!excalidrawAPI) {
return;
}
const svg = await exportToSvg({
elements: excalidrawAPI?.getSceneElements(),
appState: {
...initialData.appState,
exportWithDarkMode,
exportEmbedScene,
width: 300,
height: 100,
const svg = await exportScene({
type: "svg",
data: {
elements: excalidrawAPI.getSceneElements(),
appState: initialData.appState,
files: excalidrawAPI.getFiles(),
},
files: excalidrawAPI?.getFiles(),
config: { ...exportConfig, embedScene: exportEmbedScene },
});
appRef.current.querySelector(".export-svg").innerHTML =
svg.outerHTML;
@@ -912,15 +914,14 @@ export default function ExampleApp({
if (!excalidrawAPI) {
return;
}
const blob = await exportToBlob({
elements: excalidrawAPI?.getSceneElements(),
mimeType: "image/png",
appState: {
...initialData.appState,
exportEmbedScene,
exportWithDarkMode,
const blob = await exportScene({
type: "png",
data: {
elements: excalidrawAPI.getSceneElements(),
appState: initialData.appState,
files: excalidrawAPI.getFiles(),
},
files: excalidrawAPI?.getFiles(),
config: { ...exportConfig, embedScene: exportEmbedScene },
});
setBlobUrl(window.URL.createObjectURL(blob));
}}
@@ -935,13 +936,14 @@ export default function ExampleApp({
if (!excalidrawAPI) {
return;
}
const canvas = await exportToCanvas({
elements: excalidrawAPI.getSceneElements(),
appState: {
...initialData.appState,
exportWithDarkMode,
const canvas = await exportScene({
type: "canvas",
data: {
elements: excalidrawAPI.getSceneElements(),
appState: initialData.appState,
files: excalidrawAPI.getFiles(),
},
files: excalidrawAPI.getFiles(),
config: exportConfig,
});
const ctx = canvas.getContext("2d")!;
ctx.font = "30px Excalifont";
@@ -956,13 +958,14 @@ export default function ExampleApp({
if (!excalidrawAPI) {
return;
}
const canvas = await exportToCanvas({
elements: excalidrawAPI.getSceneElements(),
appState: {
...initialData.appState,
exportWithDarkMode,
const canvas = await exportScene({
type: "canvas",
data: {
elements: excalidrawAPI.getSceneElements(),
appState: initialData.appState,
files: excalidrawAPI.getFiles(),
},
files: excalidrawAPI.getFiles(),
config: exportConfig,
});
const ctx = canvas.getContext("2d")!;
ctx.font = "30px Excalifont";
+65 -23
View File
@@ -1,15 +1,17 @@
import {
DiagramToCodePlugin,
exportToBlob,
exportScene,
getNonDeletedElements,
getTextFromElements,
MIME_TYPES,
parseSSEStream,
TTDDialog,
TTDStreamFetch,
THEME,
} from "@excalidraw/excalidraw";
import { getDataURL } from "@excalidraw/excalidraw/data/blob";
import { safelyParseJSON } from "@excalidraw/common";
import type { StreamChunk } from "@excalidraw/excalidraw";
import type { ExcalidrawImperativeAPI } from "@excalidraw/excalidraw/types";
import { TTDIndexedDBAdapter } from "../data/TTDStorage";
@@ -22,7 +24,7 @@ export const AIComponents = ({
return (
<>
<DiagramToCodePlugin
generate={async ({ frame, children }) => {
generate={async ({ frame, children, onPartial }) => {
const appState = excalidrawAPI.getAppState();
// SAFETY: This should never happen, but log it just in case
@@ -32,16 +34,17 @@ export const AIComponents = ({
);
}
const blob = await exportToBlob({
elements: getNonDeletedElements(children),
appState: {
...appState,
exportBackground: true,
viewBackgroundColor: appState.viewBackgroundColor,
const blob = await exportScene({
type: "jpeg",
data: {
elements: getNonDeletedElements(children),
appState,
files: excalidrawAPI.getFiles(),
},
config: {
exportingFrame: frame,
theme: appState.exportWithDarkMode ? THEME.DARK : THEME.LIGHT,
},
exportingFrame: frame,
files: excalidrawAPI.getFiles(),
mimeType: MIME_TYPES.jpg,
});
const dataURL = await getDataURL(blob);
@@ -51,11 +54,11 @@ export const AIComponents = ({
const response = await fetch(
`${
import.meta.env.VITE_APP_AI_BACKEND
}/v1/ai/diagram-to-code/generate`,
}/v1/ai/diagram-to-code/generate-streaming`,
{
method: "POST",
headers: {
Accept: "application/json",
Accept: "text/event-stream",
"Content-Type": "application/json",
},
body: JSON.stringify({
@@ -94,18 +97,57 @@ export const AIComponents = ({
throw new Error(errorJSON.message || text);
}
try {
const { html } = await response.json();
const reader = response.body?.getReader();
if (!html) {
throw new Error("Generation failed (invalid response)");
}
return {
html,
};
} catch (error: any) {
if (!reader) {
throw new Error("Generation failed (invalid response)");
}
let html = "";
let streamError: Error | null = null;
for await (const data of parseSSEStream(reader)) {
if (data === "[DONE]") {
break;
}
const chunk = safelyParseJSON(data) as StreamChunk | null;
if (!chunk) {
continue;
}
switch (chunk.type) {
case "content": {
if (chunk.delta) {
html += chunk.delta;
onPartial?.(html);
}
break;
}
case "error": {
streamError = new Error(
chunk.error.message || "Generation failed",
);
break;
}
case "done": {
break;
}
}
}
if (streamError) {
throw streamError;
}
if (!html.trim()) {
throw new Error("Generation failed (invalid response)");
}
return {
html,
};
}}
/>
+3 -1
View File
@@ -3,6 +3,7 @@ import {
ExcalLogo,
eyeIcon,
} from "@excalidraw/excalidraw/components/icons";
import { useI18n } from "@excalidraw/excalidraw/i18n";
import { MainMenu } from "@excalidraw/excalidraw/index";
import React from "react";
@@ -22,6 +23,7 @@ export const AppMainMenu: React.FC<{
theme: Theme | "system";
refresh: () => void;
}> = React.memo((props) => {
const { t } = useI18n();
return (
<MainMenu>
<MainMenu.DefaultItems.LoadScene />
@@ -56,7 +58,7 @@ export const AppMainMenu: React.FC<{
}?utm_source=signin&utm_medium=app&utm_content=hamburger`}
className="highlighted"
>
{isExcalidrawPlusSignedUser ? "Sign in" : "Sign up"}
{isExcalidrawPlusSignedUser ? t("labels.signIn") : t("labels.signUp")}
</MainMenu.ItemLink>
{isDevEnv() && (
<MainMenu.Item
@@ -72,7 +72,7 @@ export const AppWelcomeScreen: React.FC<{
shortcut={null}
icon={loginIcon}
>
Sign up
{t("labels.signUp")}
</WelcomeScreen.Center.MenuItemLink>
)}
</WelcomeScreen.Center.Menu>
@@ -1,8 +1,12 @@
import { PlusPromoIcon } from "@excalidraw/excalidraw/components/icons";
import { useI18n } from "@excalidraw/excalidraw/i18n";
export const ExcalidrawPlusPromoBanner = ({
isSignedIn,
}: {
isSignedIn: boolean;
}) => {
const { t } = useI18n();
return (
<a
href={
@@ -16,7 +20,17 @@ export const ExcalidrawPlusPromoBanner = ({
rel="noopener"
className="plus-banner"
>
Excalidraw+
<span className="plus-banner__icon">{PlusPromoIcon}</span>
<span className="plus-banner__text">
<span className="plus-banner__title">
{isSignedIn ? t("labels.signIn") : t("labels.tryExcalidrawPlus")}
</span>
{!isSignedIn && (
<span className="plus-banner__subtitle">
{t("labels.plusFreeTrial")}
</span>
)}
</span>
</a>
);
};
+53 -25
View File
@@ -87,44 +87,72 @@
}
.plus-banner {
display: flex;
justify-content: center;
cursor: pointer;
align-items: center;
border: 1px solid var(--color-primary);
padding: 0.5rem 0.875rem;
border-radius: var(--border-radius-lg);
background-color: var(--island-bg-color);
text-decoration: none !important;
--plus-banner-bg: #f0efff;
--plus-banner-bg-hover: var(--color-primary-light);
--plus-banner-border: var(--color-primary-light-darker);
--plus-banner-subtitle: #8b88e0;
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
padding: 0 0.875rem 0 0.625rem;
border: 1px solid var(--plus-banner-border);
border-radius: var(--border-radius-lg);
background-color: var(--plus-banner-bg);
color: var(--color-primary) !important;
text-decoration: none !important;
font-family: var(--ui-font);
font-size: 0.8333rem;
box-sizing: border-box;
height: var(--lg-button-size);
border: none;
box-shadow: 0 0 0 1px var(--color-surface-lowest);
background-color: var(--color-surface-low);
color: var(--button-color, var(--color-on-surface)) !important;
&:active {
box-shadow: 0 0 0 1px var(--color-brand-active);
}
white-space: nowrap;
transition: background-color 0.15s ease, border-color 0.15s ease;
&:hover {
background-color: var(--color-primary);
color: white !important;
background-color: var(--plus-banner-bg-hover);
border-color: var(--plus-banner-bg-hover);
}
&:active {
background-color: var(--color-primary-darker);
border-color: var(--color-brand-active);
}
&__icon {
display: flex;
flex-shrink: 0;
svg {
width: 1.25rem;
height: 1.25rem;
stroke-width: 1.75;
}
g {
stroke-width: inherit;
}
}
&__text {
display: flex;
flex-direction: column;
line-height: 1.15;
}
&__title {
font-size: 0.875rem;
font-weight: 600;
}
&__subtitle {
font-size: 0.75rem;
color: var(--plus-banner-subtitle);
}
}
.theme--dark {
.plus-banner {
&:hover {
color: black !important;
}
--plus-banner-bg: #2b2a40;
--plus-banner-border: #4f4d6f;
--plus-banner-subtitle: #8f8cc4;
}
}
+19
View File
@@ -1,6 +1,7 @@
import {
applyDarkModeFilter,
COLOR_PALETTE,
removeDarkModeFilter,
rgbToHex,
} from "@excalidraw/common";
@@ -215,6 +216,24 @@ describe("applyDarkModeFilter", () => {
});
});
describe("removeDarkModeFilter", () => {
it("restores black and white", () => {
expect(removeDarkModeFilter("#ededed")).toBe("#000000");
expect(removeDarkModeFilter("#121212")).toBe("#ffffff");
});
it.each([
COLOR_PALETTE.black,
COLOR_PALETTE.white,
COLOR_PALETTE.red[4],
COLOR_PALETTE.green[4],
COLOR_PALETTE.blue[4],
])("preserves the rendered dark-mode color for %s", (color) => {
const filtered = applyDarkModeFilter(color);
expect(applyDarkModeFilter(removeDarkModeFilter(filtered))).toBe(filtered);
});
});
describe("rgbToHex", () => {
describe("basic RGB conversion", () => {
it("converts black (0,0,0)", () => {
+82 -13
View File
@@ -13,6 +13,9 @@ import type { Degrees } from "@excalidraw/math";
const DARK_MODE_COLORS_CACHE: Map<string, string> | null =
typeof window !== "undefined" ? new Map() : null;
const DARK_MODE_FILTER_INVERT_PERCENT = 93;
const DARK_MODE_FILTER_HUE_ROTATE_DEGREES = 180 as Degrees;
function cssHueRotate(
red: number,
green: number,
@@ -96,12 +99,17 @@ export const applyDarkModeFilter = (color: string, enable = true): string => {
// order of operations matters
// (corresponds to "filter: invert(invertPercent) hue-rotate(hueDegrees)" in css)
const rgb = tc.toRgb();
const inverted = cssInvert(rgb.r, rgb.g, rgb.b, 93);
const inverted = cssInvert(
rgb.r,
rgb.g,
rgb.b,
DARK_MODE_FILTER_INVERT_PERCENT,
);
const rotated = cssHueRotate(
inverted.r,
inverted.g,
inverted.b,
180 as Degrees,
DARK_MODE_FILTER_HUE_ROTATE_DEGREES,
);
const result = rgbToHex(rotated.r, rotated.g, rotated.b, alpha);
@@ -113,6 +121,44 @@ export const applyDarkModeFilter = (color: string, enable = true): string => {
return result;
};
const _reverseDarkModeInvert = (
r: number,
g: number,
b: number,
): { r: number; g: number; b: number } => {
const p = DARK_MODE_FILTER_INVERT_PERCENT / 100;
const denominator = 1 - 2 * p;
const restore = (color: number) =>
Math.round(clamp((color - 255 * p) / denominator, 0, 255));
return {
r: restore(r),
g: restore(g),
b: restore(b),
};
};
export const removeDarkModeFilter = (color: string): string => {
const tc = tinycolor(color);
const alpha = tc.getAlpha();
const rgb = tc.toRgb();
// 180deg hue rotation is its own inverse, so undo it before the inversion.
const rotatedBack = cssHueRotate(
rgb.r,
rgb.g,
rgb.b,
DARK_MODE_FILTER_HUE_ROTATE_DEGREES,
);
const restored = _reverseDarkModeInvert(
rotatedBack.r,
rotatedBack.g,
rotatedBack.b,
);
return rgbToHex(restored.r, restored.g, restored.b, alpha);
};
// ---------------------------------------------------------------------------
// Color palette
// ---------------------------------------------------------------------------
@@ -184,6 +230,11 @@ const COMMON_ELEMENT_SHADES = pick(COLOR_PALETTE, [
// quick picks defaults
// -----------------------------------------------------------------------------
/** number of slots in the color-picker top-picks strip — the strip layout is
* sized for exactly this many swatches, and pick customization (replace /
* reorder) preserves it */
export const COLOR_TOP_PICKS_SLOTS = 5;
// ORDER matters for positioning in quick picker
export const DEFAULT_ELEMENT_STROKE_PICKS = [
COLOR_PALETTE.black,
@@ -213,6 +264,22 @@ export const BUCKET_FILL_BACKGROUND_PICKS = [
COLOR_PALETTE.yellow[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX],
] as ColorTuple;
// sticky notes are their own color domain (own defaults, own picks)
export const DEFAULT_STICKY_NOTE_BG = "#ffdf6b";
export const STICKY_NOTE_STROKE_PICKS: ColorTuple =
DEFAULT_ELEMENT_STROKE_PICKS;
// ORDER matters for positioning in quick picker. Classic note colors; the
// first one is `DEFAULT_STICKY_NOTE_BG`. Never transparent.
export const STICKY_NOTE_BACKGROUND_PICKS = [
DEFAULT_STICKY_NOTE_BG,
COLOR_PALETTE.pink[1],
COLOR_PALETTE.green[1],
COLOR_PALETTE.blue[1],
COLOR_PALETTE.orange[1],
] as ColorTuple;
// ORDER matters for positioning in quick picker
export const DEFAULT_CANVAS_BACKGROUND_PICKS = [
COLOR_PALETTE.white,
@@ -251,17 +318,6 @@ export const DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE = {
...COMMON_ELEMENT_SHADES,
} as const;
/**
* The color the bucket fill tool actually fills with: the shared
* `currentItemBackgroundColor`, falling back to green when that is
* transparent (the tool's picker doesn't offer transparent, but the shared
* state can hold it from the generic shape picker).
*/
export const getBucketFillBackgroundColor = (backgroundColor: string) =>
isTransparent(backgroundColor)
? COLOR_PALETTE.green[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX]
: backgroundColor;
// color palette helpers
// -----------------------------------------------------------------------------
@@ -304,6 +360,19 @@ export const rgbToHex = (r: number, g: number, b: number, a?: number) => {
return hex6;
};
/**
* @returns the color with its alpha replaced by `alpha` (as #RRGGBBAA), or the
* input unchanged if it's not a valid color
*/
export const setColorAlpha = (color: string, alpha: number): string => {
const tc = tinycolor(color);
if (!tc.isValid()) {
return color;
}
const { r, g, b } = tc.toRgb();
return rgbToHex(r, g, b, alpha);
};
/**
* @returns #RRGGBB or #RRGGBBAA based on color containing non-opaque alpha,
* null if not valid color
+69 -1
View File
@@ -2,10 +2,16 @@ import type {
ExcalidrawElement,
FontFamilyValues,
} from "@excalidraw/element/types";
import type { AppProps, AppState } from "@excalidraw/excalidraw/types";
import type {
AppProps,
AppState,
NormalizedZoomValue,
} from "@excalidraw/excalidraw/types";
import { COLOR_PALETTE } from "./colors";
export { DEFAULT_STICKY_NOTE_BG } from "./colors";
export const supportsResizeObserver =
typeof window !== "undefined" && "ResizeObserver" in window;
@@ -16,6 +22,12 @@ export const APP_NAME = "Excalidraw";
// don't unintentionally create text elements that are wrapped to a few chars
// (happens a lot with fast clicks with the text tool)
export const TEXT_AUTOWRAP_THRESHOLD = 36; // px
// room left at each side of the visible canvas when a text stops growing at
// its width, or is brought into view once it wraps
export const TEXT_VIEWPORT_PADDING = 20; // px
// the widest a typed or pasted text gets before it wraps (in scene units, so
// at any zoom), however wide the view
export const TEXT_MAX_WRAP_WIDTH = 800; // px
export const DRAGGING_THRESHOLD = 10; // px
export const MINIMUM_ARROW_SIZE = 20; // px
export const LINE_CONFIRM_THRESHOLD = 8; // px
@@ -69,6 +81,7 @@ export enum EVENT {
POINTER_MOVE = "pointermove",
POINTER_DOWN = "pointerdown",
POINTER_UP = "pointerup",
POINTER_CANCEL = "pointercancel",
STATE_CHANGE = "statechange",
WHEEL = "wheel",
TOUCH_START = "touchstart",
@@ -211,7 +224,56 @@ export const FRAME_STYLE = {
export const MIN_FONT_SIZE = 1;
export const DEFAULT_FONT_SIZE = 20;
export const STICKY_NOTE_MIN_FONT_SIZE = 16;
export const STICKY_NOTE_MAX_FONT_SIZE = 512;
export const STICKY_NOTE_FALLBACK_FONT_SIZE = 28;
export const STICKY_NOTE_FONT_STEP = 2;
export const STICKY_NOTE_PADDING = 16;
/**
* The creation-date footer: a 20px text row under the label body plus a 12px
* gap above it, inside the note's bottom padding. Reserved for every note —
* also when `created` is unknown — so geometry never depends on data
* availability. The label is chosen by width bucket, never measured, so
* painting stays measurement-free (the server has no text measurer):
* `minBodyWidthForYear` is the worst case ("30 May 2026") in the system sans
* stack at 12px, with margin for wider fallbacks such as DejaVu Sans.
*/
/**
* The creation-date footer of a sticky note. The label body ends `height`
* above the note's bottom padding, and the date's baseline sits
* `baselineFromBottom` above the note's bottom edge — so the 12px glyphs
* (~9px above the baseline, ~3px below) end up roughly 11px from the edge
* with a ~13px gap to the label body above them.
*/
export const STICKY_NOTE_FOOTER = {
height: 20,
fontSize: 12,
fontFamily: "Helvetica, Arial, sans-serif",
baselineFromBottom: 14,
opacity: 1,
minBodyWidthForYear: 80,
} as const;
/**
* outer height → label body height: top + bottom padding + footer. The body
* is what the label is fitted into; a middle-aligned label is still centered
* in the whole padded note when it fits (see `computeBoundTextPosition`).
*/
export const STICKY_NOTE_BODY_INSET_Y =
STICKY_NOTE_PADDING * 2 + STICKY_NOTE_FOOTER.height;
export const DEFAULT_STICKY_NOTE_SIZE = 250;
// floor for a finalized note's width and base height; the UI floor is font-aware
// on top of it (see `getStickyNoteMinSize`)
export const STICKY_NOTE_MIN_SIZE = 75;
export const STICKY_NOTE_SHADOW_OFFSET = 3;
export const STICKY_NOTE_SHADOW_OPACITY = 0.16;
export const STICKY_NOTE_EDGE_SHADOW_WIDTH = 0.5;
export const STICKY_NOTE_EDGE_SHADOW_OPACITY = 0.08;
export const DEFAULT_FONT_FAMILY: FontFamilyValues = FONT_FAMILY.Excalifont;
/** number of slots in the font-picker top-picks strip — pick customization
* (replace / reorder) preserves it. Must equal `DEFAULT_FONTS.length` in
* `packages/excalidraw/components/FontPicker/FontPicker.tsx` (enforced by
* `fontTopPicks.test.ts`) */
export const FONT_TOP_PICKS_SLOTS = 3;
export const DEFAULT_TEXT_ALIGN = "left";
export const DEFAULT_VERTICAL_ALIGN = "top";
export const DEFAULT_VERSION = "{version}";
@@ -299,9 +361,14 @@ export const TOUCH_CTX_MENU_TIMEOUT = 500;
export const TITLE_TIMEOUT = 10000;
export const VERSION_TIMEOUT = 30000;
export const SCROLL_TIMEOUT = 100;
export const ZEN_MODE_TRANSITION_DURATION = 250;
export const ZOOM_STEP = 0.1;
export const MIN_ZOOM = 0.1;
export const MAX_ZOOM = 30;
/** 100% zoom, for computations that have no editor zoom to go by */
export const DEFAULT_ZOOM: AppState["zoom"] = Object.freeze({
value: 1 as NormalizedZoomValue,
});
export const HYPERLINK_TOOLTIP_DELAY = 300;
// Report a user inactive after IDLE_THRESHOLD milliseconds
@@ -497,6 +564,7 @@ export const TOOL_TYPE = {
hand: "hand",
frame: "frame",
magicframe: "magicframe",
stickynote: "stickynote",
embeddable: "embeddable",
laser: "laser",
autoshape: "autoshape",
+1
View File
@@ -60,6 +60,7 @@ export const KEYS = {
H: "h",
I: "i",
L: "l",
N: "n",
O: "o",
P: "p",
Q: "q",
+17
View File
@@ -14,3 +14,20 @@ export const reseed = (seed: number) => {
};
export const randomId = () => (isTestEnv() ? `id${testIdBase++}` : nanoid());
/**
* Deterministic PRNG (mulberry32) for a given seed: same seed, same
* sequence — used where a render must be stable across frames and clients
* (e.g. the sticky note's corner jitter) and roughjs's `Random` is
* unsuitable (it degenerates for seed 0). Returns numbers in [0, 1).
*/
export const seededRandom = (seed: number) => {
let value = seed >>> 0;
return () => {
value += 0x6d2b79f5;
let next = value;
next = Math.imul(next ^ (next >>> 15), next | 1);
next ^= next + Math.imul(next ^ (next >>> 7), next | 61);
return ((next ^ (next >>> 14)) >>> 0) / 4294967296;
};
};
+33
View File
@@ -1,5 +1,10 @@
import {
getNearestScrollableContainer,
isInputLike,
isInteractive,
isToolIcon,
isTransparent,
isWritableElement,
mapFind,
reduceToCommonValue,
} from "@excalidraw/common";
@@ -11,6 +16,34 @@ import { throttleRAF } from "./utils";
type RafCallback = FrameRequestCallback;
describe("@excalidraw/common/utils", () => {
describe("cross-document element guards", () => {
it("uses constructors from the target element's window", () => {
const iframe = document.createElement("iframe");
document.body.append(iframe);
const iframeDocument = iframe.contentDocument!;
const iframeWindow = iframe.contentWindow!;
const textarea = iframeDocument.createElement("textarea");
const button = iframeDocument.createElement("button");
const toolIcon = iframeDocument.createElement("div");
toolIcon.className = "ToolIcon__icon";
expect(textarea).not.toBeInstanceOf(HTMLTextAreaElement);
expect(textarea).toBeInstanceOf(
(iframeWindow as Window & typeof globalThis).HTMLTextAreaElement,
);
expect(isInputLike(textarea)).toBe(true);
expect(isWritableElement(textarea)).toBe(true);
expect(isInteractive(button)).toBe(true);
expect(isToolIcon(toolIcon)).toBe(true);
iframeDocument.body.append(textarea);
expect(getNearestScrollableContainer(textarea)).toBe(iframeDocument);
iframe.remove();
});
});
describe("isTransparent()", () => {
it("should return true when color is rgb transparent", () => {
expect(isTransparent("#ff00")).toEqual(true);
+61 -23
View File
@@ -48,10 +48,23 @@ export const getDateTime = () => {
export const capitalizeString = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1);
const getTargetWindow = (
target: Element | EventTarget | null,
): (Window & typeof globalThis) | null =>
(target as (EventTarget & { ownerDocument?: Document | null }) | null)
?.ownerDocument?.defaultView ??
(typeof window === "undefined" ? null : window);
export const isToolIcon = (
target: Element | EventTarget | null,
): target is HTMLElement =>
target instanceof HTMLElement && target.className.includes("ToolIcon");
): target is HTMLElement => {
const targetWindow = getTargetWindow(target);
return (
!!targetWindow &&
target instanceof targetWindow.HTMLElement &&
target.className.includes("ToolIcon")
);
};
export const isInputLike = (
target: Element | EventTarget | null,
@@ -60,17 +73,26 @@ export const isInputLike = (
| HTMLTextAreaElement
| HTMLSelectElement
| HTMLBRElement
| HTMLDivElement =>
(target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
target instanceof HTMLBRElement || // newline in wysiwyg
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement;
| HTMLDivElement => {
const targetWindow = getTargetWindow(target);
return (
!!targetWindow &&
((target instanceof targetWindow.HTMLElement &&
target.dataset.type === "wysiwyg") ||
target instanceof targetWindow.HTMLBRElement || // newline in wysiwyg
target instanceof targetWindow.HTMLInputElement ||
target instanceof targetWindow.HTMLTextAreaElement ||
target instanceof targetWindow.HTMLSelectElement)
);
};
export const isInteractive = (target: Element | EventTarget | null) => {
const targetWindow = getTargetWindow(target);
return (
isInputLike(target) ||
(target instanceof Element && !!target.closest("label, button"))
(!!targetWindow &&
target instanceof targetWindow.Element &&
!!target.closest("label, button"))
);
};
@@ -80,16 +102,23 @@ export const isWritableElement = (
| HTMLInputElement
| HTMLTextAreaElement
| HTMLBRElement
| HTMLDivElement =>
(target instanceof HTMLElement && target.dataset.type === "wysiwyg") ||
target instanceof HTMLBRElement || // newline in wysiwyg
target instanceof HTMLTextAreaElement ||
(target instanceof HTMLInputElement &&
(target.type === "text" ||
target.type === "number" ||
target.type === "password" ||
target.type === "search")) ||
(target instanceof HTMLElement && target.closest(".cm-editor") !== null);
| HTMLDivElement => {
const targetWindow = getTargetWindow(target);
return (
!!targetWindow &&
((target instanceof targetWindow.HTMLElement &&
target.dataset.type === "wysiwyg") ||
target instanceof targetWindow.HTMLBRElement || // newline in wysiwyg
target instanceof targetWindow.HTMLTextAreaElement ||
(target instanceof targetWindow.HTMLInputElement &&
(target.type === "text" ||
target.type === "number" ||
target.type === "password" ||
target.type === "search")) ||
(target instanceof targetWindow.HTMLElement &&
target.closest(".cm-editor") !== null))
);
};
export const getFontFamilyString = ({
fontFamily,
@@ -344,6 +373,13 @@ const RE_RTL_CHECK = new RegExp(`^[^${RS_LTR_CHARS}]*[${RS_RTL_CHARS}]`);
*/
export const isRTL = (text: string) => RE_RTL_CHECK.test(text);
const RE_RTL_CHARS = new RegExp(`[${RS_RTL_CHARS}]`);
/**
* Checks whether the text has any RTL character, i.e. whether it may be laid
* out bidirectionally.
*/
export const hasRTLChars = (text: string) => RE_RTL_CHARS.test(text);
export const tupleToCoors = (
xyTuple: readonly [number, number],
): { x: number; y: number } => {
@@ -475,12 +511,14 @@ export const supportsEmoji = () => {
export const getNearestScrollableContainer = (
element: HTMLElement,
): HTMLElement | Document => {
const ownerDocument = element.ownerDocument;
const ownerWindow = ownerDocument.defaultView ?? window;
let parent = element.parentElement;
while (parent) {
if (parent === document.body) {
return document;
if (parent === ownerDocument.body) {
return ownerDocument;
}
const { overflowY } = window.getComputedStyle(parent);
const { overflowY } = ownerWindow.getComputedStyle(parent);
const hasScrollableContent = parent.scrollHeight > parent.clientHeight;
if (
hasScrollableContent &&
@@ -492,7 +530,7 @@ export const getNearestScrollableContainer = (
}
parent = parent.parentElement;
}
return document;
return ownerDocument;
};
export const focusNearestParent = (element: HTMLInputElement) => {
@@ -14,6 +14,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -51,6 +52,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -83,6 +85,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -144,6 +147,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -210,6 +214,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -242,6 +247,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": [
{
"id": "id50",
@@ -249,6 +255,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
},
],
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -259,6 +266,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a0",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -288,6 +296,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": [
{
"id": "id50",
@@ -295,6 +304,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
},
],
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -305,6 +315,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a1",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -339,6 +350,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -400,8 +412,10 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id50",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -412,6 +426,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
"id": Any<String>,
"index": "a3",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -446,6 +461,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -507,8 +523,10 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id39",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -519,6 +537,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"id": Any<String>,
"index": "a1",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -553,6 +572,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -590,6 +610,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -627,6 +648,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -688,8 +710,10 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id43",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -700,6 +724,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a1",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -729,6 +754,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": [
{
"id": "id43",
@@ -736,6 +762,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
},
],
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -746,6 +773,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a2",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -775,6 +803,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": [
{
"id": "id43",
@@ -782,6 +811,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
},
],
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -792,6 +822,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
"id": Any<String>,
"index": "a3",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -821,6 +852,7 @@ exports[`Test Transform > should not allow duplicate ids 1`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -853,6 +885,7 @@ exports[`Test Transform > should transform linear elements 1`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -900,6 +933,7 @@ exports[`Test Transform > should transform linear elements 2`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "triangle",
@@ -947,6 +981,7 @@ exports[`Test Transform > should transform linear elements 3`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"endArrowhead": null,
"endBinding": null,
@@ -994,6 +1029,7 @@ exports[`Test Transform > should transform linear elements 4`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"endArrowhead": null,
"endBinding": null,
@@ -1041,6 +1077,7 @@ exports[`Test Transform > should transform regular shapes 1`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1073,6 +1110,7 @@ exports[`Test Transform > should transform regular shapes 2`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1105,6 +1143,7 @@ exports[`Test Transform > should transform regular shapes 3`] = `
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1137,6 +1176,7 @@ exports[`Test Transform > should transform regular shapes 4`] = `
"angle": 0,
"backgroundColor": "#c0eb75",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1169,6 +1209,7 @@ exports[`Test Transform > should transform regular shapes 5`] = `
"angle": 0,
"backgroundColor": "#ffc9c9",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1201,6 +1242,7 @@ exports[`Test Transform > should transform regular shapes 6`] = `
"angle": 0,
"backgroundColor": "#a5d8ff",
"boundElements": null,
"created": 1,
"customData": undefined,
"fillStyle": "cross-hatch",
"frameId": null,
@@ -1233,8 +1275,10 @@ exports[`Test Transform > should transform text element 1`] = `
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1245,6 +1289,7 @@ exports[`Test Transform > should transform text element 1`] = `
"id": Any<String>,
"index": "a0",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1274,8 +1319,10 @@ exports[`Test Transform > should transform text element 2`] = `
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": null,
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1286,6 +1333,7 @@ exports[`Test Transform > should transform text element 2`] = `
"id": Any<String>,
"index": "a1",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1324,6 +1372,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1363,6 +1412,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1406,6 +1456,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1453,6 +1504,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "arrow",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -1492,6 +1544,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -1560,6 +1613,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -1619,8 +1673,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "B",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1633,6 +1689,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a6",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1662,8 +1719,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "A",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1676,6 +1735,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a7",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1705,8 +1765,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "Alice",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1719,6 +1781,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a8",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1748,8 +1811,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "Bob",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1762,6 +1827,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "a9",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1791,8 +1857,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "Bob_Alice",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1803,6 +1871,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "aA",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1832,8 +1901,10 @@ exports[`Test Transform > should transform the elements correctly when linear el
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "Bob_B",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -1844,6 +1915,7 @@ exports[`Test Transform > should transform the elements correctly when linear el
"id": Any<String>,
"index": "aB",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -1859,12 +1931,12 @@ exports[`Test Transform > should transform the elements correctly when linear el
"textAlign": "center",
"type": "text",
"updated": 1,
"version": 3,
"version": 2,
"versionNonce": Any<Number>,
"verticalAlign": "middle",
"width": 100,
"x": 27.016999999999996,
"y": 66.5,
"x": -50,
"y": -12.5,
}
`;
@@ -1878,6 +1950,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -1930,6 +2003,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -1982,6 +2056,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -2034,6 +2109,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"elbowed": false,
"endArrowhead": "arrow",
@@ -2081,8 +2157,10 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id25",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2093,6 +2171,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a4",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2122,8 +2201,10 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id26",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2134,6 +2215,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a5",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2163,8 +2245,10 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id27",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2175,6 +2259,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a6",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2205,8 +2290,10 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id28",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2217,6 +2304,7 @@ exports[`Test Transform > should transform to labelled arrows when label provide
"id": Any<String>,
"index": "a7",
"isDeleted": false,
"labelPosition": 0.5,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2252,6 +2340,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2289,6 +2378,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2326,6 +2416,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2363,6 +2454,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2400,6 +2492,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2437,6 +2530,7 @@ exports[`Test Transform > should transform to text containers when label provide
"type": "text",
},
],
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"frameId": null,
@@ -2469,8 +2563,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id13",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2481,6 +2577,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a6",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2510,8 +2607,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id14",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2522,6 +2621,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a7",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2552,8 +2652,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id15",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2564,6 +2666,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a8",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2596,8 +2699,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id16",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2608,6 +2713,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "a9",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2638,8 +2744,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id17",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2650,6 +2758,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "aA",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -2681,8 +2790,10 @@ exports[`Test Transform > should transform to text containers when label provide
"angle": 0,
"autoResize": true,
"backgroundColor": "transparent",
"baseFontSize": null,
"boundElements": null,
"containerId": "id18",
"created": 1,
"customData": undefined,
"fillStyle": "solid",
"fontFamily": 5,
@@ -2693,6 +2804,7 @@ exports[`Test Transform > should transform to text containers when label provide
"id": Any<String>,
"index": "aB",
"isDeleted": false,
"labelPosition": null,
"lineHeight": 1.25,
"link": null,
"locked": false,
@@ -0,0 +1,60 @@
import { ROUNDNESS } from "@excalidraw/common";
import type { AppState } from "@excalidraw/excalidraw/types";
import { Scene } from "../Scene";
import { addNewNodes } from "../flowchart";
import { newStickyNoteElement } from "../newElement";
import { isFlowchartNodeElement, isStickyNoteElement } from "../typeChecks";
describe("flowchart", () => {
it("creates connected sticky notes", () => {
const sticky = newStickyNoteElement({
type: "stickynote",
x: 100,
y: 100,
width: 240,
height: 260,
baseHeight: 220,
roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },
roughness: 2,
backgroundColor: "#ffec99",
strokeColor: "#1e1e1e",
strokeWidth: 2,
});
const scene = new Scene([sticky], { skipValidation: true });
const {
nodes: [nextNode, bindingArrow],
} = addNewNodes(
sticky,
{
currentItemEndArrowhead: "arrow",
} as AppState,
"right",
scene,
1,
);
expect(isFlowchartNodeElement(sticky)).toBe(true);
expect(isFlowchartNodeElement(nextNode)).toBe(true);
expect(isStickyNoteElement(nextNode)).toBe(true);
expect(nextNode).toMatchObject({
type: "stickynote",
x: sticky.x + sticky.width + 100,
y: sticky.y,
width: sticky.width,
height: sticky.height,
baseHeight: sticky.baseHeight,
roundness: sticky.roundness,
roughness: sticky.roughness,
backgroundColor: sticky.backgroundColor,
strokeColor: sticky.strokeColor,
strokeWidth: sticky.strokeWidth,
});
expect(bindingArrow).toMatchObject({
type: "arrow",
startBinding: { elementId: sticky.id },
endBinding: { elementId: nextNode.id },
});
});
});
File diff suppressed because it is too large Load Diff
@@ -1,12 +1,30 @@
import {
DEFAULT_STICKY_NOTE_BG,
DEFAULT_STICKY_NOTE_SIZE,
STICKY_NOTE_MIN_FONT_SIZE,
STICKY_NOTE_MIN_SIZE,
getUpdatedTimestamp,
} from "@excalidraw/common";
import { pointFrom } from "@excalidraw/math";
import { vi } from "vitest";
import {
newElement,
newEmbeddableElement,
newFreeDrawElement,
newIframeElement,
} from "../newElement";
import {
convertToExcalidrawElements,
type ExcalidrawElementSkeleton,
} from "../transform";
import type { ExcalidrawArrowElement } from "../types";
import type {
ExcalidrawArrowElement,
ExcalidrawStickyNoteElement,
ExcalidrawTextElement,
} from "../types";
const opts = { regenerateIds: false };
@@ -965,4 +983,208 @@ describe("Test Transform", () => {
});
});
});
describe("creation timestamps", () => {
const createElements = () => [
{
...newElement({ type: "rectangle", x: 0, y: 0 }),
type: "rectangle" as const,
},
newFreeDrawElement({
type: "freedraw",
x: 0,
y: 0,
simulatePressure: false,
}),
newIframeElement({ type: "iframe", x: 0, y: 0 }),
newEmbeddableElement({ type: "embeddable", x: 0, y: 0 }),
];
it("assigns fresh timestamps when regenerating IDs without mutating the input", () => {
const elements = createElements().map((element) => ({
...element,
created: 123,
}));
const converted = convertToExcalidrawElements(elements);
expect(converted).toHaveLength(elements.length);
converted.forEach((element, index) => {
expect(element.id).not.toBe(elements[index].id);
expect(element.created).toBe(getUpdatedTimestamp());
expect(elements[index].created).toBe(123);
});
});
it.each([123, 0, null])(
"preserves an explicit timestamp of %s when retaining IDs",
(created) => {
const elements = createElements().map((element) => ({
...element,
created,
}));
const converted = convertToExcalidrawElements(elements, opts);
converted.forEach((element, index) => {
expect(element.id).toBe(elements[index].id);
expect(element.created).toBe(created);
});
},
);
it("defaults missing timestamps when retaining IDs, as every type goes through a constructor", () => {
// models skeletons persisted before `created` existed; the declared
// skeleton type is a complete element
const elements = createElements().map(
({ created, ...element }) => element,
) as unknown as ExcalidrawElementSkeleton[];
const converted = convertToExcalidrawElements(elements, opts);
converted.forEach((element, index) => {
expect(element.id).toBe(elements[index].id);
expect(element.created).toBe(getUpdatedTimestamp());
expect(elements[index]).not.toHaveProperty("created");
});
});
it("assigns fresh timestamps to generated labels and binding endpoints", () => {
const elements: ExcalidrawElementSkeleton[] = [
{
type: "arrow",
x: 100,
y: 100,
created: 123,
// fragments cannot carry a creation time; they are always new
label: { text: "label" },
start: { type: "rectangle" },
end: { type: "text", text: "end" },
},
];
const converted = convertToExcalidrawElements(elements);
expect(converted).toHaveLength(4);
expect(converted.map((element) => element.created)).toEqual(
Array(4).fill(getUpdatedTimestamp()),
);
});
});
describe("sticky notes", () => {
const find = <
T extends ExcalidrawStickyNoteElement | ExcalidrawTextElement,
>(
elements: readonly { type: string }[],
type: T["type"],
) => elements.find((element) => element.type === type) as T;
it("creates a finalized note with the sticky defaults", () => {
const elements = convertToExcalidrawElements(
[{ type: "stickynote", x: 100, y: 100 }],
opts,
);
const note = find<ExcalidrawStickyNoteElement>(elements, "stickynote");
expect(elements).toHaveLength(1);
expect(note.width).toBe(DEFAULT_STICKY_NOTE_SIZE);
expect(note.height).toBe(DEFAULT_STICKY_NOTE_SIZE);
expect(note.baseHeight).toBe(DEFAULT_STICKY_NOTE_SIZE);
expect(note.backgroundColor).toBe(DEFAULT_STICKY_NOTE_BG);
expect(note.fillStyle).toBe("solid");
});
it("enforces the note invariants on the given properties", () => {
const note = find<ExcalidrawStickyNoteElement>(
convertToExcalidrawElements(
[
{
type: "stickynote",
x: 0,
y: 0,
width: 10,
height: 300,
backgroundColor: "transparent",
strokeColor: "transparent",
},
],
opts,
),
"stickynote",
);
expect(note.width).toBe(STICKY_NOTE_MIN_SIZE);
expect(note.height).toBe(300);
expect(note.baseHeight).toBe(300);
expect(note.backgroundColor).toBe(DEFAULT_STICKY_NOTE_BG);
expect(note.strokeColor).not.toBe("transparent");
});
it("gives the note the color of a label that sets its own", () => {
const elements = convertToExcalidrawElements(
[
{
type: "stickynote",
x: 0,
y: 0,
strokeColor: "#1971c2",
label: { text: "hello", strokeColor: "#e03131" },
},
],
opts,
);
const note = find<ExcalidrawStickyNoteElement>(elements, "stickynote");
const label = find<ExcalidrawTextElement>(elements, "text");
expect(label.strokeColor).toBe("#e03131");
expect(note.strokeColor).toBe("#e03131");
});
it("binds a label whose font size becomes the note's ceiling", () => {
const elements = convertToExcalidrawElements(
[
{
type: "stickynote",
x: 100,
y: 100,
strokeColor: "#1971c2",
label: { text: "hello", fontSize: 28 },
},
],
opts,
);
const note = find<ExcalidrawStickyNoteElement>(elements, "stickynote");
const label = find<ExcalidrawTextElement>(elements, "text");
expect(elements).toHaveLength(2);
expect(label.containerId).toBe(note.id);
expect(note.boundElements).toEqual([{ type: "text", id: label.id }]);
expect(label.baseFontSize).toBe(28);
expect(label.fontSize).toBe(28);
// the label is the note's visible text: it takes the note's stroke
expect(label.strokeColor).toBe("#1971c2");
expect(note.height).toBe(DEFAULT_STICKY_NOTE_SIZE);
});
it("grows the note for a label that overflows at the minimum font size", () => {
const elements = convertToExcalidrawElements(
[
{
type: "stickynote",
x: 0,
y: 0,
label: {
text: Array(40).fill("abcdefghijklmnopqrstuvwx").join("\n"),
fontSize: 28,
},
},
],
opts,
);
const note = find<ExcalidrawStickyNoteElement>(elements, "stickynote");
const label = find<ExcalidrawTextElement>(elements, "text");
expect(label.fontSize).toBe(STICKY_NOTE_MIN_FONT_SIZE);
expect(label.baseFontSize).toBe(28);
expect(note.baseHeight).toBe(DEFAULT_STICKY_NOTE_SIZE);
expect(note.height).toBeGreaterThan(DEFAULT_STICKY_NOTE_SIZE);
});
});
});
+1 -1
View File
@@ -188,7 +188,7 @@ export const getTextBindingForArrowEndpoint = (
// than gap-outside the outline, so offsetting there would just shift them.
const gap = isElbowArrow(arrow)
? 0
: getBindingGap({ strokeWidth: targetStrokeWidth }, arrow);
: getBindingGap({ strokeWidth: targetStrokeWidth });
// How far back along the arrow the bound side has to sit for the tip to
// stay exactly where it is.
+5 -6
View File
@@ -10,7 +10,6 @@ import {
getBindingGap,
getGlobalFixedPointForBindableElement,
isBindingEnabled,
maxBindingDistance_simple,
unbindBindingElement,
updateBoundPoint,
} from "../binding";
@@ -20,7 +19,7 @@ import {
isElbowArrow,
} from "../typeChecks";
import { LinearElementEditor } from "../linearElementEditor";
import { getHoveredElementForFocusPoint, hitElementItself } from "../collision";
import { getHoveredElementForBinding, hitElementItself } from "../collision";
import { moveArrowAboveBindable } from "../zindex";
import type {
@@ -94,7 +93,7 @@ export const isFocusPointVisible = (
element: bindableElement,
elementsMap,
point: focusPoint,
threshold: getBindingGap(bindableElement, arrow),
threshold: getBindingGap(bindableElement),
overrideShouldTestInside: true,
})
);
@@ -243,12 +242,11 @@ export const handleFocusPointDrag = (
pointerCoords.y - offsetY,
);
const bindingField = isStartBinding ? "startBinding" : "endBinding";
const hit = getHoveredElementForFocusPoint(
const hit = getHoveredElementForBinding(
point,
arrow,
scene.getNonDeletedElements(),
elementsMap,
maxBindingDistance_simple(appState.zoom),
appState.zoom,
);
// Hovering a bindable element
@@ -279,6 +277,7 @@ export const handleFocusPointDrag = (
newMode || "orbit",
linearElementEditor.draggedFocusPointBinding,
scene,
appState.zoom,
point,
);
}
+187 -151
View File
@@ -62,6 +62,7 @@ import { updateElbowArrowPoints } from "./elbowArrow";
import {
deconstructDiamondElement,
deconstructRectanguloidElement,
getElbowArrowSnapMidPoint,
projectFixedPointOntoDiagonal,
} from "./utils";
@@ -114,7 +115,6 @@ export type BindingStrategy =
* IMPORTANT: currently must be > 0 (this also applies to the computed gap)
*/
export const BASE_BINDING_GAP = 5;
export const BASE_BINDING_GAP_ELBOW = 5;
export const BASE_ARROW_MIN_LENGTH = 10;
export const FOCUS_POINT_SIZE = 10 / 1.5;
@@ -126,12 +126,8 @@ export const getBindingGap = (
// only the stroke width is needed, so the gap can also be computed for a
// bind target that doesn't exist yet (see `getTextBindingForArrowEndpoint`)
bindTarget: Pick<ExcalidrawBindableElement, "strokeWidth">,
opts: Pick<ExcalidrawArrowElement, "elbowed">,
): number => {
return (
(opts.elbowed ? BASE_BINDING_GAP_ELBOW : BASE_BINDING_GAP) +
bindTarget.strokeWidth / 2
);
return BASE_BINDING_GAP + bindTarget.strokeWidth / 2;
};
export const maxBindingDistance_simple = (zoom?: AppState["zoom"]): number => {
@@ -191,6 +187,7 @@ export const bindOrUnbindBindingElement = (
start,
"start",
scene,
appState.zoom,
appState.isBindingEnabled,
isMidpointSnappingEnabled,
);
@@ -199,6 +196,7 @@ export const bindOrUnbindBindingElement = (
end,
"end",
scene,
appState.zoom,
appState.isBindingEnabled,
isMidpointSnappingEnabled,
);
@@ -244,6 +242,7 @@ const bindOrUnbindBindingElementEdge = (
{ mode, element, focusPoint }: BindingStrategy,
startOrEnd: "start" | "end",
scene: Scene,
zoom: AppState["zoom"],
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
): void => {
@@ -257,6 +256,7 @@ const bindOrUnbindBindingElementEdge = (
mode,
startOrEnd,
scene,
zoom,
focusPoint,
shouldSnapToOutline,
isMidpointSnappingEnabled,
@@ -269,7 +269,7 @@ const bindingStrategyForElbowArrowEndpointDragging = (
draggingPoints: PointsPositionUpdates,
elementsMap: NonDeletedSceneElementsMap,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
zoom?: AppState["zoom"],
zoom: AppState["zoom"],
): {
start: BindingStrategy;
end: BindingStrategy;
@@ -293,7 +293,7 @@ const bindingStrategyForElbowArrowEndpointDragging = (
globalPoint,
elements,
elementsMap,
maxBindingDistance_simple(zoom),
zoom,
);
const current = hit
@@ -341,7 +341,12 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
draggingPoints.get(startDragged ? startIdx : endIdx)!.point,
elementsMap,
);
const hit = getHoveredElementForBinding(point, elements, elementsMap);
const hit = getHoveredElementForBinding(
point,
elements,
elementsMap,
appState.zoom,
);
// With new arrows this handles the binding at arrow creation
if (startDragged) {
@@ -386,7 +391,12 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
// Check and handle nested shapes
if (hit && arrow.startBinding) {
const startBinding = arrow.startBinding;
const allHits = getAllHoveredElementAtPoint(point, elements, elementsMap);
const allHits = getAllHoveredElementAtPoint(
point,
elements,
elementsMap,
appState.zoom,
);
if (allHits.find((el) => el.id === startBinding.elementId)) {
const otherElement = elementsMap.get(
@@ -482,15 +492,16 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
globalBindMode: AppState["bindMode"],
arrow: NonDeleted<ExcalidrawArrowElement>,
zoom: AppState["zoom"],
finalize?: boolean,
): { current: BindingStrategy; other: BindingStrategy } => {
let current: BindingStrategy = { mode: undefined };
let other: BindingStrategy = { mode: undefined };
const isMultiPoint = arrow.points.length > 2;
const hit = getHoveredElementForBinding(point, elements, elementsMap);
const hit = getHoveredElementForBinding(point, elements, elementsMap, zoom);
const isOverlapping = oppositeBinding
? getAllHoveredElementAtPoint(point, elements, elementsMap).some(
? getAllHoveredElementAtPoint(point, elements, elementsMap, zoom).some(
(el) => el.id === oppositeBinding.elementId,
)
: false;
@@ -614,7 +625,6 @@ export const getBindingStrategyForDraggingBindingElementEndpoints = (
altKey?: boolean;
finalize?: boolean;
initialBinding?: boolean;
zoom?: AppState["zoom"];
gridSize?: NullableGridSize;
},
): { start: BindingStrategy; end: BindingStrategy } => {
@@ -655,7 +665,6 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
altKey?: boolean;
finalize?: boolean;
initialBinding?: boolean;
zoom?: AppState["zoom"];
gridSize?: NullableGridSize;
},
): { start: BindingStrategy; end: BindingStrategy } => {
@@ -702,7 +711,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
draggingPoints,
elementsMap,
elements,
opts?.zoom,
appState.zoom,
);
}
@@ -727,7 +736,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
: globalPoint,
elements,
elementsMap,
maxBindingDistance_simple(appState.zoom),
appState.zoom,
);
const pointInElement =
hit &&
@@ -1009,6 +1018,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_complex = (
draggingPoints,
elementsMap,
elements,
appState.zoom,
);
}
@@ -1050,6 +1060,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_complex = (
elements,
globalBindMode,
arrow,
appState.zoom,
opts?.finalize,
);
@@ -1074,6 +1085,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_complex = (
elements,
globalBindMode,
arrow,
appState.zoom,
opts?.finalize,
);
@@ -1132,6 +1144,7 @@ export const bindBindingElement = (
mode: BindMode,
startOrEnd: "start" | "end",
scene: Scene,
zoom: AppState["zoom"],
focusPoint?: GlobalPoint,
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
@@ -1149,6 +1162,7 @@ export const bindBindingElement = (
hoveredElement,
startOrEnd,
elementsMap,
zoom,
shouldSnapToOutline,
isMidpointSnappingEnabled,
),
@@ -1202,12 +1216,113 @@ export const unbindBindingElement = (
return binding.elementId;
};
export const reanchorBindingsToOutline = (
changedElement: NonDeleted<ExcalidrawBindableElement>,
scene: Scene,
zoom: AppState["zoom"],
) => {
const elementsMap = scene.getNonDeletedElementsMap();
const center = elementCenterPoint(changedElement, elementsMap);
const reach = Math.max(changedElement.width, changedElement.height) * 2;
boundElementsVisitor(elementsMap, changedElement, (element) => {
if (!isArrowElement(element) || !isNonDeletedElement(element)) {
return;
}
const updates: {
startBinding?: FixedPointBinding;
endBinding?: FixedPointBinding;
} = {};
for (const startOrEnd of ["startBinding", "endBinding"] as const) {
const binding = element[startOrEnd];
if (binding?.elementId !== changedElement.id) {
continue;
}
const startOrEndName = startOrEnd === "startBinding" ? "start" : "end";
if (isElbowArrow(element)) {
updates[startOrEnd] = {
...binding,
...calculateFixedPointForElbowArrowBinding(
element,
changedElement,
startOrEndName,
elementsMap,
zoom,
),
};
continue;
}
const focusPoint = getGlobalFixedPointForBindableElement(
binding.fixedPoint,
changedElement,
elementsMap,
);
if (
hitElementItself({
element: changedElement,
point: focusPoint,
elementsMap,
threshold: getBindingGap(changedElement),
overrideShouldTestInside: true,
})
) {
continue;
}
const direction = vectorFromPoint(focusPoint, center);
if (direction[0] === 0 && direction[1] === 0) {
continue;
}
const outlinePoint = intersectElementWithLineSegment(
changedElement,
elementsMap,
lineSegment(
center,
pointFromVector(
vectorScale(vectorNormalize(direction), reach),
center,
),
),
).sort(
(a, b) =>
pointDistanceSq(a, focusPoint) - pointDistanceSq(b, focusPoint),
)[0];
if (!outlinePoint) {
continue;
}
updates[startOrEnd] = {
...binding,
...calculateFixedPointForNonElbowArrowBinding(
element,
changedElement,
startOrEndName,
elementsMap,
outlinePoint,
),
};
}
if (updates.startBinding || updates.endBinding) {
mutateElement(element, elementsMap, updates);
}
});
};
// Supports translating, rotating and scaling `changedElement` with bound
// linear elements.
export const updateBoundElements = (
changedElement: NonDeletedExcalidrawElement,
scene: Scene,
options?: {
/** see `getSimultaneouslyUpdatedElementIds` for how to pass it */
simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[];
changedElements?: Map<string, ExcalidrawElement>;
},
@@ -1371,6 +1486,7 @@ const updateArrowBindings = (
strategy[strategyName].mode,
strategyName,
scene,
appState.zoom,
strategy[strategyName].focusPoint,
);
}
@@ -1426,10 +1542,33 @@ const doesNeedUpdate = (
);
};
const getSimultaneouslyUpdatedElementIds = (
// PERF: callers updating many elements invoke `updateBoundElements()` for each
// of them with the same `simultaneouslyUpdated` array, so cache the id set
// per array to avoid rebuilding it on every call (O(n^2) on multi-element
// transforms)
const simultaneouslyUpdatedElementIdsCache = new WeakMap<
readonly ExcalidrawElement[],
ReadonlySet<ExcalidrawElement["id"]>
>();
/**
* The id set of `simultaneouslyUpdated`, shared by every `updateBoundElements()`
* call given the same array. Pass one array instance for all elements of an
* operation, and don't change its membership after the first lookup, or the
* cached ids go stale.
*/
export const getSimultaneouslyUpdatedElementIds = (
simultaneouslyUpdated: readonly ExcalidrawElement[] | undefined,
): Set<ExcalidrawElement["id"]> => {
return new Set((simultaneouslyUpdated || []).map((element) => element.id));
): ReadonlySet<ExcalidrawElement["id"]> => {
if (!simultaneouslyUpdated) {
return new Set();
}
let ids = simultaneouslyUpdatedElementIdsCache.get(simultaneouslyUpdated);
if (!ids) {
ids = new Set(simultaneouslyUpdated.map((element) => element.id));
simultaneouslyUpdatedElementIdsCache.set(simultaneouslyUpdated, ids);
}
return ids;
};
export const getHeadingForElbowArrowSnap = (
@@ -1480,6 +1619,7 @@ export const bindPointToSnapToElementOutline = (
bindableElement: ExcalidrawBindableElement,
startOrEnd: "start" | "end",
elementsMap: ElementsMap,
zoom: AppState["zoom"],
customIntersector?: LineSegment<GlobalPoint>,
isMidpointSnappingEnabled = true,
): GlobalPoint => {
@@ -1512,19 +1652,24 @@ export const bindPointToSnapToElementOutline = (
startOrEnd === "start" ? 1 : -2,
elementsMap,
);
const bindingGap = getBindingGap(bindableElement, arrowElement);
const bindingGap = getBindingGap(bindableElement);
const aabb = aabbForElement(bindableElement, elementsMap);
const bindableCenter = getCenterForBounds(aabb);
let intersection: GlobalPoint | null = null;
if (elbowed) {
const isHorizontal = headingIsHorizontal(
headingForPointFromElement(bindableElement, aabb, point),
);
const snapPoint = isMidpointSnappingEnabled
? snapToMid(bindableElement, elementsMap, edgePoint, 0.05, arrowElement)
const snap = isMidpointSnappingEnabled
? getElbowArrowSnapMidPoint(edgePoint, bindableElement, elementsMap, zoom)
: undefined;
const resolved = snapPoint || point;
const resolved = snap?.point ?? point;
// A midpoint on the element's axes fixes the side to bind to. The pointer
// can report another side, e.g. horizontal when slightly inside a
// diamond's top vertex, which would bind next to the vertex.
const isHorizontal = headingIsHorizontal(
snap?.onAxis
? vectorToHeading(vectorFromPoint(snap.point, bindableCenter))
: headingForPointFromElement(bindableElement, aabb, point),
);
const otherPoint = pointFrom<GlobalPoint>(
isHorizontal ? bindableCenter[0] : resolved[0],
!isHorizontal ? bindableCenter[1] : resolved[1],
@@ -1541,12 +1686,16 @@ export const bindPointToSnapToElementOutline = (
otherPoint,
),
);
// The ray can cross the outline twice (e.g. a thin rotated diamond), so
// take the crossing nearest to the point we aim at
const byDistanceToResolved = (a: GlobalPoint, b: GlobalPoint) =>
pointDistanceSq(a, resolved) - pointDistanceSq(b, resolved);
intersection = intersectElementWithLineSegment(
bindableElement,
elementsMap,
intersector,
bindingGap,
).sort(pointDistanceSq)[0];
).sort(byDistanceToResolved)[0];
if (!intersection) {
const anotherPoint = pointFrom<GlobalPoint>(
@@ -1567,8 +1716,8 @@ export const bindPointToSnapToElementOutline = (
bindableElement,
elementsMap,
anotherIntersector,
BASE_BINDING_GAP_ELBOW,
).sort(pointDistanceSq)[0];
BASE_BINDING_GAP,
).sort(byDistanceToResolved)[0];
}
} else {
let intersector = customIntersector;
@@ -1626,7 +1775,7 @@ export const avoidRectangularCorner = (
-bindTarget.angle as Radians,
);
const bindingGap = getBindingGap(bindTarget, arrowElement);
const bindingGap = getBindingGap(bindTarget);
if (nonRotatedPoint[0] < bindTarget.x && nonRotatedPoint[1] < bindTarget.y) {
// Top left
@@ -1704,121 +1853,6 @@ export const avoidRectangularCorner = (
return p;
};
export const snapToMid = (
bindTarget: ExcalidrawBindableElement,
elementsMap: ElementsMap,
p: GlobalPoint,
tolerance: number = 0.05,
arrowElement?: ExcalidrawArrowElement,
): GlobalPoint | undefined => {
const { x, y, width, height, angle } = bindTarget;
const center = elementCenterPoint(bindTarget, elementsMap, -0.1, -0.1);
const nonRotated = pointRotateRads(p, center, -angle as Radians);
const bindingGap = arrowElement ? getBindingGap(bindTarget, arrowElement) : 0;
// snap-to-center point is adaptive to element size, but we don't want to go
// above and below certain px distance
const verticalThreshold = clamp(tolerance * height, 5, 80);
const horizontalThreshold = clamp(tolerance * width, 5, 80);
// Too close to the center makes it hard to resolve direction precisely
if (pointDistance(center, nonRotated) < bindingGap) {
return undefined;
}
if (
nonRotated[0] <= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
// LEFT
return pointRotateRads(
pointFrom<GlobalPoint>(x - bindingGap, center[1]),
center,
angle,
);
} else if (
nonRotated[1] <= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
// TOP
return pointRotateRads(
pointFrom<GlobalPoint>(center[0], y - bindingGap),
center,
angle,
);
} else if (
nonRotated[0] >= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
// RIGHT
return pointRotateRads(
pointFrom<GlobalPoint>(x + width + bindingGap, center[1]),
center,
angle,
);
} else if (
nonRotated[1] >= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
// DOWN
return pointRotateRads(
pointFrom<GlobalPoint>(center[0], y + height + bindingGap),
center,
angle,
);
} else if (bindTarget.type === "diamond") {
const distance = bindingGap;
const topLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + height / 4 - distance,
);
const topRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + height / 4 - distance,
);
const bottomLeft = pointFrom<GlobalPoint>(
x + width / 4 - distance,
y + (3 * height) / 4 + distance,
);
const bottomRight = pointFrom<GlobalPoint>(
x + (3 * width) / 4 + distance,
y + (3 * height) / 4 + distance,
);
if (
pointDistance(topLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(topLeft, center, angle);
}
if (
pointDistance(topRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(topRight, center, angle);
}
if (
pointDistance(bottomLeft, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(bottomLeft, center, angle);
}
if (
pointDistance(bottomRight, nonRotated) <
Math.max(horizontalThreshold, verticalThreshold)
) {
return pointRotateRads(bottomRight, center, angle);
}
}
return undefined;
};
const extractBinding = (
arrow: ExcalidrawArrowElement,
startOrEnd: "startBinding" | "endBinding",
@@ -1881,7 +1915,7 @@ const snapBoundPointToGrid = (
? vectorToHeading(vectorFromPoint(adjacentPoint, outlinePoint))
: headingForPointFromElement(bindableElement, aabb, outlinePoint);
const bindingGap = getBindingGap(bindableElement, arrowElement);
const bindingGap = getBindingGap(bindableElement);
const extent =
Math.max(bindableElement.width, bindableElement.height) + bindingGap * 2;
const center = getCenterForBounds(aabb);
@@ -1999,7 +2033,7 @@ export const updateBoundPoint = (
otherBindable,
elementsMap,
intersector,
getBindingGap(otherBindable, arrow),
getBindingGap(otherBindable),
).sort(
(a, b) => pointDistanceSq(a, focusPoint) - pointDistanceSq(b, focusPoint),
)[0];
@@ -2009,7 +2043,7 @@ export const updateBoundPoint = (
bindableElement,
elementsMap,
intersector,
getBindingGap(bindableElement, arrow),
getBindingGap(bindableElement),
).sort(
(a, b) =>
pointDistanceSq(a, otherFocusPointOrArrowPoint) -
@@ -2037,7 +2071,7 @@ export const updateBoundPoint = (
element: otherBindable,
point: outlinePoint,
elementsMap,
threshold: getBindingGap(otherBindable, arrow),
threshold: getBindingGap(otherBindable),
overrideShouldTestInside: true,
})
) {
@@ -2098,6 +2132,7 @@ export const calculateFixedPointForElbowArrowBinding = (
hoveredElement: ExcalidrawBindableElement,
startOrEnd: "start" | "end",
elementsMap: ElementsMap,
zoom: AppState["zoom"],
shouldSnapToOutline = true,
isMidpointSnappingEnabled = true,
): { fixedPoint: FixedPoint } => {
@@ -2113,6 +2148,7 @@ export const calculateFixedPointForElbowArrowBinding = (
hoveredElement,
startOrEnd,
elementsMap,
zoom,
undefined,
isMidpointSnappingEnabled,
)
@@ -2145,7 +2181,7 @@ export const calculateFixedPointForElbowArrowBinding = (
// elements smaller than the gap don't blow up the ratio: the snapped
// point sits at most one gap-width outside the outline, so this keeps
// the resulting fixedPoint bounded even for zero/near-zero-size elements.
const sizeFloor = getBindingGap(hoveredElement, linearElement);
const sizeFloor = getBindingGap(hoveredElement);
return {
fixedPoint: normalizeFixedPoint([
@@ -2195,7 +2231,7 @@ export const calculateFixedPointForNonElbowArrowBinding = (
// elements smaller than the gap don't blow up the ratio: the bound
// point sits at most one gap-width outside the outline, so this keeps
// the resulting fixedPoint bounded even for zero/near-zero-size elements.
const sizeFloor = getBindingGap(hoveredElement, linearElement);
const sizeFloor = getBindingGap(hoveredElement);
// Calculate the ratio relative to the element's bounds
const fixedPointX =
+5 -1
View File
@@ -420,6 +420,7 @@ const _isRectanguloidElement = (
return (
element != null &&
(element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "image" ||
element.type === "iframe" ||
element.type === "embeddable" ||
@@ -1276,6 +1277,7 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({
type,
excludeElementsInFrames,
shouldIgnoreElementFromSelection,
includeStroke = true,
}: {
elements: readonly T[];
elementsMap?: ElementsMap;
@@ -1287,6 +1289,8 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({
type: "contain" | "overlap";
excludeElementsInFrames?: boolean;
shouldIgnoreElementFromSelection?: (element: T) => boolean;
/** whether elements extend by their stroke, as they render */
includeStroke?: boolean;
}) => {
if (!elementsMap) {
elementsMap = arrayToMap(elements) as ElementsMap;
@@ -1335,7 +1339,7 @@ export const elementsOverlappingBBox = <T extends ExcalidrawElement>({
groups[groupId].push(element);
}
const strokeWidth = element.strokeWidth;
const strokeWidth = includeStroke ? element.strokeWidth : 0;
let labelAABB: Bounds | null = null;
let elementAABB = getElementBounds(element, elementsMap);
+217 -141
View File
@@ -8,6 +8,7 @@ import {
pointFromVector,
pointRotateRads,
pointsEqual,
polygonIncludesPoint,
vectorFromPoint,
vectorNormalize,
vectorScale,
@@ -22,10 +23,11 @@ import type {
Curve,
GlobalPoint,
LineSegment,
LocalPoint,
Radians,
} from "@excalidraw/math";
import type { FrameNameBounds } from "@excalidraw/excalidraw/types";
import type { AppState, FrameNameBounds } from "@excalidraw/excalidraw/types";
import { isPathALoop } from "./utils";
import {
@@ -40,6 +42,7 @@ import {
import {
hasBoundTextElement,
isBindableElement,
isBoundToContainer,
isFrameLikeElement,
isFreeDrawElement,
isIframeLikeElement,
@@ -53,19 +56,21 @@ import {
deconstructRectanguloidElement,
} from "./utils";
import { getBoundTextElement } from "./textElement";
import { LinearElementEditor } from "./linearElementEditor";
import {
getBoundTextElement,
getTextElementWithAccuratePosition,
} from "./textElement";
import { distanceToElement } from "./distance";
import { getBindingGap } from "./binding";
import { maxBindingDistance_simple } from "./binding";
import { hasBackground } from "./comparisons";
import { getFreedrawFillPolygon, getFreedrawMaxStrokeRadius } from "./shape";
import type {
ElementsMap,
ExcalidrawArrowElement,
ExcalidrawBindableElement,
ExcalidrawDiamondElement,
ExcalidrawElement,
@@ -141,7 +146,10 @@ export const hitElementItself = ({
// A cached hit stays valid for any larger threshold, while a cached miss
// stays valid only for a threshold no larger than the cached one (a larger
// threshold could turn a miss into a hit).
// Skipped for container-bound labels — their position can change without
// their version being bumped (see ElementBounds.getBounds).
if (
!isBoundToContainer(element) &&
cachedPoint &&
pointsEqual(point, cachedPoint) &&
(cachedHit ? cachedThreshold <= threshold : cachedThreshold >= threshold) &&
@@ -177,7 +185,10 @@ export const hitElementItself = ({
point,
bounds,
element.angle,
threshold,
// Freedraw bounds follow the centerline points, but the ink extends past them
isFreeDrawElement(element)
? threshold + getFreedrawMaxStrokeRadius(element)
: threshold,
);
// PERF: Bail out early if the point is not even in the
@@ -186,6 +197,15 @@ export const hitElementItself = ({
return false;
}
// an arrow label's stored coords can be stale. The bounds test above
// already accounts for it (getElementBounds derives the position
// internally), but the precise test below reads the element coords
// directly, so substitute them. Done after the early bail so the common
// miss path stays allocation-free.
if (isTextElement(element)) {
element = getTextElementWithAccuratePosition(element, elementsMap);
}
// Do the precise (and relatively costly) hit test
const hitElement = (
overrideShouldTestInside ? true : shouldTestInside(element)
@@ -256,78 +276,102 @@ export const hitElementBoundText = (
if (!boundTextElementCandidate) {
return false;
}
const boundTextElement = isLinearElement(element)
? {
...boundTextElementCandidate,
// arrow's bound text accurate position is not stored in the element's property
// but rather calculated and returned from the following static method
...LinearElementEditor.getBoundTextElementPosition(
element,
boundTextElementCandidate,
elementsMap,
),
}
: boundTextElementCandidate;
const boundTextElement = getTextElementWithAccuratePosition(
boundTextElementCandidate,
elementsMap,
);
return isPointInElement(point, boundTextElement, elementsMap);
};
const bindingBorderTest = (
element: NonDeleted<ExcalidrawBindableElement>,
[x, y]: Readonly<GlobalPoint>,
elementsMap: NonDeletedSceneElementsMap,
tolerance: number = 0,
): boolean => {
const p = pointFrom<GlobalPoint>(x, y);
const shouldTestInside =
// disable fullshape snapping for frame elements so we
// can bind to frame children
!isFrameLikeElement(element);
// Frame children are clipped to their enclosing frame, so a point outside
// the frame cannot hit them
const isPointClippedByEnclosingFrame = (
element: ExcalidrawElement,
point: Readonly<GlobalPoint>,
elementsMap: ElementsMap,
) => {
if (!element.frameId) {
return false;
}
const enclosingFrame = elementsMap.get(element.frameId);
return (
!!enclosingFrame &&
isFrameLikeElement(enclosingFrame) &&
!pointInsideBounds(point, getElementBounds(enclosingFrame, elementsMap))
);
};
const bindableElementBorderDistanceIfClose = (
element: NonDeleted<ExcalidrawBindableElement>,
point: GlobalPoint,
elementsMap: ElementsMap,
tolerance: number = 0,
) => {
// PERF: Run a cheap test to see if the binding element
// is even close to the element
const [x, y] = point;
const t = Math.max(1, tolerance);
const bounds = [x - t, y - t, x + t, y + t] as Bounds;
const elementBounds = getElementBounds(element, elementsMap);
if (!doBoundsIntersect(bounds, elementBounds)) {
return false;
return -Infinity;
}
// If the element is inside a frame, we should clip the element
if (element.frameId) {
const enclosingFrame = elementsMap.get(element.frameId);
if (enclosingFrame && isFrameLikeElement(enclosingFrame)) {
const enclosingFrameBounds = getElementBounds(
enclosingFrame,
elementsMap,
);
if (!pointInsideBounds(p, enclosingFrameBounds)) {
return false;
}
}
if (isPointClippedByEnclosingFrame(element, point, elementsMap)) {
return -Infinity;
}
// Do the intersection test against the element since it's close enough
const intersections = intersectElementWithLineSegment(
element,
elementsMap,
lineSegment(elementCenterPoint(element, elementsMap), p),
);
const distance = distanceToElement(element, elementsMap, p);
const isInside = isPointInElement(point, element, elementsMap);
// frames are only bindable from the outside, so arrows ending inside
// a frame can bind to its children (or stay unbound)
if (isInside && isFrameLikeElement(element)) {
return -Infinity;
}
return shouldTestInside
? intersections.length === 0 || distance <= tolerance
: intersections.length > 0 && distance <= t;
const distance = distanceToElement(element, elementsMap, point);
if (isInside) {
return distance;
}
return distance > tolerance ? -Infinity : -distance;
};
export const getAllHoveredElementAtPoint = (
type BindingCandidate = {
element: NonDeleted<ExcalidrawBindableElement>;
/** distance to the outline: positive inside, negative outside */
distance: number;
};
/**
* Whether the element hides what is behind it from binding — an arrow's or a
* text label's. Images count as opaque, and frames once they support a
* background.
*/
export const isOpaqueForBinding = (element: ExcalidrawElement) =>
isImageElement(element) ||
(hasBackground(element.type) && !isTransparent(element.backgroundColor));
/**
* Bindable elements within binding distance of the point, front to back.
* Stops at the first opaque element containing the point, since it hides
* everything behind it. Locked elements can't be bound to, but still hide
* what is behind them.
*/
const getBindingCandidates = (
point: Readonly<GlobalPoint>,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
): NonDeleted<ExcalidrawBindableElement>[] => {
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
// We need to to hit testing from front (end of the array) to back (beginning of the array)
zoom: AppState["zoom"],
): BindingCandidate[] => {
const maxDistance = maxBindingDistance_simple(zoom);
const candidates: BindingCandidate[] = [];
// A frame's children sit just below it in z-order, so a frame's background
// can't end the search: it only hides the non-children behind it
let occludingFrameId: ExcalidrawElement["id"] | null = null;
// We need to do hit testing from front (end of the array) to back (beginning of the array)
// because array is ordered from lower z-index to highest and we want element z-index
// with higher z-index
for (let index = elements.length - 1; index >= 0; --index) {
@@ -335,104 +379,109 @@ export const getAllHoveredElementAtPoint = (
invariant(
!element.isDeleted,
"Elements in the function parameter for getAllElementsAtPositionForBinding() should not contain deleted elements",
"Elements passed to binding hit tests should not contain deleted elements",
);
if (
isBindableElement(element, false) &&
bindingBorderTest(element, point, elementsMap, tolerance)
) {
candidateElements.push(element);
if (occludingFrameId && element.frameId !== occludingFrameId) {
continue;
}
if (!isBindableElement(element)) {
continue;
}
if (isFrameLikeElement(element)) {
if (
hasBackground(element.type) &&
!isTransparent(element.backgroundColor)
isOpaqueForBinding(element) &&
isPointInElement(point, element, elementsMap)
) {
occludingFrameId = element.id;
}
}
const distance = bindableElementBorderDistanceIfClose(
element,
point,
elementsMap,
maxDistance,
);
if (distance > -maxDistance) {
if (!element.locked) {
candidates.push({ element, distance });
}
if (distance >= 0 && isOpaqueForBinding(element)) {
break;
}
}
}
return candidateElements;
return candidates;
};
/**
* All elements an arrow endpoint at the point could bind to. Always includes
* the result of `getHoveredElementForBinding` for the same arguments.
*/
export const getAllHoveredElementAtPoint = (
point: Readonly<GlobalPoint>,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
zoom: AppState["zoom"],
): NonDeleted<ExcalidrawBindableElement>[] =>
getBindingCandidates(point, elements, elementsMap, zoom).map(
({ element }) => element,
);
export const getHoveredElementForBinding = (
point: Readonly<GlobalPoint>,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
zoom: AppState["zoom"],
): NonDeleted<ExcalidrawBindableElement> | null => {
const candidateElements = getAllHoveredElementAtPoint(
point,
elements,
elementsMap,
tolerance,
const candidates = getBindingCandidates(point, elements, elementsMap, zoom);
if (candidates.length === 0) {
return null;
}
if (candidates.length === 1) {
return candidates[0].element;
}
const closestElements = candidates.sort(
(a, b) => Math.abs(a.distance) - Math.abs(b.distance),
);
if (!candidateElements || candidateElements.length === 0) {
return null;
}
const candidate = closestElements[0];
const [cx1, cy1, cx2, cy2] = getElementBounds(candidate.element, elementsMap);
const candidateArea = Math.max(
0.00001,
Math.abs(cx2 - cx1) * Math.abs(cy2 - cy1),
);
// A smaller element overlapping the closest one takes precedence, but only
// when the point is inside it: otherwise the closest outline wins, e.g. an
// arrow ending just inside a container's edge next to a nested element
const overlaps = closestElements
.filter((c) => c.element !== candidate.element && c.distance >= 0)
.map((c) => {
const [x1, y1, x2, y2] = getElementBounds(c.element, elementsMap);
const overlapWidth = Math.max(0, Math.min(x2, cx2) - Math.max(x1, cx1));
const overlapHeight = Math.max(0, Math.min(y2, cy2) - Math.max(y1, cy1));
const area = Math.max(0.00001, Math.abs(x2 - x1) * Math.abs(y2 - y1));
if (candidateElements.length === 1) {
return candidateElements[0];
}
return {
...c,
overlapPercent: (overlapHeight * overlapWidth) / area,
relativeArea: area / candidateArea,
};
})
.filter((c) => c.overlapPercent > 0.25 && c.relativeArea < 0.75);
// Prefer smaller shapes
return candidateElements
.sort(
(a, b) => b.width ** 2 + b.height ** 2 - (a.width ** 2 + a.height ** 2),
)
.pop() as NonDeleted<ExcalidrawBindableElement>;
};
export const getHoveredElementForFocusPoint = (
point: GlobalPoint,
arrow: ExcalidrawArrowElement,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
elementsMap: NonDeletedSceneElementsMap,
tolerance?: number,
): NonDeleted<ExcalidrawBindableElement> | null => {
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
// We need to to hit testing from front (end of the array) to back (beginning of the array)
// because array is ordered from lower z-index to highest and we want element z-index
// with higher z-index
for (let index = elements.length - 1; index >= 0; --index) {
const element = elements[index];
invariant(
!element.isDeleted,
"Elements in the function parameter for getAllElementsAtPositionForBinding() should not contain deleted elements",
);
if (
isBindableElement(element, false) &&
bindingBorderTest(element, point, elementsMap, tolerance)
) {
candidateElements.push(element);
}
}
if (!candidateElements || candidateElements.length === 0) {
return null;
}
if (candidateElements.length === 1) {
return candidateElements[0];
}
const distanceFilteredCandidateElements = candidateElements
// Resolve by distance
.filter(
(el) =>
distanceToElement(el, elementsMap, point) <= getBindingGap(el, arrow) ||
isPointInElement(point, el, elementsMap),
);
if (distanceFilteredCandidateElements.length === 0) {
return null;
}
return distanceFilteredCandidateElements[0] as NonDeleted<ExcalidrawBindableElement>;
return candidate.distance >= 0 && overlaps.length > 0
? overlaps[0].element
: candidate.element;
};
/**
@@ -467,6 +516,7 @@ export const intersectElementWithLineSegment = (
// Do the actual intersection test against the element's shape
switch (element.type) {
case "rectangle":
case "stickynote":
case "image":
case "text":
case "iframe":
@@ -508,6 +558,8 @@ export const intersectElementWithLineSegment = (
}
};
const CURVE_BOUNDS_EPSILON = 1e-6;
const curveIntersections = (
curves: Curve<GlobalPoint>[],
segment: LineSegment<GlobalPoint>,
@@ -516,15 +568,19 @@ const curveIntersections = (
angle: Radians,
onlyFirst = false,
) => {
// Pad the segment bounds so an axis-aligned segment passing exactly through
// the joint of two curves still overlaps their bounds, as
// `doBoundsIntersect` treats bounds that only touch as not intersecting
const b2 = [
Math.min(segment[0][0], segment[1][0]) - CURVE_BOUNDS_EPSILON,
Math.min(segment[0][1], segment[1][1]) - CURVE_BOUNDS_EPSILON,
Math.max(segment[0][0], segment[1][0]) + CURVE_BOUNDS_EPSILON,
Math.max(segment[0][1], segment[1][1]) + CURVE_BOUNDS_EPSILON,
] as Bounds;
for (const c of curves) {
// Optimize by doing a cheap bounding box check first
const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]);
const b2 = [
Math.min(segment[0][0], segment[1][0]),
Math.min(segment[0][1], segment[1][1]),
Math.max(segment[0][0], segment[1][0]),
Math.max(segment[0][1], segment[1][1]),
] as Bounds;
if (!doBoundsIntersect(b1, b2)) {
continue;
@@ -784,6 +840,26 @@ export const isPointInElement = (
return false;
}
if (isFreeDrawElement(element)) {
// Test before the rotated-bounds check below: the smoothed fill can bulge
// past the recorded points, and how much of it those bounds would clip
// depends on the angle. An asymmetric loop's rotated bounds center is also
// not its rotation pivot.
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap, true);
const [px, py] = pointRotateRads(
point,
pointFrom<GlobalPoint>((x1 + x2) / 2, (y1 + y2) / 2),
-element.angle as Radians,
);
// The fill follows the centerline rather than the stroke outline, and uses
// the same even-odd rule as RoughJS's filled curves.
return polygonIncludesPoint(
pointFrom<LocalPoint>(px - element.x, py - element.y),
getFreedrawFillPolygon(element),
);
}
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
if (!isPointWithinBounds(pointFrom(x1, y1), point, pointFrom(x2, y2))) {
+9
View File
@@ -2,6 +2,7 @@ import type { ElementOrToolType } from "@excalidraw/excalidraw/types";
export const hasBackground = (type: ElementOrToolType) =>
type === "rectangle" ||
type === "stickynote" ||
type === "iframe" ||
type === "embeddable" ||
type === "ellipse" ||
@@ -12,8 +13,12 @@ export const hasBackground = (type: ElementOrToolType) =>
// tool-only type; makes the `G` background shortcut work for bucket fill
type === "bucketfill";
export const hasFillStyle = (type: ElementOrToolType) =>
hasBackground(type) && type !== "stickynote";
export const hasStrokeColor = (type: ElementOrToolType) =>
type === "rectangle" ||
type === "stickynote" ||
type === "ellipse" ||
type === "diamond" ||
type === "freedraw" ||
@@ -44,6 +49,9 @@ export const hasStrokeStyle = (type: ElementOrToolType) =>
type === "line" ||
type === "autoshape";
export const hasRoughness = (type: ElementOrToolType) =>
hasStrokeStyle(type) || type === "stickynote";
export const hasFreedrawMode = (type: ElementOrToolType) => type === "freedraw";
export const canChangeRoundness = (type: ElementOrToolType) =>
@@ -52,6 +60,7 @@ export const canChangeRoundness = (type: ElementOrToolType) =>
type === "embeddable" ||
type === "line" ||
type === "diamond" ||
type === "stickynote" ||
type === "image";
export const toolIsArrow = (type: ElementOrToolType) => type === "arrow";
+4
View File
@@ -797,6 +797,10 @@ export const convertToShapeHandlePointerMoveFromPointerDown = (
prevPreview?.type === shapePreview.type
? prevPreview.id
: shapePreview.id,
created:
prevPreview?.type === shapePreview.type
? prevPreview.created
: shapePreview.created,
seed: 1,
opacity: ELEMENT_PENDING_DRAW_SHAPE_OPACITY,
isDeleted: false as const,
+165 -434
View File
@@ -1,7 +1,6 @@
import {
type Radians,
pointFrom,
pointCenter,
pointRotateRads,
vectorFromPoint,
vectorNormalize,
@@ -12,466 +11,198 @@ import {
clamp,
isCloseTo,
} from "@excalidraw/math";
import { type Point } from "points-on-curve";
import {
elementCenterPoint,
getElementAbsoluteCoords,
getResizedElementAbsoluteCoords,
} from "./bounds";
import type { Bounds } from "@excalidraw/common";
import type { TransformHandleType } from "./transformHandles";
import type {
ElementsMap,
ExcalidrawElement,
ExcalidrawImageElement,
ImageCrop,
} from "./types";
import { elementCenterPoint, getElementAbsoluteCoords } from "./bounds";
import { getNextSingleWidthAndHeightFromPointer } from "./resizeElements";
import type { TransformHandleDirection } from "./transformHandles";
import type { ElementsMap, ExcalidrawImageElement, ImageCrop } from "./types";
export const MINIMAL_CROP_SIZE = 10;
/**
* Crops the image (as it was at the drag's start) as resizing it would
* resize it, as far as the image reaches.
*/
export const cropElement = (
element: ExcalidrawImageElement,
elementsMap: ElementsMap,
transformHandle: TransformHandleType,
transformHandle: TransformHandleDirection,
naturalWidth: number,
naturalHeight: number,
pointerX: number,
pointerY: number,
widthAspectRatio?: number,
{
shouldMaintainAspectRatio = false,
shouldResizeFromCenter = false,
}: {
shouldMaintainAspectRatio?: boolean;
shouldResizeFromCenter?: boolean;
} = {},
) => {
const { width, height } = element;
const { width: uncroppedWidth, height: uncroppedHeight } =
getUncroppedWidthAndHeight(element);
const naturalWidthToUncropped = naturalWidth / uncroppedWidth;
const naturalHeightToUncropped = naturalHeight / uncroppedHeight;
const croppedLeft = (element.crop?.x ?? 0) / naturalWidthToUncropped;
const croppedTop = (element.crop?.y ?? 0) / naturalHeightToUncropped;
/**
* uncropped width
* *––––––––––––––––––––––––*
* | (x,y) (natural) |
* | *–––––––* |
* | |///////| height | uncropped height
* | *–––––––* |
* | width (natural) |
* *––––––––––––––––––––––––*
*/
const rotatedPointer = pointRotateRads(
pointFrom(pointerX, pointerY),
elementCenterPoint(element, elementsMap),
-element.angle as Radians,
);
pointerX = rotatedPointer[0];
pointerY = rotatedPointer[1];
let nextWidth = element.width;
let nextHeight = element.height;
let crop: ImageCrop | null = element.crop ?? {
const { x: left, y: top } = getFlipAdjustedCropPosition(element) ?? {
x: 0,
y: 0,
width: naturalWidth,
height: naturalHeight,
};
let { nextWidth, nextHeight } = getNextSingleWidthAndHeightFromPointer(
element,
element,
transformHandle,
pointerX,
pointerY,
{ shouldResizeFromCenter },
);
// what stays put, as a fraction of the size: the opposite side (0 or 1),
// or the center (also of a side handle's other axis, which keeping the
// aspect ratio changes)
const anchorX =
shouldResizeFromCenter || !/[ew]/.test(transformHandle)
? 0.5
: transformHandle.includes("w")
? 1
: 0;
const anchorY =
shouldResizeFromCenter || !/[ns]/.test(transformHandle)
? 0.5
: transformHandle.includes("n")
? 1
: 0;
// as far as the image reaches from what stays put
const getMaxSize = (
anchor: number,
offset: number,
size: number,
uncroppedSize: number,
) => {
const before = offset + anchor * size;
const after = uncroppedSize - before;
return anchor === 0
? after
: anchor === 1
? before
: Math.min(before, after) * 2;
};
const maxWidth = getMaxSize(anchorX, left, width, uncroppedWidth);
const maxHeight = getMaxSize(anchorY, top, height, uncroppedHeight);
// (an image already smaller than the minimal size crops no smaller)
const minWidth = Math.min(MINIMAL_CROP_SIZE, width);
const minHeight = Math.min(MINIMAL_CROP_SIZE, height);
if (shouldMaintainAspectRatio) {
const ratio = width / height;
// as resizing, by a side handle's axis, or the one a corner grows most —
// but an axis dragged past what stays put has no size (rather than flips)
nextWidth = clamp(
transformHandle === "n" || transformHandle === "s"
? nextHeight * ratio
: transformHandle === "e" || transformHandle === "w"
? nextWidth
: Math.max(nextWidth, nextHeight * ratio),
Math.max(minWidth, minHeight * ratio),
Math.min(maxWidth, maxHeight * ratio),
);
nextHeight = nextWidth / ratio;
} else {
nextWidth = clamp(nextWidth, minWidth, maxWidth);
nextHeight = clamp(nextHeight, minHeight, maxHeight);
}
const x1 = anchorX * (width - nextWidth);
const y1 = anchorY * (height - nextHeight);
return cropElementToBounds(
element,
elementsMap,
naturalWidth,
naturalHeight,
[x1, y1, x1 + nextWidth, y1 + nextHeight],
);
};
/**
* Crops the image to `bounds`, relative to the element as shown (flipped).
*/
const cropElementToBounds = (
element: ExcalidrawImageElement,
elementsMap: ElementsMap,
naturalWidth: number,
naturalHeight: number,
[x1, y1, x2, y2]: Bounds,
) => {
// the image's natural pixels per element unit
const scaleX = (element.crop?.width ?? naturalWidth) / element.width;
const scaleY = (element.crop?.height ?? naturalHeight) / element.height;
const width = x2 - x1;
const height = y2 - y1;
const [centerX, centerY] = pointRotateRads(
pointFrom(element.x + (x1 + x2) / 2, element.y + (y1 + y2) / 2),
elementCenterPoint(element, elementsMap),
element.angle,
);
const crop = {
x:
(element.crop?.x ?? 0) +
(element.scale[0] === -1 ? element.width - x2 : x1) * scaleX,
y:
(element.crop?.y ?? 0) +
(element.scale[1] === -1 ? element.height - y2 : y1) * scaleY,
width: width * scaleX,
height: height * scaleY,
naturalWidth,
naturalHeight,
};
const previousCropHeight = crop.height;
const previousCropWidth = crop.width;
const isFlippedByX = element.scale[0] === -1;
const isFlippedByY = element.scale[1] === -1;
let changeInHeight = pointerY - element.y;
let changeInWidth = pointerX - element.x;
if (transformHandle.includes("n")) {
nextHeight = clamp(
element.height - changeInHeight,
MINIMAL_CROP_SIZE,
isFlippedByY ? uncroppedHeight - croppedTop : element.height + croppedTop,
);
}
if (transformHandle.includes("s")) {
changeInHeight = pointerY - element.y - element.height;
nextHeight = clamp(
element.height + changeInHeight,
MINIMAL_CROP_SIZE,
isFlippedByY ? element.height + croppedTop : uncroppedHeight - croppedTop,
);
}
if (transformHandle.includes("e")) {
changeInWidth = pointerX - element.x - element.width;
nextWidth = clamp(
element.width + changeInWidth,
MINIMAL_CROP_SIZE,
isFlippedByX ? element.width + croppedLeft : uncroppedWidth - croppedLeft,
);
}
if (transformHandle.includes("w")) {
nextWidth = clamp(
element.width - changeInWidth,
MINIMAL_CROP_SIZE,
isFlippedByX ? uncroppedWidth - croppedLeft : element.width + croppedLeft,
);
}
const updateCropWidthAndHeight = (crop: ImageCrop) => {
crop.height = nextHeight * naturalHeightToUncropped;
crop.width = nextWidth * naturalWidthToUncropped;
};
updateCropWidthAndHeight(crop);
const adjustFlipForHandle = (
handle: TransformHandleType,
crop: ImageCrop,
) => {
updateCropWidthAndHeight(crop);
if (handle.includes("n")) {
if (!isFlippedByY) {
crop.y += previousCropHeight - crop.height;
}
}
if (handle.includes("s")) {
if (isFlippedByY) {
crop.y += previousCropHeight - crop.height;
}
}
if (handle.includes("e")) {
if (isFlippedByX) {
crop.x += previousCropWidth - crop.width;
}
}
if (handle.includes("w")) {
if (!isFlippedByX) {
crop.x += previousCropWidth - crop.width;
}
}
};
switch (transformHandle) {
case "n": {
if (widthAspectRatio) {
const distanceToLeft = croppedLeft + element.width / 2;
const distanceToRight =
uncroppedWidth - croppedLeft - element.width / 2;
const MAX_WIDTH = Math.min(distanceToLeft, distanceToRight) * 2;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
adjustFlipForHandle(transformHandle, crop);
if (widthAspectRatio) {
crop.x += (previousCropWidth - crop.width) / 2;
}
break;
}
case "s": {
if (widthAspectRatio) {
const distanceToLeft = croppedLeft + element.width / 2;
const distanceToRight =
uncroppedWidth - croppedLeft - element.width / 2;
const MAX_WIDTH = Math.min(distanceToLeft, distanceToRight) * 2;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
adjustFlipForHandle(transformHandle, crop);
if (widthAspectRatio) {
crop.x += (previousCropWidth - crop.width) / 2;
}
break;
}
case "w": {
if (widthAspectRatio) {
const distanceToTop = croppedTop + element.height / 2;
const distanceToBottom =
uncroppedHeight - croppedTop - element.height / 2;
const MAX_HEIGHT = Math.min(distanceToTop, distanceToBottom) * 2;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
}
adjustFlipForHandle(transformHandle, crop);
if (widthAspectRatio) {
crop.y += (previousCropHeight - crop.height) / 2;
}
break;
}
case "e": {
if (widthAspectRatio) {
const distanceToTop = croppedTop + element.height / 2;
const distanceToBottom =
uncroppedHeight - croppedTop - element.height / 2;
const MAX_HEIGHT = Math.min(distanceToTop, distanceToBottom) * 2;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
}
adjustFlipForHandle(transformHandle, crop);
if (widthAspectRatio) {
crop.y += (previousCropHeight - crop.height) / 2;
}
break;
}
case "ne": {
if (widthAspectRatio) {
if (changeInWidth > -changeInHeight) {
const MAX_HEIGHT = isFlippedByY
? uncroppedHeight - croppedTop
: croppedTop + element.height;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
} else {
const MAX_WIDTH = isFlippedByX
? croppedLeft + element.width
: uncroppedWidth - croppedLeft;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
}
adjustFlipForHandle(transformHandle, crop);
break;
}
case "nw": {
if (widthAspectRatio) {
if (changeInWidth < changeInHeight) {
const MAX_HEIGHT = isFlippedByY
? uncroppedHeight - croppedTop
: croppedTop + element.height;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
} else {
const MAX_WIDTH = isFlippedByX
? uncroppedWidth - croppedLeft
: croppedLeft + element.width;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
}
adjustFlipForHandle(transformHandle, crop);
break;
}
case "se": {
if (widthAspectRatio) {
if (changeInWidth > changeInHeight) {
const MAX_HEIGHT = isFlippedByY
? croppedTop + element.height
: uncroppedHeight - croppedTop;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
} else {
const MAX_WIDTH = isFlippedByX
? croppedLeft + element.width
: uncroppedWidth - croppedLeft;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
}
adjustFlipForHandle(transformHandle, crop);
break;
}
case "sw": {
if (widthAspectRatio) {
if (-changeInWidth > changeInHeight) {
const MAX_HEIGHT = isFlippedByY
? croppedTop + element.height
: uncroppedHeight - croppedTop;
nextHeight = clamp(
nextWidth / widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_HEIGHT,
);
nextWidth = nextHeight * widthAspectRatio;
} else {
const MAX_WIDTH = isFlippedByX
? uncroppedWidth - croppedLeft
: croppedLeft + element.width;
nextWidth = clamp(
nextHeight * widthAspectRatio,
MINIMAL_CROP_SIZE,
MAX_WIDTH,
);
nextHeight = nextWidth / widthAspectRatio;
}
}
adjustFlipForHandle(transformHandle, crop);
break;
}
default:
break;
}
const newOrigin = recomputeOrigin(
element,
transformHandle,
nextWidth,
nextHeight,
!!widthAspectRatio,
);
// reset crop to null if we're back to orig size
if (
isCloseTo(crop.width, crop.naturalWidth) &&
isCloseTo(crop.height, crop.naturalHeight)
) {
crop = null;
}
return {
x: newOrigin[0],
y: newOrigin[1],
width: nextWidth,
height: nextHeight,
crop,
x: centerX - width / 2,
y: centerY - height / 2,
width,
height,
// reset crop to null if we're back to orig size
crop:
isCloseTo(crop.width, naturalWidth) &&
isCloseTo(crop.height, naturalHeight)
? null
: crop,
};
};
const recomputeOrigin = (
stateAtCropStart: ExcalidrawElement,
transformHandle: TransformHandleType,
width: number,
height: number,
shouldMaintainAspectRatio?: boolean,
/**
* Uncrops the image on the handle's side (a corner's two); mirrored, on the
* opposite side(s) too.
*/
export const uncropElementSides = (
element: ExcalidrawImageElement,
elementsMap: ElementsMap,
handle: TransformHandleDirection,
mirrored = false,
) => {
const [x1, y1, x2, y2] = getResizedElementAbsoluteCoords(
stateAtCropStart,
stateAtCropStart.width,
stateAtCropStart.height,
true,
if (!element.crop) {
return null;
}
const { width, height } = getUncroppedWidthAndHeight(element);
const { x: left, y: top } = getFlipAdjustedCropPosition(element)!;
const uncrops = (side: string, opposite: string) =>
handle.includes(side) || (mirrored && handle.includes(opposite));
return cropElementToBounds(
element,
elementsMap,
element.crop.naturalWidth,
element.crop.naturalHeight,
[
uncrops("w", "e") ? -left : 0,
uncrops("n", "s") ? -top : 0,
uncrops("e", "w") ? width - left : element.width,
uncrops("s", "n") ? height - top : element.height,
],
);
const startTopLeft = pointFrom(x1, y1);
const startBottomRight = pointFrom(x2, y2);
const startCenter: any = pointCenter(startTopLeft, startBottomRight);
const [newBoundsX1, newBoundsY1, newBoundsX2, newBoundsY2] =
getResizedElementAbsoluteCoords(stateAtCropStart, width, height, true);
const newBoundsWidth = newBoundsX2 - newBoundsX1;
const newBoundsHeight = newBoundsY2 - newBoundsY1;
// Calculate new topLeft based on fixed corner during resize
let newTopLeft = [...startTopLeft] as [number, number];
if (["n", "w", "nw"].includes(transformHandle)) {
newTopLeft = [
startBottomRight[0] - Math.abs(newBoundsWidth),
startBottomRight[1] - Math.abs(newBoundsHeight),
];
}
if (transformHandle === "ne") {
const bottomLeft = [startTopLeft[0], startBottomRight[1]];
newTopLeft = [bottomLeft[0], bottomLeft[1] - Math.abs(newBoundsHeight)];
}
if (transformHandle === "sw") {
const topRight = [startBottomRight[0], startTopLeft[1]];
newTopLeft = [topRight[0] - Math.abs(newBoundsWidth), topRight[1]];
}
if (shouldMaintainAspectRatio) {
if (["s", "n"].includes(transformHandle)) {
newTopLeft[0] = startCenter[0] - newBoundsWidth / 2;
}
if (["e", "w"].includes(transformHandle)) {
newTopLeft[1] = startCenter[1] - newBoundsHeight / 2;
}
}
// adjust topLeft to new rotation point
const angle = stateAtCropStart.angle;
const rotatedTopLeft = pointRotateRads(newTopLeft, startCenter, angle);
const newCenter: Point = [
newTopLeft[0] + Math.abs(newBoundsWidth) / 2,
newTopLeft[1] + Math.abs(newBoundsHeight) / 2,
];
const rotatedNewCenter = pointRotateRads(newCenter, startCenter, angle);
newTopLeft = pointRotateRads(
rotatedTopLeft,
rotatedNewCenter,
-angle as Radians,
);
const newOrigin = [...newTopLeft];
newOrigin[0] += stateAtCropStart.x - newBoundsX1;
newOrigin[1] += stateAtCropStart.y - newBoundsY1;
return newOrigin;
};
// refer to https://link.excalidraw.com/l/6rfy1007QOo/6stx5PmRn0k
+177 -35
View File
@@ -47,6 +47,7 @@ import { mutateElement, newElementWith } from "./mutateElement";
import { getBoundTextElementId, redrawTextBoundingBox } from "./textElement";
import {
hasBoundTextElement,
isArrowElement,
isBindableElement,
isBoundToContainer,
isTextElement,
@@ -1442,6 +1443,48 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
}
try {
// Whether this delta results in a visible change is decided from the
// *applied* result, not from the property patches: binding repair and
// layout (text bounding boxes, bound arrows) run below and can move
// elements the delta never named, and an `isDeleted` flip or a
// `boundElements` edit is not visible by itself — deleting a note's
// empty label is the canonical case. History relies on this answer to
// skip such entries on undo/redo (see `History`'s apply loop).
//
// `idsToCheck` is every element whose "before" and "after" get
// compared: 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 added
// for its container brings in its own label in turn. The dev/test
// assertion after the redraw verifies the set is complete.
const idsToCheck = new Set(changedElements.keys());
// Unchanged elements are shared between `elements` and `nextElements`,
// and layout mutates them in place — their "before" must be a shallow
// copy taken now. Changed elements already have a fresh instance in
// `nextElements`, so the instance in `elements` is their "before" as
// is. Only `idsToCheck` is saved; the whole scene is never copied.
const previousElements = new Map<string, OrderedExcalidrawElement>();
for (const id of idsToCheck) {
const previous = elements.get(id);
const next = nextElements.get(id);
for (const element of [previous, next]) {
if (element) {
if (isTextElement(element) && element.containerId) {
idsToCheck.add(element.containerId);
}
for (const binding of element.boundElements ?? []) {
idsToCheck.add(binding.id);
}
}
}
if (previous) {
previousElements.set(
id,
previous === next ? { ...previous } : previous,
);
}
}
// the following reorder performs mutations, but only on new instances of changed elements,
// unless something goes really bad and it fallbacks to fixing all invalid indices
nextElements = ElementsDelta.reorderElements(
@@ -1450,8 +1493,53 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
flags,
);
// Guard for `idsToCheck`: layout bumps the version of everything it
// mutates, so an element whose version moved during the redraw but was
// never collected is a layout dependency the expansion above does not
// know about — and a visible change that undo would silently skip.
// Fail loudly instead (dev and tests only; this is a scene-wide pass).
const versionsBeforeRedraw =
isTestEnv() || isDevEnv()
? new Map(
Array.from(nextElements, ([id, element]) => [
id,
element.version,
]),
)
: undefined;
ElementsDelta.redrawElements(nextElements, changedElements);
if (versionsBeforeRedraw) {
for (const [id, element] of nextElements) {
if (
versionsBeforeRedraw.get(id) !== element.version &&
!idsToCheck.has(id)
) {
throw new Error(
`Redrawn element "${id}" is missing from idsToCheck`,
);
}
}
}
if (!flags.containsVisibleDifference) {
for (const id of idsToCheck) {
if (
ElementsDelta.checkForVisibleDifference(
previousElements.get(id),
nextElements.get(id),
previousElements,
nextElements,
)
) {
flags.containsVisibleDifference = true;
break;
}
}
}
} catch (e) {
flags.containsVisibleDifference = true;
console.error(
`Couldn't mutate elements after applying elements change`,
e,
@@ -1460,9 +1548,9 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
if (isTestEnv() || isDevEnv()) {
throw e;
}
} finally {
return [nextElements, flags.containsVisibleDifference];
}
return [nextElements, flags.containsVisibleDifference];
}
public squash(delta: ElementsDelta): this {
@@ -1625,12 +1713,8 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
if (element) {
// as the element was brought from the snapshot, it automatically results in a possible zindex difference
// (whether it is *visible* is decided in `applyTo`, from the applied result)
flags.containsZindexDifference = true;
// as the element was force deleted, we need to check if adding it back results in a visible change
if (!partial.isDeleted || (partial.isDeleted && !element.isDeleted)) {
flags.containsVisibleDifference = true;
}
} else {
// not in elements, not in snapshot? element might have been added remotely!
element = newElementWith(
@@ -1687,17 +1771,8 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
});
}
if (!flags.containsVisibleDifference) {
// strip away fractional index, as even if it would be different, it doesn't have to result in visible change
const { index, ...rest } = directlyApplicablePartial;
const containsVisibleDifference = ElementsDelta.checkForVisibleDifference(
element,
rest,
);
flags.containsVisibleDifference = containsVisibleDifference;
}
// visibility is not decided here: `applyTo` compares the applied result
// once layout has run, so that its effects count too
if (!flags.containsZindexDifference) {
flags.containsZindexDifference =
delta.deleted.index !== delta.inserted.index;
@@ -1707,29 +1782,96 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
}
/**
* Check for visible changes regardless of whether they were removed, added or updated.
* Whether an element looks different after the delta — and the layout that
* followed it — was applied. The input to history's "skip entries with no
* visible change" loop.
*
* Both sides are first reduced to what actually paints:
* - a missing or deleted element paints nothing;
* - an empty text element paints nothing either — unless it carries arrow
* bindings (an arrow may end at it) or sits on an arrow (an empty label
* still cuts the arrow's gap);
* so an empty label's deletion or restoration compares as nothing against
* nothing. Two painting elements are then compared property by property:
* - `version`, `versionNonce`, `updated`, `created` are metadata, and
* `index` is covered by the separate z-order check (`reorderElements`);
* - `boundElements` is compared as `type:id` references with references to
* empty labels dropped, so adding or removing an empty label's reference
* is not visible on its own, and binding repair that rebuilt equal
* objects is not either;
* - everything else counts. Nested arrays (`points`, binding fixed points)
* compare by reference, which can only over-report a change — the safe
* direction, where undo stops one entry early.
*
* `previousElements` holds only `idsToCheck` (see `applyTo`); the label
* lookups it serves are for elements whose labels are in that set.
*/
private static checkForVisibleDifference(
element: OrderedExcalidrawElement,
partial: ElementPartial,
previous: OrderedExcalidrawElement | undefined,
next: OrderedExcalidrawElement | undefined,
previousElements: ReadonlyMap<string, OrderedExcalidrawElement>,
nextElements: ReadonlyMap<string, OrderedExcalidrawElement>,
) {
if (element.isDeleted && partial.isDeleted !== false) {
// when it's deleted and partial is not false, it cannot end up with a visible change
return false;
const visibleElement = (
element: OrderedExcalidrawElement | undefined,
elements: ReadonlyMap<string, OrderedExcalidrawElement>,
) => {
if (!element || element.isDeleted) {
return null;
}
if (
isTextElement(element) &&
!element.text.trim() &&
!element.boundElements?.length &&
!isArrowElement(elements.get(element.containerId ?? ""))
) {
return null;
}
return element;
};
const before = visibleElement(previous, previousElements);
const after = visibleElement(next, nextElements);
if (!before || !after) {
return before !== after;
}
if (element.isDeleted && partial.isDeleted === false) {
// when we add an element, it results in a visible change
return true;
}
const visibleBindings = (
element: OrderedExcalidrawElement,
elements: ReadonlyMap<string, OrderedExcalidrawElement>,
) =>
(element.boundElements ?? [])
.filter((binding) => {
const label = elements.get(binding.id);
return (
binding.type !== "text" ||
isArrowElement(element) ||
!label ||
!isTextElement(label) ||
!!label.text.trim()
);
})
.map(({ id, type }) => `${type}:${id}`);
if (element.isDeleted === false && partial.isDeleted) {
// when we remove an element, it results in a visible change
return true;
}
// check for any difference on a visible element
return Delta.isRightDifferent(element, partial);
return Delta.getDifferences(before, after).some((key) => {
switch (key) {
// Ordering is checked separately; the remaining fields are metadata.
case "index":
case "version":
case "versionNonce":
case "updated":
case "created":
return false;
case "boundElements":
return !isShallowEqual(
visibleBindings(before, previousElements),
visibleBindings(after, nextElements),
);
default:
return true;
}
});
}
/**
+31 -1
View File
@@ -2,6 +2,7 @@ import {
curvePointDistance,
distanceToLineSegment,
pointRotateRads,
polygonIncludesPointNonZero,
} from "@excalidraw/math";
import { ellipse, ellipseDistanceFromPoint } from "@excalidraw/math/ellipse";
@@ -34,6 +35,7 @@ export const distanceToElement = (
switch (element.type) {
case "selection":
case "rectangle":
case "stickynote":
case "image":
case "text":
case "iframe":
@@ -47,8 +49,9 @@ export const distanceToElement = (
return distanceToEllipseElement(element, elementsMap, p);
case "line":
case "arrow":
case "freedraw":
return distanceToLinearOrFreeDraElement(element, elementsMap, p);
case "freedraw":
return distanceToFreeDrawElement(element, elementsMap, p);
}
};
@@ -141,3 +144,30 @@ const distanceToLinearOrFreeDraElement = (
...curves.map((a) => curvePointDistance(a, p)),
);
};
/**
* Returns the distance of a point to a freedraw element.
*
* @param element The freedraw element
* @param p The point to consider
* @returns 0 if the point is within the inked area, otherwise the euclidean
* distance to the stroke outline
*/
const distanceToFreeDrawElement = (
element: ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
p: GlobalPoint,
) => {
const [lines] = deconstructLinearOrFreeDrawElement(element, elementsMap);
if (lines.length === 0) {
return Infinity;
}
const polygon = lines.map((line) => line[0]);
if (polygonIncludesPointNonZero(p, polygon)) {
return 0;
}
return Math.min(...lines.map((s) => distanceToLineSegment(p, s)));
};
+17 -20
View File
@@ -15,7 +15,11 @@ import type {
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { unbindBindingElement, updateBoundElements } from "./binding";
import {
getSimultaneouslyUpdatedElementIds,
unbindBindingElement,
updateBoundElements,
} from "./binding";
import { getCommonBounds } from "./bounds";
import { getPerfectElementSize } from "./sizeHelpers";
import { getBoundTextElement } from "./textElement";
@@ -103,23 +107,14 @@ export const dragSelectedElements = (
gridSize,
);
const elementsToUpdateIds = new Set(
Array.from(elementsToUpdate, (el) => el.id),
// one array for the whole update, so that every element's bound-arrow
// update and the unbinding checks share its cached id set
const elementsToUpdateArray = Array.from(elementsToUpdate);
const elementsToUpdateIds = getSimultaneouslyUpdatedElementIds(
elementsToUpdateArray,
);
elementsToUpdate.forEach((element) => {
const isArrow = !isArrowElement(element);
const isStartBoundElementSelected =
isArrow ||
(element.startBinding
? elementsToUpdateIds.has(element.startBinding.elementId)
: false);
const isEndBoundElementSelected =
isArrow ||
(element.endBinding
? elementsToUpdateIds.has(element.endBinding.elementId)
: false);
if (!isArrowElement(element)) {
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
@@ -137,13 +132,12 @@ export const dragSelectedElements = (
);
}
updateBoundElements(element, scene, {
simultaneouslyUpdated: Array.from(elementsToUpdate),
simultaneouslyUpdated: elementsToUpdateArray,
});
} else if (
// NOTE: Add a little initial drag to the arrow dragging when the arrow
// is the single element being dragged to avoid accidentally unbinding
// the arrow when the user just wants to select it.
elementsToUpdate.size > 1 ||
Math.max(Math.abs(adjustedOffset.x), Math.abs(adjustedOffset.y)) >
DRAGGING_THRESHOLD ||
@@ -151,9 +145,12 @@ export const dragSelectedElements = (
) {
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
const shouldUnbindStart =
element.startBinding && !isStartBoundElementSelected;
const shouldUnbindEnd = element.endBinding && !isEndBoundElementSelected;
const shouldUnbindStart = element.startBinding
? !elementsToUpdateIds.has(element.startBinding.elementId)
: true;
const shouldUnbindEnd = element.endBinding
? !elementsToUpdateIds.has(element.endBinding.elementId)
: true;
if (shouldUnbindStart || shouldUnbindEnd) {
// NOTE: Moving the bound arrow should unbind it, otherwise we would
// have weird situations, like 0 lenght arrow when the user moves
+187 -4
View File
@@ -30,6 +30,7 @@ import { bumpVersion } from "./mutateElement";
import {
hasBoundTextElement,
isArrowElement,
isBoundToContainer,
isFrameLikeElement,
} from "./typeChecks";
@@ -38,16 +39,54 @@ import { getBoundTextElement, getContainerElement } from "./textElement";
import { fixDuplicatedBindingsAfterDuplication } from "./binding";
import { ShapeCache } from "./shape";
import { isNonDeletedElement } from ".";
import type { ElementUpdate } from "./mutateElement";
import type {
ElementsMap,
ExcalidrawArrowElement,
ExcalidrawElement,
GroupId,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
} from "./types";
/**
* Lookups supplied to the host's `props.onDuplicate`, covering just the
* elements taking part in the duplication.
*/
export type OnDuplicateData = {
/** the duplicates, by their id */
duplicateElements: ReadonlyMap<ExcalidrawElement["id"], ExcalidrawElement>;
/**
* The elements the duplicates were made from, by their id.
*
* On paste and library insert these are the inserted elements, which aren't
* part of the scene (though they may share ids with the scene elements they
* were copied from).
*/
originalElements: ReadonlyMap<ExcalidrawElement["id"], ExcalidrawElement>;
/**
* id of an original -> id of its duplicate (e.g. to remap element ids you
* keep in `customData`, which the duplicate copied from its original)
*/
origIdToDuplicateId: ReadonlyMap<
ExcalidrawElement["id"],
ExcalidrawElement["id"]
>;
/**
* id of a duplicate -> id of its original (e.g. to look up the original in
* `originalElements` while modifying the duplicate)
*/
duplicateIdToOrigId: ReadonlyMap<
ExcalidrawElement["id"],
ExcalidrawElement["id"]
>;
};
/**
* Duplicate an element, often used in the alt-drag operation.
* Note that this method has gotten a bit complicated since the
@@ -75,6 +114,7 @@ export const duplicateElement = <TElement extends ExcalidrawElement>(
copy.id = randomId();
copy.updated = getUpdatedTimestamp();
copy.created = copy.updated;
if (randomizeSeed) {
copy.seed = randomInteger();
bumpVersion(copy);
@@ -166,11 +206,12 @@ export const duplicateElements = (
ExcalidrawElement["id"],
ExcalidrawElement["id"]
>();
const duplicateIdToOrigElement = new Map<
const duplicateIdToOrigId = new Map<
ExcalidrawElement["id"],
ExcalidrawElement
ExcalidrawElement["id"]
>();
const duplicateElementsMap = new Map<string, NonDeletedExcalidrawElement>();
const origElementsMap = new Map<ExcalidrawElement["id"], ExcalidrawElement>();
const elementsMap = arrayToMap(elements) as ElementsMap;
const _idsOfElementsToDuplicate =
opts.type === "in-place"
@@ -230,8 +271,9 @@ export const duplicateElements = (
processedIds.set(newElement.id, true);
duplicateElementsMap.set(newElement.id, newElement);
origElementsMap.set(element.id, element);
origIdToDuplicateId.set(element.id, newElement.id);
duplicateIdToOrigElement.set(newElement.id, element);
duplicateIdToOrigId.set(newElement.id, element.id);
origElements.push(element);
duplicatedElements.push(newElement);
@@ -410,7 +452,9 @@ export const duplicateElements = (
if (opts.overrides) {
for (const duplicateElement of duplicatedElements) {
const origElement = duplicateIdToOrigElement.get(duplicateElement.id);
const origElement = origElementsMap.get(
duplicateIdToOrigId.get(duplicateElement.id)!,
);
if (origElement) {
Object.assign(
duplicateElement,
@@ -427,11 +471,150 @@ export const duplicateElements = (
return {
duplicatedElements,
duplicateElementsMap,
origElementsMap,
elementsWithDuplicates,
origIdToDuplicateId,
duplicateIdToOrigId,
};
};
/**
* Folds the elements returned by the host (`props.onDuplicate`) back into the
* duplicates the editor created, so that everything that follows (frame
* assignment, bound text redraw, selection, alt-drag handover) can keep
* working with the editor's own objects, whether the host mutated the
* duplicates or returned new objects for them.
*
* - A returned element with a duplicate's id is shallow-merged into that
* duplicate, which takes its place in the returned array. Properties the
* host omits are kept, so that a partial element can't invalidate the
* duplicate. Safe only because the duplicates are fresh (not in the scene or
* the store snapshot yet), which is why nothing but the passed duplicates is
* ever merged into. Since the merge goes around `mutateElement`, what may
* have been cached for the duplicate by then is invalidated here.
* - A duplicate missing from the returned array (or returned as deleted) is
* vetoed. So is the bound text of a vetoed container. What the remaining
* duplicates reference of the vetoed ones is cleared, as if those were never
* part of the duplication (see `fixDuplicatedBindingsAfterDuplication`).
* - Any other returned element is used as is (existing elements must not be
* mutated, so the host replaces them).
* - `false` vetoes all the duplicates.
*
* @returns next elements, and the duplicates that weren't vetoed
*/
export const reconcileDuplicatedElements = <
TDuplicate extends ExcalidrawElement,
>(
/** what the host returned from `props.onDuplicate`, if anything */
hostElements: readonly ExcalidrawElement[] | void | false,
/** elements that were passed to the host */
nextElements: ExcalidrawElement[],
duplicatedElements: TDuplicate[],
): {
elements: ExcalidrawElement[];
duplicatedElements: TDuplicate[];
} => {
if (hostElements === false) {
return { elements: nextElements, duplicatedElements: [] };
}
if (!hostElements) {
return { elements: nextElements, duplicatedElements };
}
const duplicatesMap = arrayToMap(duplicatedElements);
// (if a duplicate is returned more than once, the last one wins)
const hostDuplicates = new Map<ExcalidrawElement["id"], ExcalidrawElement>();
for (const element of hostElements) {
if (duplicatesMap.has(element.id)) {
hostDuplicates.set(element.id, element);
}
}
// merge first, so that everything below sees the duplicates as the host
// wants them (what the host returned may be partial)
const survivedIds = new Set<ExcalidrawElement["id"]>();
for (const [id, element] of hostDuplicates) {
const duplicate = duplicatesMap.get(id)!;
if (element !== duplicate) {
Object.assign(duplicate, element);
// The duplicate may have been measured already (e.g. to resolve the
// frame it's pasted into), and we're going around `mutateElement`.
// The shape is cached by identity, the bounds by version.
ShapeCache.delete(duplicate);
bumpVersion(duplicate);
}
if (!duplicate.isDeleted) {
survivedIds.add(id);
}
}
const isVetoed = (id: ExcalidrawElement["id"]) =>
duplicatesMap.has(id) && !survivedIds.has(id);
for (const id of survivedIds) {
const duplicate = duplicatesMap.get(id)!;
if (isBoundToContainer(duplicate) && isVetoed(duplicate.containerId)) {
survivedIds.delete(id);
}
}
const elements: ExcalidrawElement[] = [];
for (const element of hostElements) {
const duplicate = duplicatesMap.get(element.id);
if (!duplicate) {
elements.push(element);
} else if (
survivedIds.has(element.id) &&
hostDuplicates.get(element.id) === element
) {
elements.push(duplicate);
}
}
if (survivedIds.size === duplicatedElements.length) {
return { elements, duplicatedElements };
}
const survivedDuplicates = duplicatedElements.filter((duplicate) =>
survivedIds.has(duplicate.id),
);
for (const duplicate of survivedDuplicates) {
const updates: Mutable<ElementUpdate<ExcalidrawArrowElement>> = {};
if (duplicate.boundElements?.some((binding) => isVetoed(binding.id))) {
updates.boundElements = duplicate.boundElements.filter(
(binding) => !isVetoed(binding.id),
);
}
if (duplicate.frameId && isVetoed(duplicate.frameId)) {
updates.frameId = null;
}
if (isArrowElement(duplicate)) {
if (
duplicate.startBinding &&
isVetoed(duplicate.startBinding.elementId)
) {
updates.startBinding = null;
}
if (duplicate.endBinding && isVetoed(duplicate.endBinding.elementId)) {
updates.endBinding = null;
}
}
Object.assign(duplicate, updates);
}
return { elements, duplicatedElements: survivedDuplicates };
};
// Simplified deep clone for the purpose of cloning ExcalidrawElement.
//
// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,
+26 -31
View File
@@ -21,6 +21,7 @@ import {
getSizeFromPoints,
isDevEnv,
arrayToMap,
DEFAULT_ZOOM,
} from "@excalidraw/common";
import type { AppState } from "@excalidraw/excalidraw/types";
@@ -30,8 +31,7 @@ import {
getHeadingForElbowArrowSnap,
getGlobalFixedPointForBindableElement,
getBindingGap,
maxBindingDistance_simple,
BASE_BINDING_GAP_ELBOW,
BASE_BINDING_GAP,
} from "./binding";
import { distanceToElement } from "./distance";
import {
@@ -1217,24 +1217,20 @@ const getElbowArrowData = (
GlobalPoint
>(nextPoints[nextPoints.length - 1], vector(arrow.x, arrow.y));
// NOTE: updates coming through `mutateElement` don't carry the zoom, so
// those fall back to the zoom=1 binding distance
const zoom = options?.zoom ?? DEFAULT_ZOOM;
let hoveredStartElement = null;
let hoveredEndElement = null;
if (options?.isDragging && options?.isBindingEnabled !== false) {
const elements = Array.from(elementsMap.values());
hoveredStartElement =
getHoveredElement(
origStartGlobalPoint,
elementsMap,
elements,
options?.zoom,
) || null;
getHoveredElement(origStartGlobalPoint, elementsMap, elements, zoom) ||
null;
hoveredEndElement =
getHoveredElement(
origEndGlobalPoint,
elementsMap,
elements,
options?.zoom,
) || null;
getHoveredElement(origEndGlobalPoint, elementsMap, elements, zoom) ||
null;
} else {
hoveredStartElement = arrow.startBinding
? getBindableElementForId(arrow.startBinding.elementId, elementsMap) ||
@@ -1256,6 +1252,7 @@ const getElbowArrowData = (
"start",
arrow.startBinding?.fixedPoint,
origStartGlobalPoint,
zoom,
hoveredStartElement,
elementsMap,
options?.isDragging,
@@ -1273,6 +1270,7 @@ const getElbowArrowData = (
"end",
arrow.endBinding?.fixedPoint,
origEndGlobalPoint,
zoom,
hoveredEndElement,
elementsMap,
options?.isDragging,
@@ -1285,7 +1283,7 @@ const getElbowArrowData = (
hoveredStartElement,
origStartGlobalPoint,
elementsMap,
options?.zoom,
zoom,
);
const endHeading = getBindPointHeading(
endGlobalPoint,
@@ -1293,7 +1291,7 @@ const getElbowArrowData = (
hoveredEndElement,
origEndGlobalPoint,
elementsMap,
options?.zoom,
zoom,
);
const startPointBounds = [
startGlobalPoint[0] - 2,
@@ -1314,8 +1312,8 @@ const getElbowArrowData = (
offsetFromHeading(
startHeading,
arrow.startArrowhead
? getBindingGap(hoveredStartElement, { elbowed: true }) * 6
: getBindingGap(hoveredStartElement, { elbowed: true }) * 2,
? getBindingGap(hoveredStartElement) * 6
: getBindingGap(hoveredStartElement) * 2,
1,
),
)
@@ -1327,8 +1325,8 @@ const getElbowArrowData = (
offsetFromHeading(
endHeading,
arrow.endArrowhead
? getBindingGap(hoveredEndElement, { elbowed: true }) * 6
: getBindingGap(hoveredEndElement, { elbowed: true }) * 2,
? getBindingGap(hoveredEndElement) * 6
: getBindingGap(hoveredEndElement) * 2,
1,
),
)
@@ -1375,8 +1373,8 @@ const getElbowArrowData = (
? 0
: BASE_PADDING -
(arrow.startArrowhead
? BASE_BINDING_GAP_ELBOW * 6
: BASE_BINDING_GAP_ELBOW * 2),
? BASE_BINDING_GAP * 6
: BASE_BINDING_GAP * 2),
BASE_PADDING,
),
boundsOverlap
@@ -1391,8 +1389,8 @@ const getElbowArrowData = (
? 0
: BASE_PADDING -
(arrow.endArrowhead
? BASE_BINDING_GAP_ELBOW * 6
: BASE_BINDING_GAP_ELBOW * 2),
? BASE_BINDING_GAP * 6
: BASE_BINDING_GAP * 2),
BASE_PADDING,
),
boundsOverlap,
@@ -2218,6 +2216,7 @@ const getGlobalPoint = (
startOrEnd: "start" | "end",
fixedPointRatio: [number, number] | undefined | null,
initialPoint: GlobalPoint,
zoom: AppState["zoom"],
element?: ExcalidrawBindableElement | null,
elementsMap?: ElementsMap,
isDragging?: boolean,
@@ -2231,6 +2230,7 @@ const getGlobalPoint = (
element,
startOrEnd,
elementsMap,
zoom,
undefined,
isMidpointSnappingEnabled,
);
@@ -2282,14 +2282,9 @@ const getHoveredElement = (
origPoint: GlobalPoint,
elementsMap: NonDeletedSceneElementsMap,
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
zoom?: AppState["zoom"],
zoom: AppState["zoom"],
) => {
return getHoveredElementForBinding(
origPoint,
elements,
elementsMap,
maxBindingDistance_simple(zoom),
);
return getHoveredElementForBinding(origPoint, elements, elementsMap, zoom);
};
const gridAddressesEqual = (a: GridAddress, b: GridAddress): boolean =>
+1 -1
View File
@@ -23,7 +23,7 @@ type IframeDataWithSandbox = MarkRequired<IframeData, "sandbox">;
const embeddedLinkCache = new Map<string, IframeDataWithSandbox>();
const RE_YOUTUBE =
/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)/;
/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|live\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)/;
const RE_VIMEO =
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
+29 -6
View File
@@ -25,7 +25,11 @@ import {
} from "./heading";
import { LinearElementEditor } from "./linearElementEditor";
import { mutateElement } from "./mutateElement";
import { newArrowElement, newElement } from "./newElement";
import {
newArrowElement,
newElement,
newStickyNoteElement,
} from "./newElement";
import { aabbForElement } from "./bounds";
import { elementsAreInFrameBounds, elementOverlapsWithFrame } from "./frame";
import {
@@ -230,8 +234,7 @@ const cloneFlowchartNode = (
x: number,
y: number,
) => {
const node = newElement({
type: template.type,
const commonNodeProps = {
x,
y,
width: template.width,
@@ -244,7 +247,19 @@ const cloneFlowchartNode = (
opacity: template.opacity,
fillStyle: template.fillStyle,
strokeStyle: template.strokeStyle,
});
};
const node =
template.type === "stickynote"
? newStickyNoteElement({
type: "stickynote",
...commonNodeProps,
baseHeight: template.baseHeight,
})
: newElement({
type: template.type,
...commonNodeProps,
});
invariant(
isFlowchartNodeElement(node),
@@ -254,7 +269,7 @@ const cloneFlowchartNode = (
return node;
};
const addNewNodes = (
export const addNewNodes = (
startNode: NonDeleted<ExcalidrawFlowchartNodeElement>,
appState: AppState,
direction: LinkDirection,
@@ -376,8 +391,16 @@ const createBindingArrow = (
"orbit",
"start",
scene,
appState.zoom,
);
bindBindingElement(
bindingArrow,
endBindingElement,
"orbit",
"end",
scene,
appState.zoom,
);
bindBindingElement(bindingArrow, endBindingElement, "orbit", "end", scene);
const changedElements = new Map<string, OrderedExcalidrawElement>();
changedElements.set(
+51 -21
View File
@@ -1,7 +1,8 @@
import { arrayToMap } from "@excalidraw/common";
import { arrayToMap, type Bounds } from "@excalidraw/common";
import {
isPointWithinBounds,
pointFrom,
PRECISION,
segmentsIntersectAt,
} from "@excalidraw/math";
@@ -13,7 +14,10 @@ import type {
import type { ReadonlySetLike } from "@excalidraw/common/utility-types";
import { getElementsWithinSelection, getSelectedElements } from "./selection";
import {
getSelectedElements,
shouldIgnoreElementFromSelection,
} from "./selection";
import { getElementsInGroup, selectGroupsFromGivenElements } from "./groups";
import {
@@ -23,6 +27,7 @@ import {
doBoundsIntersect,
getElementBounds,
boundsContainBounds,
elementsOverlappingBBox,
} from "./bounds";
import { mutateElement } from "./mutateElement";
import { getBoundTextElement, getContainerElement } from "./textElement";
@@ -90,13 +95,34 @@ export function isElementIntersectingFrame(
return intersecting;
}
/**
* What's in the frame: to a hair beyond its edges, which snapping it to an
* element's (or an element to its) leaves the element at.
*/
const getFrameInnerBounds = (
frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap,
): Bounds => {
const [x1, y1, x2, y2] = getElementBounds(frame, elementsMap);
return [x1 - PRECISION, y1 - PRECISION, x2 + PRECISION, y2 + PRECISION];
};
export const getElementsCompletelyInFrame = (
elements: readonly ExcalidrawElement[],
frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap,
) =>
omitGroupsContainingFrameLikes(
getElementsWithinSelection(elements, frame, elementsMap, false),
// by their outlines (as the frame's other bounds checks), so that a frame
// snapped to an element's edges contains it
elementsOverlappingBBox({
elements,
elementsMap,
bounds: getFrameInnerBounds(frame, elementsMap),
type: "contain",
shouldIgnoreElementFromSelection,
includeStroke: false,
}),
).filter(
(element) =>
(!isFrameLikeElement(element) && !element.frameId) ||
@@ -129,7 +155,7 @@ export const elementsAreInFrameBounds = (
frame: ExcalidrawFrameLikeElement,
elementsMap: ElementsMap,
) => {
const [frameX1, frameY1, frameX2, frameY2] = getElementAbsoluteCoords(
const [frameX1, frameY1, frameX2, frameY2] = getFrameInnerBounds(
frame,
elementsMap,
);
@@ -919,6 +945,21 @@ export const shouldApplyFrameClip = (
return false;
}
// a frame's children are clipped to it (as in SVG exports): one inside it
// may still reach out of it with its stroke. Only those being dragged are
// checked (as their drop will be), the rest are in it as they stand.
if (element.frameId === frame.id) {
const shouldClip = isElementInFrame(element, elementsMap, appState, {
targetFrame: frame,
checkedGroups,
});
for (const groupId of element.groupIds) {
checkedGroups?.set(groupId, shouldClip);
}
return shouldClip;
}
// for individual elements, only clip when the element is
// a. overlapping with the frame, or
// b. containing the frame, for example when an element is used as a background
@@ -935,28 +976,17 @@ export const shouldApplyFrameClip = (
return true;
}
// if an element is outside the frame, but is part of a group that has some elements
// if an element is outside the frame, but is part of a group being dragged
// "in" the frame, we should clip the element
if (
!shouldClipElementItself &&
appState.selectedElementsAreBeingDragged &&
element.groupIds.length > 0 &&
!elementsAreInFrameBounds([element], frame, elementsMap)
) {
let shouldClip = false;
// if no elements are being dragged, we can skip the geometry check
// because we know if the element is in the given frame or not
if (!appState.selectedElementsAreBeingDragged) {
shouldClip = element.frameId === frame.id;
for (const groupId of element.groupIds) {
checkedGroups?.set(groupId, shouldClip);
}
} else {
shouldClip = isElementInFrame(element, elementsMap, appState, {
targetFrame: frame,
checkedGroups,
});
}
const shouldClip = isElementInFrame(element, elementsMap, appState, {
targetFrame: frame,
checkedGroups,
});
for (const groupId of element.groupIds) {
checkedGroups?.set(groupId, shouldClip);
-149
View File
@@ -1,16 +1,12 @@
import type {
AppClassProperties,
AppState,
InteractiveCanvasAppState,
} from "@excalidraw/excalidraw/types";
import type { Mutable } from "@excalidraw/common/utility-types";
import { getBoundTextElement } from "./textElement";
import { isBoundToContainer } from "./typeChecks";
import { makeNextSelectedElementIds, getSelectedElements } from "./selection";
import type {
GroupId,
ExcalidrawElement,
@@ -63,151 +59,6 @@ export const selectGroup = (
};
};
export const selectGroupsForSelectedElements = (function () {
type SelectGroupsReturnType = Pick<
InteractiveCanvasAppState,
"selectedGroupIds" | "editingGroupId" | "selectedElementIds"
>;
let lastSelectedElements: readonly NonDeletedExcalidrawElement[] | null =
null;
let lastElements: readonly NonDeletedExcalidrawElement[] | null = null;
let lastReturnValue: SelectGroupsReturnType | null = null;
const _selectGroups = (
selectedElements: readonly NonDeletedExcalidrawElement[],
elements: readonly NonDeletedExcalidrawElement[],
appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
prevAppState: InteractiveCanvasAppState,
): SelectGroupsReturnType => {
if (
lastReturnValue !== undefined &&
elements === lastElements &&
selectedElements === lastSelectedElements &&
appState.editingGroupId === lastReturnValue?.editingGroupId
) {
return lastReturnValue;
}
const selectedGroupIds: Record<GroupId, boolean> = {};
// Gather all the groups withing selected elements
for (const selectedElement of selectedElements) {
let groupIds = selectedElement.groupIds;
if (appState.editingGroupId) {
// handle the case where a group is nested within a group
const indexOfEditingGroup = groupIds.indexOf(appState.editingGroupId);
if (indexOfEditingGroup > -1) {
groupIds = groupIds.slice(0, indexOfEditingGroup);
}
}
if (groupIds.length > 0) {
const lastSelectedGroup = groupIds[groupIds.length - 1];
selectedGroupIds[lastSelectedGroup] = true;
}
}
// Gather all the elements within selected groups
const groupElementsIndex: Record<GroupId, string[]> = {};
const selectedElementIdsInGroups = elements.reduce(
(acc: Record<string, true>, element) => {
if (element.isDeleted) {
return acc;
}
const groupId = element.groupIds.find((id) => selectedGroupIds[id]);
if (groupId) {
acc[element.id] = true;
// Populate the index
if (!Array.isArray(groupElementsIndex[groupId])) {
groupElementsIndex[groupId] = [element.id];
} else {
groupElementsIndex[groupId].push(element.id);
}
}
return acc;
},
{},
);
for (const groupId of Object.keys(groupElementsIndex)) {
// If there is one element in the group, and the group is selected or it's being edited, it's not a group
if (groupElementsIndex[groupId].length < 2) {
if (selectedGroupIds[groupId]) {
selectedGroupIds[groupId] = false;
}
}
}
lastElements = elements;
lastSelectedElements = selectedElements;
lastReturnValue = {
editingGroupId: appState.editingGroupId,
selectedGroupIds,
selectedElementIds: makeNextSelectedElementIds(
{
...appState.selectedElementIds,
...selectedElementIdsInGroups,
},
prevAppState,
),
};
return lastReturnValue;
};
/**
* When you select an element, you often want to actually select the whole group it's in, unless
* you're currently editing that group.
*/
const selectGroupsForSelectedElements = (
appState: Pick<AppState, "selectedElementIds" | "editingGroupId">,
elements: readonly NonDeletedExcalidrawElement[],
prevAppState: InteractiveCanvasAppState,
/**
* supply null in cases where you don't have access to App instance and
* you don't care about optimizing selectElements retrieval
*/
app: AppClassProperties | null,
): Mutable<
Pick<
InteractiveCanvasAppState,
"selectedGroupIds" | "editingGroupId" | "selectedElementIds"
>
> => {
const selectedElements = app
? app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
// supplying elements explicitly in case we're passed non-state elements
elements,
})
: getSelectedElements(elements, appState);
if (!selectedElements.length) {
return {
selectedGroupIds: {},
editingGroupId: null,
selectedElementIds: makeNextSelectedElementIds(
appState.selectedElementIds,
prevAppState,
),
};
}
return _selectGroups(selectedElements, elements, appState, prevAppState);
};
selectGroupsForSelectedElements.clearCache = () => {
lastElements = null;
lastSelectedElements = null;
lastReturnValue = null;
};
return selectGroupsForSelectedElements;
})();
/**
* If the element's group is selected, don't render an individual
* selection border around it.
+2
View File
@@ -81,6 +81,7 @@ export * from "./groups";
export * from "./heading";
export * from "./image";
export * from "./linearElementEditor";
export * from "./listMarker";
export * from "./mutateElement";
export * from "./newElement";
export * from "./positionElementsOnGrid";
@@ -94,6 +95,7 @@ export * from "./showSelectedShapeActions";
export * from "./sizeHelpers";
export * from "./sortElements";
export * from "./store";
export * from "./stickyNote";
export * from "./textElement";
export * from "./textMeasurements";
export * from "./textWrapping";
+352 -34
View File
@@ -8,7 +8,14 @@ import {
pointDistance,
vectorFromPoint,
curveLength,
curveLengthAtParameter,
curvePointAtLength,
lineSegmentClosestParameter,
lineSegmentPointAt,
curveClosestParameter,
clamp,
bezierEquation,
isCurve,
} from "@excalidraw/math";
import { getCurvePathOps } from "@excalidraw/utils/shape";
@@ -30,8 +37,11 @@ import {
moveArrowAboveBindable,
projectFixedPointOntoDiagonal,
type Store,
getLinearElementPathSegments,
} from "@excalidraw/element";
import type { LinearPathSegment } from "@excalidraw/element";
import type { Radians } from "@excalidraw/math";
import type {
@@ -48,7 +58,6 @@ import {
calculateFixedPointForNonElbowArrowBinding,
getBindingStrategyForDraggingBindingElementEndpoints,
isBindingEnabled,
snapToMid,
updateBoundPoint,
} from "./binding";
import {
@@ -122,6 +131,15 @@ type PointMoveOtherUpdates = {
suggestedBinding?: AppState["suggestedBinding"] | null;
};
const BoundTextPositionCache = new WeakMap<
ExcalidrawTextElementWithContainer,
{
containerVersion: ExcalidrawElement["version"];
textVersion: ExcalidrawElement["version"];
position: { x: number; y: number };
}
>();
export class LinearElementEditor {
public readonly elementId: ExcalidrawElement["id"] & {
_brand: "excalidrawLinearElementId";
@@ -346,7 +364,7 @@ export class LinearElementEditor {
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
const { positions, updates } = pointDraggingUpdates(
const { positions, updates, hit } = pointDraggingUpdates(
[idx],
deltaX,
deltaY,
@@ -388,17 +406,20 @@ export class LinearElementEditor {
// Move the arrow over the bindable object in terms of z-index
if (isBindingElement(element)) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
if (hit) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
element,
element.points[element.points.length - 1],
elementsMap,
),
element,
element.points[element.points.length - 1],
elements,
elementsMap,
),
element,
elements,
elementsMap,
app.scene,
);
app.scene,
hit,
);
}
}
// PERF: Avoid state updates if not absolutely necessary
@@ -547,7 +568,7 @@ export class LinearElementEditor {
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
const { positions, updates } = pointDraggingUpdates(
const { positions, updates, hit } = pointDraggingUpdates(
selectedPointsIndices,
deltaX,
deltaY,
@@ -591,19 +612,22 @@ export class LinearElementEditor {
// Move the arrow over the bindable object in terms of z-index
if (isBindingElement(element) && startIsSelected !== endIsSelected) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
if (hit) {
moveArrowAboveBindable(
LinearElementEditor.getPointGlobalCoordinates(
element,
startIsSelected
? element.points[0]
: element.points[element.points.length - 1],
elementsMap,
),
element,
startIsSelected
? element.points[0]
: element.points[element.points.length - 1],
elements,
elementsMap,
),
element,
elements,
elementsMap,
app.scene,
);
app.scene,
hit,
);
}
}
// Attached text might need to update if arrow dimensions change
@@ -1031,6 +1055,8 @@ export class LinearElementEditor {
): {
didAddPoint: boolean;
hitElement: NonDeleted<ExcalidrawElement> | null;
/** the pointer went down on the arrow's label, grabbing it for a drag */
hitBoundText: boolean;
linearElementEditor: LinearElementEditor | null;
} {
const appState = app.state;
@@ -1039,6 +1065,7 @@ export class LinearElementEditor {
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
hitBoundText: false,
linearElementEditor: null,
};
@@ -1112,16 +1139,51 @@ export class LinearElementEditor {
return ret;
}
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
const pointIndexUnderCursor = LinearElementEditor.getPointIndexUnderCursor(
element,
elementsMap,
appState.zoom,
scenePointer.x,
scenePointer.y,
);
// if we clicked on a point, set the element as hitElement otherwise
// it would get deselected if the point is outside the hitbox area
if (clickedPointIndex >= 0 || segmentMidpoint) {
const clickedPointIsHandle = LinearElementEditor.isPointHandle(
element,
pointIndexUnderCursor,
);
const boundTextElement = getBoundTextElement(element, elementsMap);
let boundTextGrabOffset: { x: number; y: number } | null = null;
if (
!clickedPointIsHandle &&
// the segment midpoint knob keeps precedence over the label sitting
// on top of it, so a labeled arrow can still be bent at its middle
!segmentMidpoint &&
boundTextElement &&
isArrowElement(element) &&
app.arrowText.isBoundTextGrabbable(
element,
scenePointer.x,
scenePointer.y,
)
) {
const { x: textX, y: textY } =
LinearElementEditor.getBoundTextElementPosition(
element,
boundTextElement,
elementsMap,
);
boundTextGrabOffset = {
x: scenePointer.x - (textX + boundTextElement.width / 2),
y: scenePointer.y - (textY + boundTextElement.height / 2),
};
}
// when the label grab wins (possible over a non-interactive elbow route
// point), the click must not double as a point click
const clickedPointIndex = boundTextGrabOffset ? -1 : pointIndexUnderCursor;
ret.hitBoundText = !!boundTextGrabOffset;
if (clickedPointIndex >= 0 || segmentMidpoint || boundTextGrabOffset) {
ret.hitElement = element;
}
@@ -1174,7 +1236,7 @@ export class LinearElementEditor {
x: scenePointer.x - targetPoint[0],
y: scenePointer.y - targetPoint[1],
}
: { x: 0, y: 0 },
: boundTextGrabOffset ?? { x: 0, y: 0 },
};
return ret;
@@ -1355,6 +1417,19 @@ export class LinearElementEditor {
return pointFrom(x - element.x, y - element.y);
}
/**
* Whether the point at `index` is an interactive handle. Elbow arrows only
* expose their endpoints; their intermediate route points are not draggable.
*/
static isPointHandle(element: ExcalidrawLinearElement, index: number) {
return (
index >= 0 &&
(!isElbowArrow(element) ||
index === 0 ||
index === element.points.length - 1)
);
}
static getPointIndexUnderCursor(
element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
@@ -1885,17 +1960,163 @@ export class LinearElementEditor {
);
};
static handleBoundTextDragging(
linearElementEditor: LinearElementEditor,
scene: Scene,
pointerX: number,
pointerY: number,
): LinearElementEditor | null {
const elementsMap = scene.getNonDeletedElementsMap();
const element = LinearElementEditor.getElement(
linearElementEditor.elementId,
elementsMap,
);
const boundTextElement = getBoundTextElement(element, elementsMap);
if (!element || !isArrowElement(element) || !boundTextElement) {
return null;
}
const pointerGlobalPoint = pointFrom<GlobalPoint>(
pointerX - linearElementEditor.pointerOffset.x,
pointerY - linearElementEditor.pointerOffset.y,
);
const { segments, lengths, prefixSums, totalLength } =
getLinearElementPathMetrics(element, elementsMap);
if (segments.length === 0 || totalLength === 0) {
return null;
}
let bestDistance = Infinity;
let bestSegmentIndex = 0;
let bestParameter = 0;
for (let i = 0; i < segments.length; i++) {
const { t, distance } = pathSegmentClosestParameter(
segments[i],
pointerGlobalPoint,
);
if (distance < bestDistance) {
bestDistance = distance;
bestSegmentIndex = i;
bestParameter = t;
}
}
const lengthWithinSegment = pathSegmentLengthAtParameter(
segments[bestSegmentIndex],
bestParameter,
lengths[bestSegmentIndex],
);
const labelPosition = clamp(
(prefixSums[bestSegmentIndex] + lengthWithinSegment) / totalLength,
0,
1,
);
const pathPoint = LinearElementEditor.getPointAtPathParameter(
element,
labelPosition,
elementsMap,
);
if (!pathPoint) {
return null;
}
scene.mutateElement(boundTextElement, {
labelPosition,
x: pathPoint[0] - boundTextElement.width / 2,
y: pathPoint[1] - boundTextElement.height / 2,
});
return {
...linearElementEditor,
isDragging: true,
};
}
static getPointAtPathParameter(
container: ExcalidrawLinearElement,
pathParameter: number,
elementsMap: ElementsMap,
): GlobalPoint | null {
if (!Number.isFinite(pathParameter)) {
return null;
}
const { segments, lengths, prefixSums, totalLength } =
getLinearElementPathMetrics(container, elementsMap);
if (segments.length === 0) {
return null;
}
const targetLength = clamp(pathParameter, 0, 1) * totalLength;
// the first segment whose end lies at or beyond the target; the last one
// catches a target that floating point pushed past the total length
const found = segments.findIndex(
(_, i) => targetLength <= prefixSums[i + 1],
);
const i = found === -1 ? segments.length - 1 : found;
const lengthFraction =
lengths[i] === 0
? 0
: clamp((targetLength - prefixSums[i]) / lengths[i], 0, 1);
return pathSegmentPointAtLength(segments[i], lengthFraction, lengths[i]);
}
static getBoundTextElementPosition = (
element: ExcalidrawLinearElement,
boundTextElement: ExcalidrawTextElementWithContainer,
elementsMap: ElementsMap,
): { x: number; y: number } => {
const points = LinearElementEditor.getPointsGlobalCoordinates(
// derived on every hit test, bounds query and render of the label, so
// memoize on the pair of versions the result depends on
const cached = BoundTextPositionCache.get(boundTextElement);
if (
cached &&
cached.containerVersion === element.version &&
cached.textVersion === boundTextElement.version
) {
return cached.position;
}
const position = LinearElementEditor.computeBoundTextElementPosition(
element,
boundTextElement,
elementsMap,
);
if (points.length < 2) {
mutateElement(boundTextElement, elementsMap, { isDeleted: true });
BoundTextPositionCache.set(boundTextElement, {
containerVersion: element.version,
textVersion: boundTextElement.version,
position,
});
return position;
};
private static computeBoundTextElementPosition = (
element: ExcalidrawLinearElement,
boundTextElement: ExcalidrawTextElementWithContainer,
elementsMap: ElementsMap,
): { x: number; y: number } => {
if (element.points.length < 2) {
return { x: boundTextElement.x, y: boundTextElement.y };
}
if (isArrowElement(element) && boundTextElement.labelPosition != null) {
const pathPoint = LinearElementEditor.getPointAtPathParameter(
element,
boundTextElement.labelPosition,
elementsMap,
);
if (pathPoint) {
return {
x: pathPoint[0] - boundTextElement.width / 2,
y: pathPoint[1] - boundTextElement.height / 2,
};
}
}
const center = LinearElementEditor.getBoundTextElementCenter(
@@ -2169,6 +2390,7 @@ const pointDraggingUpdates = (
): {
positions: PointsPositionUpdates;
updates?: PointMoveOtherUpdates;
hit?: NonDeleted<ExcalidrawBindableElement> | null;
} => {
const naiveDraggingPoints = new Map(
selectedPointsIndices.map((pointIndex) => {
@@ -2227,18 +2449,21 @@ const pointDraggingUpdates = (
? {
element: suggestedBindingElement,
midPoint: app.state.isMidpointSnappingEnabled
? snapToMid(
suggestedBindingElement,
elementsMap,
? getSnapOutlineMidPoint(
pointFrom<GlobalPoint>(
scenePointerX - linearElementEditor.pointerOffset.x,
scenePointerY - linearElementEditor.pointerOffset.y,
),
suggestedBindingElement,
elementsMap,
app.state.zoom,
element,
)
: undefined,
}
: null,
},
hit: suggestedBindingElement,
};
}
@@ -2340,6 +2565,7 @@ const pointDraggingUpdates = (
start.element,
elementsMap,
app.state.zoom,
element,
),
}
: null;
@@ -2379,6 +2605,7 @@ const pointDraggingUpdates = (
end.element,
elementsMap,
app.state.zoom,
element,
),
}
: null;
@@ -2528,6 +2755,7 @@ const pointDraggingUpdates = (
];
}),
),
hit: startIsDragged ? start.element : end.element,
};
};
@@ -2536,3 +2764,93 @@ const determineCustomLinearAngle = (
draggedPoint: LocalPoint,
) =>
Math.atan2(draggedPoint[1] - pivotPoint[1], draggedPoint[0] - pivotPoint[0]);
type LinearElementPathMetrics = {
segments: LinearPathSegment[];
lengths: number[];
prefixSums: number[];
totalLength: number;
};
const LinearElementPathMetricsCache = new WeakMap<
ExcalidrawElement,
{ version: ExcalidrawElement["version"]; metrics: LinearElementPathMetrics }
>();
function getLinearElementPathMetrics(
element: ExcalidrawLinearElement,
elementsMap: ElementsMap,
): LinearElementPathMetrics {
const cached = LinearElementPathMetricsCache.get(element);
if (cached) {
if (cached.version === element.version) {
return cached.metrics;
}
LinearElementPathMetricsCache.delete(element);
}
const segments = getLinearElementPathSegments(element, elementsMap);
const lengths = segments.map(pathSegmentLength);
const prefixSums = new Array<number>(lengths.length + 1);
prefixSums[0] = 0;
for (let i = 0; i < lengths.length; i++) {
prefixSums[i + 1] = prefixSums[i] + lengths[i];
}
const metrics: LinearElementPathMetrics = {
segments,
lengths,
prefixSums,
totalLength: prefixSums[lengths.length],
};
LinearElementPathMetricsCache.set(element, {
version: element.version,
metrics,
});
return metrics;
}
const pathSegmentLength = (segment: LinearPathSegment): number =>
isCurve(segment)
? curveLength(segment)
: pointDistance(segment[0], segment[1]);
/**
* The segment's parameter `t` (`0..1`) at the point closest to `point`, and
* how far that point is from `point`.
*/
const pathSegmentClosestParameter = (
segment: LinearPathSegment,
point: GlobalPoint,
): { t: number; distance: number } => {
if (isCurve(segment)) {
const t = curveClosestParameter(segment, point);
return { t, distance: pointDistance(point, bezierEquation(segment, t)) };
}
const t = lineSegmentClosestParameter(point, segment);
return { t, distance: pointDistance(point, lineSegmentPointAt(segment, t)) };
};
/** arc length from the segment's start to its parameter `t` */
const pathSegmentLengthAtParameter = (
segment: LinearPathSegment,
t: number,
segmentLength: number,
): number =>
isCurve(segment) ? curveLengthAtParameter(segment, t) : t * segmentLength;
/** point at `fraction` (`0..1`) of the segment's arc length */
const pathSegmentPointAtLength = (
segment: LinearPathSegment,
fraction: number,
segmentLength: number,
): GlobalPoint =>
isCurve(segment)
? curvePointAtLength(segment, fraction, segmentLength)
: lineSegmentPointAt(segment, fraction);
+364
View File
@@ -0,0 +1,364 @@
import { arrayToMap } from "@excalidraw/common";
import { refreshTextDimensions } from "./newElement";
import {
getBoundTextElement,
getContainerElement,
redrawTextBoundingBox,
} from "./textElement";
import { isBoundToContainer, isTextElement } from "./typeChecks";
import type { Scene } from "./Scene";
import type { ExcalidrawElement, ExcalidrawTextElement } from "./types";
/**
* A list marker a text starts with: `1.`, `1)`, `(1)`, `[1]`, `a.`, `a)`,
* `(a)`, `A.`, `iv.` etc. Must be followed by whitespace (or nothing), so that
* `1.5` or `e.g.` aren't list markers. See also `LONE_NUMBER_REGEX`.
*
* (Letters don't take `[]`, as `[a]` tends to mean other things.)
*/
const LIST_MARKER_REGEX =
/^(\s*)(?:\((\d{1,9}|[a-zA-Z]+)\)|\[(\d{1,9})\]|(\d{1,9}|[a-zA-Z]+)([.)]))(?=\s|$)/;
/** a text that's just a number counts as a list item too (e.g. a step badge) */
const LONE_NUMBER_REGEX = /^(\s*)(\d{1,9})\s*$/;
/** letters below `i` count alphabetically, from `i` up as roman numerals */
const LAST_ALPHA_ORDINAL = "h".charCodeAt(0) - "a".charCodeAt(0) + 1;
type ListMarkerKind = "decimal" | "alpha" | "roman";
/**
* Lists count up to 42 (so that e.g. `2024. foo` isn't a list item), roman
* numerals up to `xcix`.
*/
const MAX_ORDINAL: Record<ListMarkerKind, number> = {
decimal: 42,
alpha: 9, // i. (then switching to roman)
roman: 99,
};
const toRoman = (value: number) =>
["", "x", "xx", "xxx", "xl", "l", "lx", "lxx", "lxxx", "xc"][
Math.floor(value / 10)
] + ["", "i", "ii", "iii", "iv", "v", "vi", "vii", "viii", "ix"][value % 10];
const ROMAN_VALUES = new Map(
Array.from({ length: MAX_ORDINAL.roman }, (_, index) => [
toRoman(index + 1),
index + 1,
]),
);
type ListMarker = {
/** where the marker's value starts in the text */
index: number;
value: string;
kind: ListMarkerKind;
isUpperCase: boolean;
/** e.g. `1.` and `2.` are of the same style, but `1.` and `(1)` aren't */
style: string;
/** 1-based */
ordinal: number;
/** where the item's text (after the marker and whitespace) starts */
contentIndex: number;
};
const parseLoneNumber = (text: string): ListMarker | null => {
const match = text.match(LONE_NUMBER_REGEX);
if (!match) {
return null;
}
const [, indent, value] = match;
return {
index: indent.length,
value,
kind: "decimal",
isUpperCase: false,
style: "decimal",
ordinal: parseInt(value, 10),
contentIndex: text.length,
};
};
const parseListMarker = (text: string): ListMarker | null => {
const match = text.match(LIST_MARKER_REGEX);
if (!match) {
return null;
}
const [, indent, parenValue, bracketValue, plainValue, plainSuffix] = match;
const value = parenValue ?? bracketValue ?? plainValue;
const lowerCaseValue = value.toLowerCase();
const isUpperCase = /[A-Z]/.test(value);
const alphaOrdinal = lowerCaseValue.charCodeAt(0) - "a".charCodeAt(0) + 1;
let kind: ListMarkerKind;
let ordinal: number;
if (/\d/.test(value)) {
kind = "decimal";
ordinal = parseInt(value, 10);
} else if (isUpperCase && /[a-z]/.test(value)) {
// mixed case
return null;
} else if (value.length === 1 && alphaOrdinal <= LAST_ALPHA_ORDINAL) {
kind = "alpha";
ordinal = alphaOrdinal;
} else if (ROMAN_VALUES.has(lowerCaseValue)) {
kind = "roman";
ordinal = ROMAN_VALUES.get(lowerCaseValue)!;
} else {
return null;
}
const affixes =
parenValue !== undefined
? "()"
: bracketValue !== undefined
? "[]"
: plainSuffix;
return {
index: indent.length + (plainValue !== undefined ? 0 : 1),
value,
kind,
isUpperCase,
style: `${kind}${isUpperCase ? "-upper" : ""}${affixes}`,
ordinal,
contentIndex:
match[0].length + text.slice(match[0].length).match(/^\s*/)![0].length,
};
};
/**
* @returns the list marker the text starts with (or the number the text is),
* unless the text is a whole list (other lines start with markers of
* the same style)
*/
const getListItemMarker = (text: string): ListMarker | null => {
const marker = parseLoneNumber(text) ?? parseListMarker(text);
if (!marker || marker.ordinal > MAX_ORDINAL[marker.kind]) {
return null;
}
const otherLines = text.slice(marker.index).split("\n").slice(1);
if (
otherLines.some((line) => parseListMarker(line)?.style === marker.style)
) {
return null;
}
return marker;
};
/** @returns `null` if the marker would be past `MAX_ORDINAL` */
const renumberListMarker = (
text: string,
marker: ListMarker,
ordinal: number,
): string | null => {
if (ordinal > MAX_ORDINAL[marker.kind]) {
return null;
}
let value: string;
if (marker.kind === "decimal") {
// keep zero padding (`01.` -> `02.`)
value = String(ordinal).padStart(
marker.value.startsWith("0") ? marker.value.length : 0,
"0",
);
} else if (marker.kind === "alpha") {
value = String.fromCharCode("a".charCodeAt(0) + ordinal - 1);
} else {
value = toRoman(ordinal);
}
if (marker.isUpperCase) {
value = value.toUpperCase();
}
return (
text.slice(0, marker.index) +
value +
text.slice(marker.index + marker.value.length)
);
};
/** a list marker advanced by duplication, to go back and forth */
export type ListMarkerAdvance = {
elementId: ExcalidrawTextElement["id"];
prevOriginalText: string;
nextOriginalText: string;
/**
* where the item's text (after the marker and whitespace) starts in
* `nextOriginalText` (its length if there's none)
*/
contentStart: number;
/** the label's container before the label (may have) grown it */
prevContainerSize: { width: number; height: number } | null;
};
const setText = (
element: ExcalidrawTextElement,
container: ExcalidrawElement | null,
originalText: string,
scene: Scene,
) => {
if (container) {
scene.mutateElement(element, { originalText });
// re-wraps the label, and grows the container if need be
redrawTextBoundingBox(element, container, scene);
} else {
scene.mutateElement(element, {
originalText,
// re-wraps the text, and keeps it anchored as per its alignment
...refreshTextDimensions(
element,
null,
scene.getNonDeletedElementsMap(),
originalText,
),
});
}
};
/**
* Advances the list markers of the duplicated texts and labels, so that
* duplicating `1. foo` gives `2. foo` (and `1` gives `2`).
*
* Duplicating several list items at once continues the list from the
* highest of them: duplicating `1.`, `3.`, `5.` gives `6.`, `7.`, `8.` (only
* if they're just markers, i.e. without text).
*
* Only if nothing but list items (texts, or containers with list item labels)
* is duplicated.
*/
export const advanceDuplicatedListMarkers = (
duplicatedElements: readonly ExcalidrawElement[],
scene: Scene,
): ListMarkerAdvance[] => {
const duplicatesMap = arrayToMap(duplicatedElements);
const elementsMap = scene.getNonDeletedElementsMap();
// per marker style
const itemsByStyle = new Map<
string,
{
element: ExcalidrawTextElement;
container: ExcalidrawElement | null;
marker: ListMarker;
}[]
>();
for (const element of duplicatedElements) {
// a label goes with its container
if (isBoundToContainer(element) && duplicatesMap.has(element.containerId)) {
continue;
}
const text = isTextElement(element)
? element
: getBoundTextElement(element, elementsMap);
const marker = text && getListItemMarker(text.originalText);
// list items duplicated along with anything else (another text, a shape,
// a frame they're in…) are copied as they are
if (!text || !marker) {
return [];
}
const items = itemsByStyle.get(marker.style) ?? [];
items.push({
element: text,
container: text === element ? null : element,
marker,
});
itemsByStyle.set(marker.style, items);
}
// several list items are continued only if they're just markers (`1.`,
// `2.`, `3.`), not items with text (`1. foo`, `2. bar`)
const allItems = [...itemsByStyle.values()].flat();
if (
allItems.length > 1 &&
allItems.some(
({ element, marker }) =>
marker.contentIndex < element.originalText.length,
)
) {
return [];
}
const advances: ListMarkerAdvance[] = [];
for (const items of itemsByStyle.values()) {
const maxOrdinal = Math.max(...items.map((item) => item.marker.ordinal));
// (stable, so items with the same marker keep their order)
items.sort((a, b) => a.marker.ordinal - b.marker.ordinal);
for (const [index, { element, container, marker }] of items.entries()) {
const nextOriginalText = renumberListMarker(
element.originalText,
marker,
maxOrdinal + 1 + index,
);
if (nextOriginalText === null) {
continue;
}
advances.push({
elementId: element.id,
prevOriginalText: element.originalText,
nextOriginalText,
contentStart:
marker.contentIndex +
nextOriginalText.length -
element.originalText.length,
prevContainerSize: container
? { width: container.width, height: container.height }
: null,
});
setText(element, container, nextOriginalText, scene);
}
}
return advances;
};
/**
* Sets the advanced list markers back (`"prev"`), or forth again (`"next"`).
*/
export const applyListMarkerAdvances = (
advances: readonly ListMarkerAdvance[],
direction: "prev" | "next",
scene: Scene,
) => {
const elementsMap = scene.getNonDeletedElementsMap();
for (const advance of advances) {
const element = elementsMap.get(advance.elementId);
if (!element || !isTextElement(element)) {
continue;
}
const container = getContainerElement(element, elementsMap);
if (direction === "prev" && container && advance.prevContainerSize) {
// labels only ever grow their containers
scene.mutateElement(container, advance.prevContainerSize);
}
setText(
element,
container,
direction === "prev"
? advance.prevOriginalText
: advance.nextOriginalText,
scene,
);
}
};
+4 -1
View File
@@ -21,9 +21,12 @@ import type {
NonDeletedSceneElementsMap,
} from "./types";
// `created` is lifetime metadata: it is set once when an element instance is
// constructed (or duplicated) and never updated, so it is not part of an
// element update. An explicit repair must construct a new element object.
export type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>,
"id" | "updated"
"id" | "updated" | "created"
>;
/**
+114 -2
View File
@@ -3,6 +3,8 @@ import {
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
DEFAULT_TEXT_ALIGN,
DEFAULT_STICKY_NOTE_SIZE,
STICKY_NOTE_MIN_SIZE,
DEFAULT_VERTICAL_ALIGN,
DEFAULT_STROKE_STREAMLINE,
VERTICAL_ALIGN,
@@ -22,6 +24,10 @@ import {
getResizedElementAbsoluteCoords,
} from "./bounds";
import { newElementWith } from "./mutateElement";
import {
normalizeStickyNoteBackgroundColor,
normalizeStickyNoteStrokeColor,
} from "./stickyNote";
import { getBoundTextMaxWidth } from "./textElement";
import { normalizeText, measureText } from "./textMeasurements";
import { wrapText } from "./textWrapping";
@@ -49,6 +55,7 @@ import type {
ExcalidrawArrowElement,
ExcalidrawElbowArrowElement,
ExcalidrawLineElement,
ExcalidrawStickyNoteElement,
} from "./types";
export type ElementConstructorOpts = MarkOptional<
@@ -74,6 +81,7 @@ export type ElementConstructorOpts = MarkOptional<
| "locked"
| "opacity"
| "customData"
| "created"
>;
const _newElementBase = <T extends ExcalidrawElement>(
@@ -123,6 +131,8 @@ const _newElementBase = <T extends ExcalidrawElement>(
});
}
const timestamp = getUpdatedTimestamp();
// assign type to guard against excess properties
const element: Merge<
ExcalidrawGenericElement,
@@ -151,7 +161,9 @@ const _newElementBase = <T extends ExcalidrawElement>(
versionNonce: rest.versionNonce ?? 0,
isDeleted: false as false,
boundElements,
updated: getUpdatedTimestamp(),
updated: timestamp,
// Preserve explicit null when reconstructing a legacy element with its id.
created: rest.created === undefined ? timestamp : rest.created,
link,
locked,
customData: rest.customData,
@@ -166,6 +178,70 @@ export const newElement = (
): NonDeleted<ExcalidrawGenericElement> =>
_newElementBase<ExcalidrawGenericElement>(opts.type, opts);
/**
* Style invariants of a sticky note: never-transparent colors, solid fill.
* Applied by the constructor and by every normalization pass. Returns the
* same object when nothing needs fixing.
*/
export const normalizeStickyNoteStyle = <T extends ExcalidrawStickyNoteElement>(
element: T,
): T => {
return newElementWith(element as ExcalidrawStickyNoteElement, {
backgroundColor: normalizeStickyNoteBackgroundColor(
element.backgroundColor,
),
strokeColor: normalizeStickyNoteStrokeColor(element.strokeColor),
fillStyle: "solid",
}) as T;
};
/**
* Geometry invariants of a *finalized* sticky note: minimum size and
* `baseHeight ≤ height`. Deliberately not part of the constructor — a
* pointer-down draft starts at 0×0 like every other tool and is previewed at
* its true dragged size; pointer-up, restore, the skeleton path and the
* action post-passes enforce this.
*/
export const normalizeStickyNoteGeometry = <
T extends ExcalidrawStickyNoteElement,
>(
element: T,
): T => {
const width = Math.max(element.width, STICKY_NOTE_MIN_SIZE);
const baseHeight = Math.max(
element.baseHeight || element.height || DEFAULT_STICKY_NOTE_SIZE,
STICKY_NOTE_MIN_SIZE,
);
return newElementWith(element as ExcalidrawStickyNoteElement, {
width,
height: Math.max(element.height, baseHeight),
baseHeight,
}) as T;
};
/** all sticky note invariants (style + finalized geometry) */
export const normalizeStickyNote = <T extends ExcalidrawStickyNoteElement>(
element: T,
): T => {
return normalizeStickyNoteGeometry(normalizeStickyNoteStyle(element));
};
export const newStickyNoteElement = (
opts: {
type: "stickynote";
baseHeight?: number;
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawStickyNoteElement> => {
const base = _newElementBase<ExcalidrawStickyNoteElement>("stickynote", opts);
// no size inflation here (see `normalizeStickyNoteGeometry`)
return normalizeStickyNoteStyle({
...base,
baseHeight: opts.baseHeight ?? base.height,
});
};
export const newEmbeddableElement = (
opts: {
type: "embeddable";
@@ -267,6 +343,8 @@ export const newTextElement = (
containerId?: ExcalidrawTextContainer["id"] | null;
lineHeight?: ExcalidrawTextElement["lineHeight"];
autoResize?: ExcalidrawTextElement["autoResize"];
labelPosition?: ExcalidrawTextElement["labelPosition"];
baseFontSize?: ExcalidrawTextElement["baseFontSize"];
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawTextElement> => {
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
@@ -289,6 +367,7 @@ export const newTextElement = (
..._newElementBase<ExcalidrawTextElement>("text", opts),
text,
fontSize,
baseFontSize: opts.baseFontSize ?? null,
fontFamily,
textAlign,
verticalAlign,
@@ -300,6 +379,7 @@ export const newTextElement = (
originalText: opts.originalText ?? text,
autoResize: opts.autoResize ?? true,
lineHeight,
labelPosition: opts.labelPosition ?? null,
};
const textElement: NonDeleted<ExcalidrawTextElement> = newElementWith(
@@ -314,6 +394,8 @@ const getAdjustedDimensions = (
element: ExcalidrawTextElement,
elementsMap: ElementsMap,
nextText: string,
/** the width the text is to take regardless of its content */
nextFixedWidth?: number,
): {
x: number;
y: number;
@@ -327,7 +409,9 @@ const getAdjustedDimensions = (
);
// wrapped text
if (!element.autoResize) {
if (nextFixedWidth !== undefined) {
nextWidth = nextFixedWidth;
} else if (!element.autoResize) {
nextWidth = element.width;
}
@@ -451,10 +535,38 @@ export const refreshTextDimensions = (
container: ExcalidrawTextContainer | null,
elementsMap: ElementsMap,
text = textElement.text,
/**
* For a free text that grows with its content (`autoResize`): the widest
* it may grow to. Crossing it, the text stops growing and wraps at this
* width from then on (`autoResize: false`), anchored as its growth was. A
* text that is already wider keeps growing.
*/
maxWidth?: number,
) => {
if (textElement.isDeleted) {
return;
}
if (
maxWidth !== undefined &&
!container &&
textElement.autoResize &&
textElement.width <= maxWidth
) {
const font = getFontString(textElement);
if (measureText(text, font, textElement.lineHeight).width > maxWidth) {
const wrappedText = wrapText(text, font, maxWidth);
return {
text: wrappedText,
autoResize: false,
...getAdjustedDimensions(
textElement,
elementsMap,
wrappedText,
maxWidth,
),
};
}
}
if (container || !textElement.autoResize) {
text = wrapText(
text,
+399 -93
View File
@@ -1,6 +1,7 @@
import rough from "roughjs/bin/rough";
import {
clamp,
type GlobalPoint,
isRightAngleRads,
lineSegment,
@@ -24,6 +25,11 @@ import {
invariant,
applyDarkModeFilter,
isSafari,
STICKY_NOTE_EDGE_SHADOW_OPACITY,
STICKY_NOTE_EDGE_SHADOW_WIDTH,
STICKY_NOTE_FOOTER,
STICKY_NOTE_SHADOW_OPACITY,
DEFAULT_ZOOM,
} from "@excalidraw/common";
import type {
@@ -31,9 +37,7 @@ import type {
StaticCanvasAppState,
Zoom,
InteractiveCanvasAppState,
ElementsPendingErasure,
PendingExcalidrawElements,
NormalizedZoomValue,
ElementRenderOverrides,
} from "@excalidraw/excalidraw/types";
import type {
@@ -61,12 +65,18 @@ import {
isArrowElement,
hasBoundTextElement,
isMagicFrameElement,
isFrameLikeElement,
isImageElement,
} from "./typeChecks";
import { getContainingFrame } from "./frame";
import { getCornerRadius } from "./utils";
import { ShapeCache } from "./shape";
import {
getStickyNoteFooter,
getStickyNotePathCommands,
type StickyNotePathCommand,
} from "./stickyNote";
import type {
ExcalidrawElement,
@@ -76,7 +86,6 @@ import type {
ExcalidrawFreeDrawElement,
ExcalidrawImageElement,
ExcalidrawTextElementWithContainer,
ExcalidrawFrameLikeElement,
NonDeletedSceneElementsMap,
ElementsMap,
} from "./types";
@@ -106,30 +115,90 @@ const getCanvasPadding = (element: ExcalidrawElement) => {
}
};
export const getRenderOpacity = (
element: ExcalidrawElement,
containingFrame: ExcalidrawFrameLikeElement | null,
elementsPendingErasure: ElementsPendingErasure,
pendingNodes: Readonly<PendingExcalidrawElements> | null,
globalAlpha: number = 1,
) => {
// multiplying frame opacity with element opacity to combine them
// (e.g. frame 50% and element 50% opacity should result in 25% opacity)
let opacity =
(((containingFrame?.opacity ?? 100) * element.opacity) / 10000) *
globalAlpha;
export type RenderPositionOffset = Readonly<{ x: number; y: number }>;
// if pending erasure, multiply again to combine further
// (so that erasing always results in lower opacity than original)
const ZERO_RENDER_OFFSET: RenderPositionOffset = { x: 0, y: 0 };
/** Bound labels follow their container; a label's own offset is ignored. */
export const getElementRenderOffset = (
element: ExcalidrawElement,
elementsMap: ElementsMap,
overrides: ElementRenderOverrides | undefined,
): RenderPositionOffset | undefined => {
const container = isTextElement(element)
? getContainerElement(element, elementsMap)
: null;
return overrides?.get((container ?? element).id)?.offset;
};
export const getRenderElementWithPositionOverride = <
TElement extends ExcalidrawElement,
>(
element: TElement,
positionOffset: RenderPositionOffset,
): TElement => {
if (positionOffset.x === 0 && positionOffset.y === 0) {
return element;
}
return {
...element,
x: element.x + positionOffset.x,
y: element.y + positionOffset.y,
} as TElement;
};
export type ElementRenderState = Readonly<{
/** Alpha including frame opacity and pending erasure; selection dimming is separate. */
opacity: number;
offset: RenderPositionOffset;
}>;
/** Resolve visual state at the drawing boundary, preserving document cache keys. */
export const resolveElementRenderState = (
element: ExcalidrawElement,
elementsMap: ElementsMap,
renderConfig: Pick<
StaticCanvasRenderConfig,
| "elementRenderOverrides"
| "elementsPendingErasure"
| "pendingFlowchartNodes"
>,
allElementsMap: ElementsMap = elementsMap,
): ElementRenderState => {
const {
elementRenderOverrides,
elementsPendingErasure,
pendingFlowchartNodes,
} = renderConfig;
const override = elementRenderOverrides?.get(element.id);
const containingFrame = getContainingFrame(element, elementsMap);
const frameOpacity = containingFrame
? clamp(
elementRenderOverrides?.get(containingFrame.id)?.opacity ??
containingFrame.opacity,
0,
100,
)
: 100;
// Frame and element alpha multiply (50% each produces 25%).
let opacity =
(frameOpacity * clamp(override?.opacity ?? element.opacity, 0, 100)) /
10000;
if (
elementsPendingErasure.has(element.id) ||
(pendingNodes && pendingNodes.some((node) => node.id === element.id)) ||
pendingFlowchartNodes?.some((node) => node.id === element.id) ||
(containingFrame && elementsPendingErasure.has(containingFrame.id))
) {
opacity *= ELEMENT_READY_TO_ERASE_OPACITY / 100;
}
const offset = getElementRenderOffset(
element,
allElementsMap,
elementRenderOverrides,
);
return opacity;
return { opacity, offset: offset ?? ZERO_RENDER_OFFSET };
};
export interface ExcalidrawElementWithCanvas {
@@ -315,6 +384,50 @@ const drawImagePlaceholder = (
);
};
const drawStickyNotePath = (
context: CanvasRenderingContext2D,
commands: StickyNotePathCommand[],
) => {
context.beginPath();
for (const command of commands) {
if (command.type === "move") {
context.moveTo(command.point.x, command.point.y);
} else if (command.type === "line") {
context.lineTo(command.point.x, command.point.y);
} else {
context.quadraticCurveTo(
command.control.x,
command.control.y,
command.point.x,
command.point.y,
);
}
}
context.closePath();
};
const fillStickyNoteShape = (
context: CanvasRenderingContext2D,
commands: StickyNotePathCommand[],
) => {
drawStickyNotePath(context, commands);
context.fill();
};
const strokeStickyNoteEdge = (
context: CanvasRenderingContext2D,
commands: StickyNotePathCommand[],
) => {
context.save();
drawStickyNotePath(context, commands);
context.clip();
context.lineWidth = STICKY_NOTE_EDGE_SHADOW_WIDTH * 2;
context.strokeStyle = `rgba(0, 0, 0, ${STICKY_NOTE_EDGE_SHADOW_OPACITY})`;
drawStickyNotePath(context, commands);
context.stroke();
context.restore();
};
const drawElementOnCanvas = (
element: NonDeletedExcalidrawElement,
rc: RoughCanvas,
@@ -322,6 +435,41 @@ const drawElementOnCanvas = (
renderConfig: StaticCanvasRenderConfig,
) => {
switch (element.type) {
case "stickynote": {
context.save();
context.fillStyle = `rgba(0, 0, 0, ${STICKY_NOTE_SHADOW_OPACITY})`;
fillStickyNoteShape(
context,
getStickyNotePathCommands(element, { shadow: true }),
);
const commands = getStickyNotePathCommands(element);
context.fillStyle = applyDarkModeFilter(
element.backgroundColor,
renderConfig.theme === THEME.DARK,
);
fillStickyNoteShape(context, commands);
strokeStickyNoteEdge(context, commands);
// the label is absolute, so this cached canvas only goes stale at a
// year boundary — and is regenerated on the next zoom, theme or
// element change anyway
const footer = getStickyNoteFooter(element);
if (footer) {
context.font = `${STICKY_NOTE_FOOTER.fontSize}px ${STICKY_NOTE_FOOTER.fontFamily}`;
context.textAlign = "right";
context.textBaseline = "alphabetic";
context.fillStyle = applyDarkModeFilter(
element.strokeColor,
renderConfig.theme === THEME.DARK,
);
context.globalAlpha *= STICKY_NOTE_FOOTER.opacity;
context.fillText(footer.text, footer.x, footer.y);
}
context.restore();
break;
}
case "rectangle":
case "iframe":
case "embeddable":
@@ -542,11 +690,7 @@ const generateElementWithCanvas = (
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
) => {
const zoom: Zoom = renderConfig
? appState.zoom
: {
value: 1 as NormalizedZoomValue,
};
const zoom: Zoom = renderConfig ? appState.zoom : DEFAULT_ZOOM;
const prevElementWithCanvas = elementWithCanvasCache.get(element);
const shouldRegenerateBecauseZoom =
prevElementWithCanvas &&
@@ -583,21 +727,59 @@ const generateElementWithCanvas = (
return prevElementWithCanvas;
};
/**
* Whether an element's cached bitmap may be laid on the device-pixel grid:
* unrotated or at a right angle, and not during a zoom gesture. The cached
* path disables smoothing for exactly these — a nearest-neighbor 1:1 blit is
* a pixel-exact copy, and rounding its origin keeps it off the half-pixel
* boundary where it tears — and every eligible blit is snapped. 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.
*
* Not during a zoom gesture: the bitmaps stay at the old scale and are
* resampled, and blurry shapes look better on low resolution (while still
* zooming in) than sharp ones; snapping would only make elements twitch.
* Right angles qualify because smoothing can be off there without aliasing
* (for other angles it is terrible on Chromium); the right-angle test
* tolerates float arithmetic.
*/
const canSnapElement = (
element: ExcalidrawElement,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
) =>
!appState?.shouldCacheIgnoreZoom &&
(!element.angle || isRightAngleRads(element.angle));
/**
* Breaks a `Math.round` tie at exactly half a device pixel the same way
* every frame. A label's offset from its container lands on one routinely
* (an odd scene offset at 150%), and the float noise of a fractional drag
* would otherwise flip it between the two neighbors.
*/
const SNAP_TIE_BIAS = 1e-6;
const drawElementFromCanvas = (
elementWithCanvas: ExcalidrawElementWithCanvas,
context: CanvasRenderingContext2D,
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
allElementsMap: NonDeletedSceneElementsMap,
positionOffset: RenderPositionOffset,
) => {
const element = elementWithCanvas.element;
// the ratio the cached bitmap was generated with (`generateElementCanvas`);
// the blit's size math needs the same one, so it is not the owner window's
const devicePixelRatio = window.devicePixelRatio;
const padding = getCanvasPadding(element);
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, allElementsMap);
const cx = ((x1 + x2) / 2 + appState.scrollX) * window.devicePixelRatio;
const cy = ((y1 + y2) / 2 + appState.scrollY) * window.devicePixelRatio;
const cx =
((x1 + x2) / 2 + positionOffset.x + appState.scrollX) * devicePixelRatio;
const cy =
((y1 + y2) / 2 + positionOffset.y + appState.scrollY) * devicePixelRatio;
context.save();
context.scale(1 / window.devicePixelRatio, 1 / window.devicePixelRatio);
context.scale(1 / devicePixelRatio, 1 / devicePixelRatio);
const boundTextElement = getBoundTextElement(element, allElementsMap);
@@ -612,7 +794,7 @@ const drawElementFromCanvas = (
);
// generously covers the arrow's blit at any rotation
const outerHalf =
Math.max(distance(x1, x2), distance(y1, y2)) * window.devicePixelRatio +
Math.max(distance(x1, x2), distance(y1, y2)) * devicePixelRatio +
padding * 10;
context.beginPath();
context.rect(cx - outerHalf, cy - outerHalf, outerHalf * 2, outerHalf * 2);
@@ -620,17 +802,17 @@ const drawElementFromCanvas = (
(boundTextCx -
boundTextElement.width / 2 -
BOUND_TEXT_PADDING +
positionOffset.x +
appState.scrollX) *
window.devicePixelRatio,
devicePixelRatio,
(boundTextCy -
boundTextElement.height / 2 -
BOUND_TEXT_PADDING +
positionOffset.y +
appState.scrollY) *
window.devicePixelRatio,
(boundTextElement.width + BOUND_TEXT_PADDING * 2) *
window.devicePixelRatio,
(boundTextElement.height + BOUND_TEXT_PADDING * 2) *
window.devicePixelRatio,
devicePixelRatio,
(boundTextElement.width + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
(boundTextElement.height + BOUND_TEXT_PADDING * 2) * devicePixelRatio,
);
context.clip("evenodd");
}
@@ -654,16 +836,79 @@ const drawElementFromCanvas = (
// revert afterwards we don't have account for it during drawing
context.translate(-cx, -cy);
// the blit origin, in the space the context is in here (scaled by
// canvas scale × zoom ÷ devicePixelRatio)
let drawX =
(x1 + positionOffset.x + appState.scrollX) * devicePixelRatio - padding;
let drawY =
(y1 + positionOffset.y + appState.scrollY) * devicePixelRatio - padding;
const transform = context.getTransform();
if (canSnapElement(element, appState)) {
// blit the cached bitmap on whole device pixels. Nearest-neighbor at a
// fractional offset is 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 and a few rows
// sample the neighboring row: doubled or broken strokes, varying with
// scroll and position. A centered label lands on a half pixel
// routinely.
//
// Done by moving the transform's origin onto the rounded device
// position of the blit and drawing at (0, 0): the rotation, mirroring
// and scale stay in `a`–`d` (a right angle keeps its scale in `b`/`c`),
// and the origin is an exact integer even in the canvas's float32
// matrix. Rounding `drawX` itself only lands on device pixels at 100%
// zoom.
const { a, b, c, d, e, f } = transform;
const container = isTextElement(element)
? getContainerElement(element, allElementsMap)
: null;
// A bound label shares its unrotated container's offset and anchor.
// Other bitmaps anchor to themselves.
const anchor = container && !container.angle ? container : element;
const anchorCoords =
anchor === element
? null
: getElementAbsoluteCoords(anchor, allElementsMap);
const anchorSceneX = anchorCoords?.[0] ?? x1;
const anchorSceneY = anchorCoords?.[1] ?? y1;
const anchorPadding =
anchor === element ? padding : getCanvasPadding(anchor);
const anchorX =
(anchorSceneX + positionOffset.x + appState.scrollX) * devicePixelRatio -
anchorPadding;
const anchorY =
(anchorSceneY + positionOffset.y + appState.scrollY) * devicePixelRatio -
anchorPadding;
// Form the relative vector before introducing the scroll translation.
const dx = (x1 - anchorSceneX) * devicePixelRatio + anchorPadding - padding;
const dy = (y1 - anchorSceneY) * devicePixelRatio + anchorPadding - padding;
context.setTransform(
a,
b,
c,
d,
Math.round(a * anchorX + c * anchorY + e) +
Math.round(a * dx + c * dy + SNAP_TIE_BIAS),
Math.round(b * anchorX + d * anchorY + f) +
Math.round(b * dx + d * dy + SNAP_TIE_BIAS),
);
drawX = 0;
drawY = 0;
}
context.drawImage(
elementWithCanvas.canvas!,
(x1 + appState.scrollX) * window.devicePixelRatio -
(padding * elementWithCanvas.scale) / elementWithCanvas.scale,
(y1 + appState.scrollY) * window.devicePixelRatio -
(padding * elementWithCanvas.scale) / elementWithCanvas.scale,
drawX,
drawY,
elementWithCanvas.canvas!.width / elementWithCanvas.scale,
elementWithCanvas.canvas!.height / elementWithCanvas.scale,
);
context.setTransform(transform);
if (
import.meta.env.VITE_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX ===
"true" &&
@@ -677,10 +922,10 @@ const drawElementFromCanvas = (
context.strokeStyle = "#c92a2a";
context.lineWidth = 3;
context.strokeRect(
(coords.x + appState.scrollX) * window.devicePixelRatio,
(coords.y + appState.scrollY) * window.devicePixelRatio,
getBoundTextMaxWidth(element, textElement) * window.devicePixelRatio,
getBoundTextMaxHeight(element, textElement) * window.devicePixelRatio,
(coords.x + positionOffset.x + appState.scrollX) * devicePixelRatio,
(coords.y + positionOffset.y + appState.scrollY) * devicePixelRatio,
getBoundTextMaxWidth(element, textElement) * devicePixelRatio,
getBoundTextMaxHeight(element, textElement) * devicePixelRatio,
);
}
context.restore();
@@ -696,7 +941,10 @@ export const renderSelectionElement = (
) => {
context.save();
context.translate(element.x + appState.scrollX, element.y + appState.scrollY);
context.fillStyle = "rgba(0, 0, 200, 0.04)";
context.fillStyle = applyDarkModeFilter(
"rgba(0, 0, 200, 0.04)",
appState.theme === THEME.DARK,
);
// render from 0.5px offset to get 1px wide line
// https://stackoverflow.com/questions/7530593/html5-canvas-and-line-width/7531540#7531540
@@ -720,20 +968,56 @@ export const renderElement = (
context: CanvasRenderingContext2D,
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
renderState = resolveElementRenderState(
element,
elementsMap,
renderConfig,
allElementsMap,
),
) => {
const reduceAlphaForSelection =
appState.openDialog?.name === "elementLinkSelector" &&
!appState.selectedElementIds[element.id] &&
!appState.hoveredElementIds[element.id];
context.globalAlpha = getRenderOpacity(
element,
getContainingFrame(element, elementsMap),
renderConfig.elementsPendingErasure,
renderConfig.pendingFlowchartNodes,
reduceAlphaForSelection ? DEFAULT_REDUCED_GLOBAL_ALPHA : 1,
);
context.save();
context.globalAlpha =
renderState.opacity *
(reduceAlphaForSelection ? DEFAULT_REDUCED_GLOBAL_ALPHA : 1);
// Cached bitmaps apply the offset before pixel snapping. Moving it into
// the canvas transform first loses precision at half-device-pixel ties.
if (
(renderConfig.isExporting || isFrameLikeElement(element)) &&
(renderState.offset.x || renderState.offset.y)
) {
context.translate(renderState.offset.x, renderState.offset.y);
}
try {
drawElement(
element,
elementsMap,
allElementsMap,
rc,
context,
renderConfig,
appState,
renderState,
);
} finally {
context.restore();
}
};
const drawElement = (
element: NonDeletedExcalidrawElement,
elementsMap: RenderableElementsMap,
allElementsMap: NonDeletedSceneElementsMap,
rc: RoughCanvas,
context: CanvasRenderingContext2D,
renderConfig: StaticCanvasRenderConfig,
appState: StaticCanvasAppState | InteractiveCanvasAppState,
renderState: ElementRenderState,
) => {
switch (element.type) {
case "magicframe":
case "frame": {
@@ -808,12 +1092,14 @@ export const renderElement = (
renderConfig,
appState,
allElementsMap,
renderState.offset,
);
}
break;
}
case "rectangle":
case "stickynote":
case "diamond":
case "ellipse":
case "line":
@@ -918,17 +1204,9 @@ export const renderElement = (
const currentImageSmoothingStatus = context.imageSmoothingEnabled;
if (
// do not disable smoothing during zoom as blurry shapes look better
// on low resolution (while still zooming in) than sharp ones
!appState?.shouldCacheIgnoreZoom &&
// angle is 0 -> always disable smoothing
(!element.angle ||
// or check if angle is a right angle in which case we can still
// disable smoothing without adversely affecting the result
// We need less-than comparison because of FP artihmetic
isRightAngleRads(element.angle))
) {
// see `canSnapElement` for why not during zoom gestures or at
// other angles
if (canSnapElement(element, appState)) {
// Disabling smoothing makes output much sharper, especially for
// text. Unless for non-right angles, where the aliasing is really
// terrible on Chromium.
@@ -939,45 +1217,75 @@ export const renderElement = (
context.imageSmoothingEnabled = false;
}
if (
const uncroppedElementCanvas =
element.id === appState.croppingElementId &&
isImageElement(elementWithCanvas.element) &&
elementWithCanvas.element.crop !== null
) {
? generateElementCanvas(
getUncroppedImageElement(
elementWithCanvas.element,
elementsMap,
) as NonDeleted<ExcalidrawImageElement>,
allElementsMap,
appState.zoom,
renderConfig,
appState,
)
: null;
if (uncroppedElementCanvas) {
// the crop editor shows the uncropped image, faded outside the
// crop: one bitmap, so cropping moves only the crop's edges over it
// (the cropped image's own bitmap snaps to whole pixels by its own
// corner, shifting the image by a pixel as that corner moves)
context.save();
context.globalAlpha = 0.1;
const uncroppedElementCanvas = generateElementCanvas(
getUncroppedImageElement(
elementWithCanvas.element,
elementsMap,
) as NonDeleted<ExcalidrawImageElement>,
allElementsMap,
appState.zoom,
drawElementFromCanvas(
uncroppedElementCanvas,
context,
renderConfig,
appState,
allElementsMap,
// The crop editor's uncropped preview stays at document coordinates.
ZERO_RENDER_OFFSET,
);
if (uncroppedElementCanvas) {
drawElementFromCanvas(
uncroppedElementCanvas,
context,
renderConfig,
appState,
allElementsMap,
);
}
context.restore();
}
drawElementFromCanvas(
elementWithCanvas,
context,
renderConfig,
appState,
allElementsMap,
);
const [x1, y1, x2, y2] = getElementAbsoluteCoords(
elementWithCanvas.element,
allElementsMap,
);
context.save();
// (built in the element's rotated box: save/restore leaves the path)
context.save();
context.translate(
(x1 + x2) / 2 + renderState.offset.x + appState.scrollX,
(y1 + y2) / 2 + renderState.offset.y + appState.scrollY,
);
context.rotate(elementWithCanvas.element.angle);
context.beginPath();
context.rect((x1 - x2) / 2, (y1 - y2) / 2, x2 - x1, y2 - y1);
context.restore();
context.clip();
drawElementFromCanvas(
uncroppedElementCanvas,
context,
renderConfig,
appState,
allElementsMap,
renderState.offset,
);
context.restore();
} else {
drawElementFromCanvas(
elementWithCanvas,
context,
renderConfig,
appState,
allElementsMap,
renderState.offset,
);
}
// reset
context.imageSmoothingEnabled = currentImageSmoothingStatus;
@@ -989,8 +1297,6 @@ export const renderElement = (
throw new Error(`Unimplemented type ${element.type}`);
}
}
context.globalAlpha = 1;
};
export function getFreedrawOutlineAsSegments(
+122 -30
View File
@@ -10,6 +10,7 @@ import {
import {
MIN_FONT_SIZE,
SHIFT_LOCKING_ANGLE,
STICKY_NOTE_MIN_SIZE,
rescalePoints,
getFontString,
} from "@excalidraw/common";
@@ -57,10 +58,16 @@ import {
isFreeDrawElement,
isImageElement,
isLinearElement,
isStickyNoteElement,
isTextElement,
} from "./typeChecks";
import { isInGroup } from "./groups";
import {
getStickyNoteMinSize,
getStickyNoteResizeIntent,
updateStickyNoteLayout,
} from "./stickyNote";
import type { Scene } from "./Scene";
@@ -318,6 +325,15 @@ export const resizeSingleTextElement = (
) => {
const elementsMap = scene.getNonDeletedElementsMap();
// a corner follows the axis it grows most, as keeping the aspect ratio
// does (which text always does)
if (transformHandleType.length === 2) {
nextHeight = Math.max(
nextHeight,
(nextWidth / origElement.width) * origElement.height,
);
}
const metricsWidth = element.width * (nextHeight / element.height);
const metrics = measureFontSizeFromWidth(element, elementsMap, metricsWidth);
@@ -749,11 +765,54 @@ export const resizeSingleElement = (
);
}
let boundTextFont: { fontSize?: number } = {};
// Constraints and font scaling use magnitudes. Keep the signs for the
// geometry below, where crossing the opposite edge flips the element.
const flipFactorX = nextWidth < 0 ? -1 : 1;
const flipFactorY = nextHeight < 0 ? -1 : 1;
nextWidth = Math.abs(nextWidth);
nextHeight = Math.abs(nextHeight);
const elementsMap = scene.getNonDeletedElementsMap();
const boundTextElement = getBoundTextElement(latestElement, elementsMap);
const isResizingStickyNote = isStickyNoteElement(latestElement);
let minSize: { width: number; height: number } | undefined;
if (isResizingStickyNote) {
// A note must fit one line at its label's font ceiling.
minSize = boundTextElement
? getStickyNoteMinSize({
fontSize: boundTextElement.baseFontSize ?? boundTextElement.fontSize,
fontFamily: boundTextElement.fontFamily,
})
: { width: STICKY_NOTE_MIN_SIZE, height: STICKY_NOTE_MIN_SIZE };
} else if (boundTextElement && !shouldMaintainAspectRatio) {
minSize = {
width: getApproxMinLineWidth(
getFontString(boundTextElement),
boundTextElement.lineHeight,
),
height: getApproxMinLineHeight(
boundTextElement.fontSize,
boundTextElement.lineHeight,
),
};
}
if (boundTextElement) {
if (minSize) {
nextWidth = Math.max(nextWidth, minSize.width);
nextHeight = Math.max(nextHeight, minSize.height);
if (shouldMaintainAspectRatio) {
// Both dimensions must use the same scale even at the minimum size.
const scale = Math.max(
nextWidth / origElement.width,
nextHeight / origElement.height,
);
nextWidth = origElement.width * scale;
nextHeight = origElement.height * scale;
}
}
let boundTextFont: { fontSize?: number } = {};
if (boundTextElement && !isResizingStickyNote) {
const stateOfBoundTextElementAtResize = originalElementsMap.get(
boundTextElement.id,
) as typeof boundTextElement | undefined;
@@ -780,20 +839,12 @@ export const resizeSingleElement = (
boundTextFont = {
fontSize: nextFont.size,
};
} else {
const minWidth = getApproxMinLineWidth(
getFontString(boundTextElement),
boundTextElement.lineHeight,
);
const minHeight = getApproxMinLineHeight(
boundTextElement.fontSize,
boundTextElement.lineHeight,
);
nextWidth = Math.max(nextWidth, minWidth);
nextHeight = Math.max(nextHeight, minHeight);
}
}
nextWidth *= flipFactorX;
nextHeight *= flipFactorY;
const rescaledPoints = rescalePointsInElement(
origElement,
nextWidth,
@@ -865,7 +916,7 @@ export const resizeSingleElement = (
shouldMaintainAspectRatio
) {
const fontSize =
(nextWidth / latestElement.width) * boundTextElement.fontSize;
(Math.abs(nextWidth) / latestElement.width) * boundTextElement.fontSize;
if (fontSize < MIN_FONT_SIZE) {
return;
}
@@ -909,24 +960,41 @@ export const resizeSingleElement = (
isDragging: false,
});
if (boundTextElement && boundTextFont != null) {
scene.mutateElement(boundTextElement, {
fontSize: boundTextFont.fontSize,
if (isStickyNoteElement(latestElement)) {
updateStickyNoteLayout(latestElement, scene, {
...getStickyNoteResizeIntent(
latestElement,
originalElementsMap,
handleDirection,
{
proportional: shouldMaintainAspectRatio,
fromCenter: shouldResizeFromCenter,
},
),
// the arrow pass below is this function's — keep it single
bindings: false,
});
} else {
if (boundTextElement && boundTextFont != null) {
scene.mutateElement(boundTextElement, {
fontSize: boundTextFont.fontSize,
});
}
handleBindTextResize(
latestElement,
scene,
handleDirection,
shouldMaintainAspectRatio,
shouldResizeFromCenter,
flipFactorY < 0,
);
}
handleBindTextResize(
latestElement,
scene,
handleDirection,
shouldMaintainAspectRatio,
shouldResizeFromCenter,
);
updateBoundElements(latestElement, scene);
}
};
const getNextSingleWidthAndHeightFromPointer = (
export const getNextSingleWidthAndHeightFromPointer = (
latestElement: ExcalidrawElement,
origElement: ExcalidrawElement,
handleDirection: TransformHandleDirection,
@@ -1441,7 +1509,8 @@ export const resizeMultipleElements = (
getBoundTextElementId(orig) ?? "",
) as ExcalidrawTextElementWithContainer | undefined;
if (boundTextElement) {
// sticky notes derive their label's size from the layout below
if (boundTextElement && !isStickyNoteElement(orig)) {
if (keepAspectRatio) {
const newFontSize = boundTextElement.fontSize * scale;
if (newFontSize < MIN_FONT_SIZE) {
@@ -1473,9 +1542,27 @@ export const resizeMultipleElements = (
scene.mutateElement(element, update);
updateBoundElements(element, scene, {
simultaneouslyUpdated: elementsToUpdate,
});
if (isStickyNoteElement(element)) {
// the content correction runs before the (single) arrow pass, which
// must still skip arrows resized in the same gesture
updateStickyNoteLayout(element, scene, {
...getStickyNoteResizeIntent(
element,
originalElementsMap,
handleDirection,
{
proportional: keepAspectRatio,
fromCenter: shouldResizeFromCenter,
flip: flipByX || flipByY,
},
),
bindings: { simultaneouslyUpdated: elementsToUpdate },
});
} else {
updateBoundElements(element, scene, {
simultaneouslyUpdated: elementsToUpdate,
});
}
if (isBindingElement(element)) {
if (element.startBinding) {
@@ -1491,7 +1578,11 @@ export const resizeMultipleElements = (
}
const boundTextElement = getBoundTextElement(element, elementsMap);
if (boundTextElement && boundTextFontSize) {
if (
boundTextElement &&
boundTextFontSize &&
!isStickyNoteElement(element)
) {
scene.mutateElement(boundTextElement, {
fontSize: boundTextFontSize,
angle: isLinearElement(element) ? undefined : angle,
@@ -1502,6 +1593,7 @@ export const resizeMultipleElements = (
handleDirection,
true,
shouldResizeFromCenter,
flipByY,
);
}
}
+2
View File
@@ -71,6 +71,8 @@ export const resizeTest = <Point extends GlobalPoint | LocalPoint>(
if (
rotationTransformHandle &&
// (the crop editor has none, nor draws it)
!appState.croppingElementId &&
isInsideTransformHandle(rotationTransformHandle, x, y)
) {
return "rotation" as TransformHandleType;
+2 -52
View File
@@ -1,4 +1,4 @@
import { arrayToMap, isShallowEqual, type Bounds } from "@excalidraw/common";
import { isShallowEqual, type Bounds } from "@excalidraw/common";
import type {
AppState,
@@ -11,14 +11,10 @@ import { isElementInViewport } from "./sizeHelpers";
import {
isBoundToContainer,
isFrameLikeElement,
isLinearElement,
isTextElement,
} from "./typeChecks";
import { getFrameChildren } from "./frame";
import { LinearElementEditor } from "./linearElementEditor";
import { selectGroupsForSelectedElements } from "./groups";
import { isNonDeletedElement } from ".";
import type {
@@ -30,7 +26,7 @@ import type {
NonDeletedExcalidrawElement,
} from "./types";
const shouldIgnoreElementFromSelection = (element: ExcalidrawElement) =>
export const shouldIgnoreElementFromSelection = (element: ExcalidrawElement) =>
element.locked || isBoundToContainer(element);
const excludeElementsFromFrames = <T extends ExcalidrawElement>(
@@ -245,52 +241,6 @@ export const makeNextSelectedElementIds = (
return nextSelectedElementIds;
};
const _getLinearElementEditor = (
targetElements: readonly NonDeletedExcalidrawElement[],
allElements: readonly NonDeletedExcalidrawElement[],
) => {
const linears = targetElements.filter(isLinearElement);
if (linears.length === 1) {
const linear = linears[0];
const boundElements = linear.boundElements?.map((def) => def.id) ?? [];
const onlySingleLinearSelected = targetElements.every(
(el) => el.id === linear.id || boundElements.includes(el.id),
);
if (onlySingleLinearSelected) {
return new LinearElementEditor(linear, arrayToMap(allElements));
}
}
return null;
};
export const getSelectionStateForElements = (
targetElements: readonly NonDeletedExcalidrawElement[],
allElements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
) => {
return {
selectedLinearElement: _getLinearElementEditor(targetElements, allElements),
...selectGroupsForSelectedElements(
{
editingGroupId: appState.editingGroupId,
selectedElementIds: excludeElementsInFramesFromSelection(
targetElements,
).reduce((acc: Record<ExcalidrawElement["id"], true>, element) => {
if (!isBoundToContainer(element)) {
acc[element.id] = true;
}
return acc;
}, {}),
},
allElements,
appState,
null,
),
};
};
/**
* Returns editing or single-selected text element, if any.
*/
+102 -64
View File
@@ -1,4 +1,4 @@
import { simplify } from "points-on-curve";
import { pointsOnBezierCurves, simplify } from "points-on-curve";
import { getStroke, getStrokePoints } from "perfect-freehand";
import { LaserPointer } from "@excalidraw/laser-pointer";
@@ -16,6 +16,7 @@ import {
pointDistance,
type LocalPoint,
pointRotateRads,
polygonFromPoints,
} from "@excalidraw/math";
import {
ROUGHNESS,
@@ -30,7 +31,7 @@ import {
import { RoughGenerator } from "roughjs/bin/generator";
import type { GlobalPoint } from "@excalidraw/math";
import type { GlobalPoint, Polygon } from "@excalidraw/math";
import type { Mutable } from "@excalidraw/common/utility-types";
@@ -575,6 +576,48 @@ const getArrowheadShapes = (
}
};
/** The simplified centerline the freedraw fill is drawn along. */
const getFreedrawFillCurvePoints = (element: ExcalidrawFreeDrawElement) =>
simplify(element.points as Mutable<LocalPoint[]>, 0.75) as [number, number][];
const freedrawFillPolygonCache = new WeakMap<
ExcalidrawFreeDrawElement,
{ version: number; polygon: Polygon<LocalPoint> }
>();
/**
* Returns the flattened fill contour of a freedraw loop in local, unrotated
* coordinates, following the rendered fill rather than the stroke outline.
*/
export const getFreedrawFillPolygon = (element: ExcalidrawFreeDrawElement) => {
const cached = freedrawFillPolygonCache.get(element);
if (cached?.version === element.version) {
return cached.polygon;
}
// Same curve as the rendered fill, without roughness jitter. RoughJS also
// handles inputs simplified to two points.
const ops = new RoughGenerator().curve(getFreedrawFillCurvePoints(element), {
roughness: 0,
disableMultiStroke: true,
}).sets[0].ops;
const bezierPoints: LocalPoint[] = [];
// A single curve pass consists of a move followed by cubic control points.
for (const { data } of ops) {
for (let i = 0; i < data.length; i += 2) {
bezierPoints.push(pointFrom<LocalPoint>(data[i], data[i + 1]));
}
}
// Omit the optional distance argument to avoid simplifying the boundary again.
const polygon = polygonFromPoints(
pointsOnBezierCurves(bezierPoints, 0.5) as LocalPoint[],
);
freedrawFillPolygonCache.set(element, { version: element.version, polygon });
return polygon;
};
export const generateLinearCollisionShape = (
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
@@ -675,69 +718,44 @@ export const generateLinearCollisionShape = (
});
}
case "freedraw": {
if (element.points.length < 2) {
const outlinePoints = getFreedrawOutlinePoints(element);
if (outlinePoints.length < 2) {
return [];
}
const simplifiedPoints = simplify(
element.points as Mutable<LocalPoint[]>,
0.75,
);
const collisionOutline =
element.strokeOptions?.variability === "constant"
? (simplify(
outlinePoints as Mutable<LocalPoint[]>,
CONSTANT_WIDTH_FREEDRAW.COLLISION_SIMPLIFY_TOLERANCE,
) as [number, number][])
: outlinePoints;
return generator
.curve(simplifiedPoints as [number, number][], options)
.sets[0].ops.slice(0, element.points.length)
.map((op, i) => {
if (i === 0) {
const p = pointRotateRads<GlobalPoint>(
pointFrom<GlobalPoint>(
element.x + op.data[0],
element.y + op.data[1],
),
center,
element.angle,
);
if (collisionOutline.length < 2) {
return [];
}
return {
op: "move",
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
};
}
// Close the outline polygon so its boundary never has a gap at the seam.
const [firstX, firstY] = collisionOutline[0];
const [lastX, lastY] = collisionOutline[collisionOutline.length - 1];
const closedOutline =
firstX === lastX && firstY === lastY
? collisionOutline
: [...collisionOutline, collisionOutline[0]];
return {
op: "bcurveTo",
data: [
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[0],
element.y + op.data[1],
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[2],
element.y + op.data[3],
),
center,
element.angle,
),
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + op.data[4],
element.y + op.data[5],
),
center,
element.angle,
),
]
.map((p) =>
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
)
.flat(),
};
});
return closedOutline.map((point, idx) => {
const p = pointRotateRads<GlobalPoint>(
pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
center,
element.angle,
);
return {
op: idx === 0 ? "move" : "lineTo",
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
};
});
}
}
};
@@ -962,12 +980,8 @@ const _generateElementShape = (
// (1) background fill (rc shape), optional
if (isPathALoop(element.points)) {
// generate rough polygon to fill freedraw shape
const simplifiedPoints = simplify(
element.points as Mutable<LocalPoint[]>,
0.75,
);
shapes.push(
generator.curve(simplifiedPoints as [number, number][], {
generator.curve(getFreedrawFillCurvePoints(element), {
...generateRoughOptions(element, false, isDarkMode),
stroke: "none",
}),
@@ -979,6 +993,9 @@ const _generateElementShape = (
return shapes;
}
// sticky notes are painted directly (canvas + SVG) from
// `getStickyNoteRenderPoints`, never through roughjs
case "stickynote":
case "frame":
case "magicframe":
case "text":
@@ -1073,6 +1090,7 @@ export const getElementShape = <Point extends GlobalPoint | LocalPoint>(
): GeometricShape<Point> => {
switch (element.type) {
case "rectangle":
case "stickynote":
case "diamond":
case "frame":
case "magicframe":
@@ -1189,6 +1207,11 @@ const VARIABLE_WIDTH_FREEDRAW = {
const CONSTANT_WIDTH_FREEDRAW = {
/** Stroke size relative to `strokeWidth` for uniform (laser) strokes. */
SIZE_FACTOR: 1.4,
/**
* Max deviation (px) when dropping vertices of the dense laser outline for
* collision. Perfect-freehand outlines are already thinned by `smoothing`.
*/
COLLISION_SIMPLIFY_TOLERANCE: 0.2,
} as const;
const getFreedrawStreamline = (element: ExcalidrawFreeDrawElement) =>
@@ -1253,6 +1276,21 @@ export const getFreedrawOutlinePoints = (
: getVariableWidthFreedrawOutline(element);
};
/**
* Upper bound on how far a freedraw stroke's ink reaches past its centerline
* points. Both stroke generators scale the stroke size by at most 1 (easing
* or pressure), so the size itself bounds the radius, except for
* perfect-freehand's short strokes: under 3px long, the start cap is drawn
* around the first point from an outline point of the last one (reaching
* sqrt(size² + 3²)), and a single point gets a synthetic neighbor 1px away.
*/
export const getFreedrawMaxStrokeRadius = (
element: ExcalidrawFreeDrawElement,
) =>
element.strokeOptions?.variability === "constant"
? element.strokeWidth * CONSTANT_WIDTH_FREEDRAW.SIZE_FACTOR
: element.strokeWidth * VARIABLE_WIDTH_FREEDRAW.SIZE_FACTOR + 3;
/**
* The streamline-smoothed centerline the freedraw stroke is rendered
* around, in element-local coordinates. Boundary-sensitive consumers (e.g.
+31
View File
@@ -22,6 +22,37 @@ import {
import type { ElementsMap, ExcalidrawElement } from "./types";
export type VerticalResizeAnchor = "top" | "bottom" | "center";
/** Keeps the chosen edge or center fixed when an element's height changes. */
export const getPositionAfterHeightChange = (
element: Pick<ExcalidrawElement, "x" | "y" | "height" | "angle">,
nextHeight: number,
anchor: VerticalResizeAnchor = "top",
) => {
const delta = (element.height - nextHeight) / 2;
if (anchor === "center") {
// Rotation is about the center, so holding it is angle-independent.
return { x: element.x, y: element.y + delta };
}
const sin = Math.sin(element.angle);
const cos = Math.cos(element.angle);
if (anchor === "bottom") {
return {
x: element.x - delta * sin,
y: element.y + delta * (1 + cos),
};
}
return {
x: element.x + delta * sin,
y: element.y + delta * (1 - cos),
};
};
export const INVISIBLY_SMALL_ELEMENT_SIZE = 0.1;
// TODO: remove invisible elements consistently actions, so that invisible elements are not recorded by the store, exported, broadcasted or persisted
+971
View File
@@ -0,0 +1,971 @@
import {
DEFAULT_ELEMENT_PROPS,
DEFAULT_STICKY_NOTE_BG,
MIN_FONT_SIZE,
arrayToMap,
STICKY_NOTE_BODY_INSET_Y,
STICKY_NOTE_FALLBACK_FONT_SIZE,
STICKY_NOTE_FOOTER,
STICKY_NOTE_FONT_STEP,
STICKY_NOTE_MAX_FONT_SIZE,
STICKY_NOTE_MIN_SIZE,
STICKY_NOTE_MIN_FONT_SIZE,
STICKY_NOTE_PADDING,
STICKY_NOTE_SHADOW_OFFSET,
getFontString,
getLineHeight,
isTransparent,
seededRandom,
} from "@excalidraw/common";
import { clamp } from "@excalidraw/math";
import { updateBoundElements } from "./binding";
import { newElementWith } from "./mutateElement";
import { getPositionAfterHeightChange } from "./sizeHelpers";
import { computeBoundTextPosition, getBoundTextElement } from "./textElement";
import { measureText } from "./textMeasurements";
import { wrapText } from "./textWrapping";
import { isStickyNoteElement, isTextElement } from "./typeChecks";
import type { Scene } from "./Scene";
import type { VerticalResizeAnchor } from "./sizeHelpers";
import type { TransformHandleDirection } from "./transformHandles";
import type {
ElementsMap,
ExcalidrawElement,
ExcalidrawStickyNoteElement,
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
NonDeletedExcalidrawElement,
} from "./types";
export type StickyNoteRenderPoint = {
x: number;
y: number;
};
export type StickyNotePathCommand =
| {
type: "move";
point: StickyNoteRenderPoint;
}
| {
type: "line";
point: StickyNoteRenderPoint;
}
| {
type: "quadratic";
control: StickyNoteRenderPoint;
point: StickyNoteRenderPoint;
};
const STICKY_NOTE_RENDER_ROUGHNESS = [0, 1.5, 8] as const;
const STICKY_NOTE_CORNER_RADIUS_RATIO = 0.04;
const STICKY_NOTE_MAX_CORNER_RADIUS = 16;
export const normalizeStickyNoteStrokeColor = (
strokeColor: string | null | undefined,
) => {
return !strokeColor || isTransparent(strokeColor)
? DEFAULT_ELEMENT_PROPS.strokeColor
: strokeColor;
};
export const normalizeStickyNoteBackgroundColor = (
backgroundColor: string | null | undefined,
) => {
return !backgroundColor || isTransparent(backgroundColor)
? DEFAULT_STICKY_NOTE_BG
: backgroundColor;
};
/**
* The update that applies a picked color to an element under the sticky
* note policy: a note is always filled and its label — the visible text,
* which the note's own `strokeColor` seeds — never goes transparent. Every
* color surface (actions, both eyedroppers, paste styles, bind) routes
* through this instead of re-deriving the rule.
*/
/**
* The element a color pick on `element` lands on. A note's label has no fill
* of its own, so a background pick on the label — the styles panel while
* editing it — goes to the note; everything else colors itself.
*/
export const getColorTargetElement = (
element: ExcalidrawElement,
property: "strokeColor" | "backgroundColor",
elementsMap: ElementsMap,
): ExcalidrawElement => {
if (
property === "backgroundColor" &&
isTextElement(element) &&
isStickyNoteBoundText(element, elementsMap)
) {
return elementsMap.get(element.containerId!) ?? element;
}
return element;
};
export const getColorUpdate = (
element: ExcalidrawElement,
property: "strokeColor" | "backgroundColor",
color: string,
elementsMap: ElementsMap,
): { strokeColor: string } | { backgroundColor: string } => {
if (isStickyNoteElement(element)) {
return property === "backgroundColor"
? { backgroundColor: normalizeStickyNoteBackgroundColor(color) }
: { strokeColor: normalizeStickyNoteStrokeColor(color) };
}
if (
property === "strokeColor" &&
isTextElement(element) &&
isStickyNoteBoundText(element, elementsMap)
) {
const container = elementsMap.get(element.containerId!);
return {
strokeColor: isTransparent(color)
? normalizeStickyNoteStrokeColor(container?.strokeColor)
: color,
};
}
return property === "backgroundColor"
? { backgroundColor: color }
: { strokeColor: color };
};
/**
* A note's ink is one color: the container's `strokeColor` — the seed for a
* new label and what the creation-date footer paints with — and its label's.
* Run after a property write to copy the side that changed onto the other;
* when both changed, or neither (data that drifted), the label wins: it is
* the text the user styled. A transparent label always takes the note's
* color. Returns the same array when nothing needs to change.
*/
export const syncStickyNoteInk = <T extends ExcalidrawElement>(
elements: readonly T[],
prevElementsMap: ElementsMap,
): readonly T[] => {
const elementsMap = arrayToMap(elements);
const inkById = new Map<string, string>();
for (const container of elements) {
if (!isStickyNoteElement(container) || container.isDeleted) {
continue;
}
const label = getBoundTextElement(container, elementsMap);
if (!label || label.strokeColor === container.strokeColor) {
continue;
}
const containerChanged =
prevElementsMap.get(container.id)?.strokeColor !== container.strokeColor;
const labelChanged =
prevElementsMap.get(label.id)?.strokeColor !== label.strokeColor;
if (
isTransparent(label.strokeColor) ||
(containerChanged && !labelChanged)
) {
inkById.set(
label.id,
normalizeStickyNoteStrokeColor(container.strokeColor),
);
} else {
inkById.set(
container.id,
normalizeStickyNoteStrokeColor(label.strokeColor),
);
}
}
if (!inkById.size) {
return elements;
}
return elements.map((element) => {
const strokeColor = inkById.get(element.id);
return strokeColor === undefined
? element
: (newElementWith(element as ExcalidrawElement, { strokeColor }) as T);
});
};
const jitter = (random: () => number, amount: number) =>
(random() * 2 - 1) * amount;
const pointAtDistance = (
from: StickyNoteRenderPoint,
to: StickyNoteRenderPoint,
distance: number,
) => {
const dx = to.x - from.x;
const dy = to.y - from.y;
const length = Math.hypot(dx, dy);
if (!length) {
return from;
}
const ratio = Math.min(distance / length, 1);
return {
x: from.x + dx * ratio,
y: from.y + dy * ratio,
};
};
export const getStickyNoteCornerRadius = (
element: ExcalidrawStickyNoteElement,
) => {
if (!element.roundness) {
return 0;
}
return Math.min(
Math.min(element.width, element.height) * STICKY_NOTE_CORNER_RADIUS_RATIO,
STICKY_NOTE_MAX_CORNER_RADIUS,
);
};
export const getStickyNoteRenderPoints = (
element: ExcalidrawStickyNoteElement,
{
offsetX = 0,
offsetY = 0,
seedOffset = 0,
}: {
offsetX?: number;
offsetY?: number;
seedOffset?: number;
} = {},
): StickyNoteRenderPoint[] => {
const roughness = Math.max(0, Math.min(2, Math.round(element.roughness)));
const amount = Math.min(
STICKY_NOTE_RENDER_ROUGHNESS[roughness],
Math.min(element.width, element.height) * 0.012,
);
if (!amount) {
return [
{ x: offsetX, y: offsetY },
{ x: offsetX + element.width, y: offsetY },
{ x: offsetX + element.width, y: offsetY + element.height },
{ x: offsetX, y: offsetY + element.height },
];
}
const random = seededRandom(element.seed + seedOffset);
return [
{
x: offsetX + jitter(random, amount),
y: offsetY + jitter(random, amount),
},
{
x: offsetX + element.width + jitter(random, amount),
y: offsetY + jitter(random, amount),
},
{
x: offsetX + element.width + jitter(random, amount),
y: offsetY + element.height + jitter(random, amount),
},
{
x: offsetX + jitter(random, amount),
y: offsetY + element.height + jitter(random, amount),
},
];
};
export const getStickyNotePathCommands = (
element: ExcalidrawStickyNoteElement,
{ shadow = false }: { shadow?: boolean } = {},
): StickyNotePathCommand[] => {
const points = getStickyNoteRenderPoints(
element,
shadow
? {
offsetX: STICKY_NOTE_SHADOW_OFFSET,
offsetY: STICKY_NOTE_SHADOW_OFFSET,
seedOffset: 1,
}
: undefined,
);
const radius = getStickyNoteCornerRadius(element);
// The note's seed keeps the same corner for the paper and shadow through
// redraws and resizes.
const liftedCorner =
element.roughness === 2
? Math.floor(seededRandom(element.seed)() * points.length)
: -1;
if (!radius && liftedCorner === -1) {
return [
{ type: "move", point: points[0] },
...points.slice(1).map(
(point): StickyNotePathCommand => ({
type: "line",
point,
}),
),
];
}
const corners = points.map((point, index): StickyNotePathCommand[] => {
const prev = points[(index + points.length - 1) % points.length];
const next = points[(index + 1) % points.length];
const cornerRadius = Math.min(
radius,
Math.hypot(point.x - prev.x, point.y - prev.y) / 2,
Math.hypot(point.x - next.x, point.y - next.y) / 2,
);
if (index === liftedCorner) {
const size = Math.min(element.width, element.height);
const reach = Math.min(size * 0.18, 40);
// The shadow follows the paper inward at half the bend, keeping its
// usual down-right offset from the light at the top left.
const lift = Math.min(size * 0.02, 5) * (shadow ? 0.5 : 1);
// The bend joins the straight edges before the corner, keeping it local.
const tip = {
x: point.x + (index === 1 || index === 2 ? -lift : lift),
y: point.y + (index >= 2 ? -lift : lift),
};
const start = pointAtDistance(point, prev, reach);
const end = pointAtDistance(point, next, reach);
return [
{ type: "line", point: start },
{
type: "quadratic",
control: pointAtDistance(point, prev, reach / 2),
point: pointAtDistance(tip, start, cornerRadius),
},
{
type: "quadratic",
control: tip,
point: pointAtDistance(tip, end, cornerRadius),
},
{
type: "quadratic",
control: pointAtDistance(point, next, reach / 2),
point: end,
},
];
}
return [
{ type: "line", point: pointAtDistance(point, prev, cornerRadius) },
{
type: "quadratic",
control: point,
point: pointAtDistance(point, next, cornerRadius),
},
];
});
const commands: StickyNotePathCommand[] = [
{ type: "move", point: corners[0][corners[0].length - 1].point },
];
for (let index = 1; index <= corners.length; index++) {
commands.push(...corners[index % corners.length]);
}
return commands;
};
// -----------------------------------------------------------------------------
// font size — `baseFontSize` is the size the user picked, `fontSize` the fitted one
// -----------------------------------------------------------------------------
// clamping the ceiling: the fit steps down from it in `STICKY_NOTE_FONT_STEP`
// increments, and for values >= ~2^56 (1e20 - 2 === 1e20) that would never
// progress and hang the editor
export const normalizeStickyNoteFontSize = (fontSize: number) => {
if (!Number.isFinite(fontSize)) {
return STICKY_NOTE_FALLBACK_FONT_SIZE;
}
return Math.min(STICKY_NOTE_MAX_FONT_SIZE, Math.max(MIN_FONT_SIZE, fontSize));
};
/** whether the text element is the label of a sticky note */
export const isStickyNoteBoundText = (
textElement: ExcalidrawTextElement,
elementsMap: ElementsMap,
) => {
return (
!!textElement.containerId &&
isStickyNoteElement(elementsMap.get(textElement.containerId))
);
};
/**
* The font size the user picked: the ceiling the auto-fit shrinks from for a
* sticky note label, plain `fontSize` for any other text.
*
* Container-aware on purpose — generic binding repair (duplication, history)
* rewrites `containerId` without touching the ceiling, so a numeric
* `baseFontSize` alone does not prove the text is still sticky-bound.
*/
export const getBaseFontSize = (
textElement: ExcalidrawTextElement,
elementsMap: ElementsMap,
) => {
return isStickyNoteBoundText(textElement, elementsMap)
? textElement.baseFontSize ?? textElement.fontSize
: textElement.fontSize;
};
/** the update that applies a user-picked font size (see `getBaseFontSize`) */
export const getBaseFontSizeUpdate = (
textElement: ExcalidrawTextElement,
fontSize: number,
elementsMap: ElementsMap,
): { fontSize: number } | { baseFontSize: number } => {
return isStickyNoteBoundText(textElement, elementsMap)
? { baseFontSize: normalizeStickyNoteFontSize(fontSize) }
: { fontSize };
};
const MONTHS = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
/**
* The creation-date label: absolute, so painting needs no clock and exports
* don't go stale, and short ("7 Sep") while the year is the current one.
* `null` when the note has no usable timestamp (files restored without one).
* Fixed English in the viewer's local time zone — the element package has no
* locale, and the footer is chosen by width bucket rather than measured.
*/
export const getStickyNoteDateLabel = (
created: ExcalidrawStickyNoteElement["created"],
{ short = false, now = Date.now() }: { short?: boolean; now?: number } = {},
): string | null => {
if (created === null || !Number.isFinite(created)) {
return null;
}
const date = new Date(created);
if (Number.isNaN(date.getTime())) {
return null;
}
const label = `${date.getDate()} ${MONTHS[date.getMonth()]}`;
const year = date.getFullYear();
return short || year === new Date(now).getFullYear()
? label
: `${label} ${year}`;
};
/**
* What the footer paints and where, in note-local coordinates — shared by the
* canvas and SVG renderers, which take the font and opacity from
* `STICKY_NOTE_FOOTER`. `null` for the 0×0 creation draft and anything under
* the data floor, where the band would overlap the top padding.
*/
export const getStickyNoteFooter = (
element: Pick<ExcalidrawStickyNoteElement, "created" | "width" | "height">,
now = Date.now(),
) => {
if (
element.width < STICKY_NOTE_MIN_SIZE ||
element.height < STICKY_NOTE_MIN_SIZE
) {
return null;
}
const text = getStickyNoteDateLabel(element.created, {
short:
element.width - STICKY_NOTE_PADDING * 2 <
STICKY_NOTE_FOOTER.minBodyWidthForYear,
now,
});
if (!text) {
return null;
}
return {
text,
x: element.width - STICKY_NOTE_PADDING,
y: element.height - STICKY_NOTE_FOOTER.baselineFromBottom,
};
};
/**
* The smallest note the UI lets a user create or resize to: one line at the
* label's font ceiling plus padding (and, vertically, the footer), never below
* `STICKY_NOTE_MIN_SIZE`. Without the font term a fresh note would grow on
* the very first keystroke. Data-level passes (restore, action post-passes)
* only enforce the constant floor — the layout grows a note as needed.
*/
export const getStickyNoteMinSize = ({
fontSize,
fontFamily,
}: Pick<ExcalidrawTextElement, "fontSize" | "fontFamily">) => {
const lineHeightPx = Math.ceil(
normalizeStickyNoteFontSize(fontSize) * getLineHeight(fontFamily),
);
return {
width: Math.max(
STICKY_NOTE_MIN_SIZE,
lineHeightPx + STICKY_NOTE_PADDING * 2,
),
height: Math.max(
STICKY_NOTE_MIN_SIZE,
lineHeightPx + STICKY_NOTE_BODY_INSET_Y,
),
};
};
// -----------------------------------------------------------------------------
// layout — one pure calculation, two ways of applying it
// -----------------------------------------------------------------------------
export type StickyNoteLayoutAnchor = VerticalResizeAnchor;
export type StickyNoteLayoutOpts = {
/** unwrapped text to lay out; defaults to the label's `originalText` */
originalText?: string;
/**
* absolute base-height intent — the gesture-start value to preserve, or the
* height a resize asked for. Omitted = keep the note's live `baseHeight`
* (typing, style changes, restore).
*/
baseHeight?: number;
/**
* absolute font-ceiling intent (a proportional resize passes
* `gesture-start ceiling × scale`). Omitted = keep the label's live ceiling.
* Never a multiplier on the live value — that compounds across pointer-moves.
*/
baseFontSize?: number;
/** the edge that stays put when the content correction changes the height */
anchor?: StickyNoteLayoutAnchor;
};
export type StickyNoteLayout = {
container: Pick<
ExcalidrawStickyNoteElement,
"x" | "y" | "width" | "height" | "baseHeight"
>;
text: Pick<
ExcalidrawTextElement,
| "text"
| "fontSize"
| "baseFontSize"
| "width"
| "height"
| "x"
| "y"
| "angle"
> | null;
};
type FontFit = {
text: string;
fontSize: number;
width: number;
height: number;
};
// `computeBoundTextPosition` only consults the map for arrow containers
const NO_ELEMENTS: ElementsMap = new Map();
const getStickyNoteBaseWidth = (container: ExcalidrawStickyNoteElement) => {
return Math.max(container.width, STICKY_NOTE_MIN_SIZE);
};
/**
* Largest font size on the grid `{ceiling − k·STEP} ∪ {min}` whose wrapped
* text fits the note; `min` when nothing fits (the note then grows). The grid
* is anchored at the ceiling so the result never depends on earlier edits.
* Warm-started from the previously fitted size: the common keystroke costs one
* or two wrap+measure passes, a cold search at most log2(steps) + 2.
*/
const fitStickyNoteFont = (
fit: (fontSize: number) => FontFit,
{
baseFontSize,
fontSizeMin,
maxWidth,
maxHeight,
warmStart,
}: {
baseFontSize: number;
fontSizeMin: number;
maxWidth: number;
maxHeight: number;
warmStart: number;
},
): FontFit => {
const steps = Math.max(
0,
Math.ceil((baseFontSize - fontSizeMin) / STICKY_NOTE_FONT_STEP),
);
const sizeAt = (index: number) =>
index >= steps ? fontSizeMin : baseFontSize - index * STICKY_NOTE_FONT_STEP;
const fits = new Map<number, FontFit>();
const at = (index: number) => {
let result = fits.get(index);
if (!result) {
result = fit(sizeAt(index));
fits.set(index, result);
}
return result;
};
const doesFit = (index: number) => {
const result = at(index);
return result.width <= maxWidth && result.height <= maxHeight;
};
if (steps === 0) {
return at(0);
}
// the previous fitted size, snapped onto the grid and clamped into the
// current interval (a lowered ceiling must not keep the old larger size)
const warm = clamp(
Math.round((baseFontSize - warmStart) / STICKY_NOTE_FONT_STEP),
0,
steps,
);
// binary search for the smallest index (largest font) that fits
let lo: number;
let hi: number;
if (doesFit(warm)) {
if (warm === 0 || !doesFit(warm - 1)) {
return at(warm);
}
lo = 0;
hi = warm - 1;
} else {
if (warm === steps) {
return at(steps);
}
lo = warm + 1;
hi = steps;
}
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (doesFit(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
return at(lo);
};
/**
* The single source of truth for a sticky note's geometry: wraps the label at
* the note's width, fits the font under the ceiling, grows the note past
* `baseHeight` only when the text still overflows at the minimum size, and
* positions the label inside. Pure — returns the updates for both elements.
*/
export const getStickyNoteLayout = (
container: ExcalidrawStickyNoteElement,
textElement: ExcalidrawTextElement | null,
opts: StickyNoteLayoutOpts = {},
): StickyNoteLayout => {
const baseWidth = getStickyNoteBaseWidth(container);
const baseHeight = Math.max(
opts.baseHeight ?? (container.baseHeight || container.height),
STICKY_NOTE_MIN_SIZE,
);
const anchor = opts.anchor ?? "top";
if (!textElement) {
// an empty note sits at its base height
return {
container: {
...getPositionAfterHeightChange(container, baseHeight, anchor),
width: baseWidth,
height: baseHeight,
baseHeight,
},
text: null,
};
}
const originalText = opts.originalText ?? textElement.originalText;
const baseFontSize = normalizeStickyNoteFontSize(
opts.baseFontSize ?? textElement.baseFontSize ?? textElement.fontSize,
);
const fontSizeMin = Math.min(STICKY_NOTE_MIN_FONT_SIZE, baseFontSize);
const maxWidth = Math.max(baseWidth - STICKY_NOTE_PADDING * 2, 1);
const maxHeight = Math.max(baseHeight - STICKY_NOTE_BODY_INSET_Y, 0);
const { fontFamily, lineHeight } = textElement;
const fit = (fontSize: number): FontFit => {
const font = getFontString({ fontFamily, fontSize });
const text = wrapText(originalText, font, maxWidth);
return { text, fontSize, ...measureText(text, font, lineHeight) };
};
const isBlank = !originalText.trim();
const fitted: FontFit = isBlank
? {
text: "",
fontSize: baseFontSize,
...measureText(
"",
getFontString({ fontFamily, fontSize: baseFontSize }),
lineHeight,
),
}
: fitStickyNoteFont(fit, {
baseFontSize,
fontSizeMin,
maxWidth,
maxHeight,
warmStart: textElement.fontSize,
});
const height = isBlank
? baseHeight
: Math.max(baseHeight, fitted.height + STICKY_NOTE_BODY_INSET_Y);
const nextContainer = {
...getPositionAfterHeightChange(container, height, anchor),
width: baseWidth,
height,
baseHeight,
};
const { x, y } = computeBoundTextPosition(
{ ...container, ...nextContainer },
{
...textElement,
text: fitted.text,
fontSize: fitted.fontSize,
width: fitted.width,
height: fitted.height,
} as ExcalidrawTextElementWithContainer,
NO_ELEMENTS,
);
return {
container: nextContainer,
text: {
text: fitted.text,
fontSize: fitted.fontSize,
baseFontSize,
width: fitted.width,
height: fitted.height,
x,
y,
angle: container.angle,
},
};
};
/**
* Resize intents for a sticky note — the §3.3 matrix of the plan. Every value
* is absolute and derived from the gesture-start snapshot on each pointer-move,
* so releasing Shift (or Alt) mid-gesture restores the original base height
* and ceiling instead of keeping values a previous move scaled.
*
* - width-only gestures (free E/W, Stats W) preserve the base height
* - height-changing gestures use the requested height as the new base
* - proportional gestures (Shift on any handle, aspect-locked multi-select,
* Stats group) additionally scale the font ceiling with the note
* - flips preserve everything
* - the content correction anchors at the edge the gesture holds still
*/
export const getStickyNoteResizeIntent = (
/** the note with the requested geometry already applied */
container: ExcalidrawStickyNoteElement,
originalElementsMap: ElementsMap,
handleDirection: TransformHandleDirection,
{
proportional,
fromCenter,
flip = false,
}: { proportional: boolean; fromCenter: boolean; flip?: boolean },
): Pick<StickyNoteLayoutOpts, "baseHeight" | "baseFontSize" | "anchor"> => {
const origContainer = originalElementsMap.get(container.id);
const origSticky = isStickyNoteElement(origContainer)
? origContainer
: container;
const origText = getBoundTextElement(origSticky, originalElementsMap);
const ceiling = origText
? origText.baseFontSize ?? origText.fontSize
: undefined;
if (flip) {
return { baseHeight: origSticky.baseHeight, baseFontSize: ceiling };
}
const changesHeight =
proportional ||
handleDirection.includes("n") ||
handleDirection.includes("s");
const scale =
proportional && origSticky.width ? container.width / origSticky.width : 1;
const isSideHandle = handleDirection.length === 1;
return {
baseHeight: changesHeight ? container.height : origSticky.baseHeight,
baseFontSize: ceiling === undefined ? undefined : ceiling * scale,
anchor: fromCenter
? "center"
: handleDirection.includes("n")
? "bottom"
: proportional &&
isSideHandle &&
(handleDirection === "e" || handleDirection === "w")
? // Shift+E/W holds the opposite side's midpoint, i.e. the vertical center
"center"
: "top",
};
};
/**
* Applies `getStickyNoteLayout` to a live scene, then runs the bound-arrow
* pass unless the caller already owns one (`bindings: false`) or needs to
* forward its context (`bindings: { simultaneouslyUpdated }` — arrows resized
* in the same gesture must not be moved by the pass, `updateBoundElements`
* skips them only when told).
*/
export const updateStickyNoteLayout = (
container: ExcalidrawStickyNoteElement,
scene: Scene,
{
text,
bindings,
...layoutOpts
}: StickyNoteLayoutOpts & {
/** the label to lay out when it is an uncommitted clone (font actions clone before install) */
text?: ExcalidrawTextElement | null;
bindings?:
| { simultaneouslyUpdated?: readonly NonDeletedExcalidrawElement[] }
| false;
} = {},
): StickyNoteLayout => {
const elementsMap = scene.getNonDeletedElementsMap();
const textElement =
text === undefined ? getBoundTextElement(container, elementsMap) : text;
const layout = getStickyNoteLayout(container, textElement, layoutOpts);
scene.mutateElement(container, layout.container);
if (textElement && layout.text) {
scene.mutateElement(textElement, layout.text);
}
if (bindings !== false && !container.isDeleted) {
updateBoundElements(
container as NonDeletedExcalidrawElement,
scene,
bindings || undefined,
);
}
return layout;
};
const STICKY_NOTE_LAYOUT_INPUTS = {
container: ["x", "y", "width", "baseHeight", "angle"],
text: [
"originalText",
"baseFontSize",
"fontFamily",
"lineHeight",
"textAlign",
"verticalAlign",
],
} as const;
const hasStickyNoteLayoutInputChanged = (
container: ExcalidrawStickyNoteElement,
textElement: ExcalidrawTextElement | null,
prevElementsMap: ElementsMap,
) => {
const prevContainer = prevElementsMap.get(container.id);
const prevText = textElement ? prevElementsMap.get(textElement.id) : null;
if (
!prevContainer ||
(textElement && !prevText) ||
(!textElement &&
prevContainer.boundElements?.some(({ type }) => type === "text"))
) {
return true;
}
return (
STICKY_NOTE_LAYOUT_INPUTS.container.some(
(key) => (prevContainer as any)[key] !== container[key],
) ||
(!!textElement &&
STICKY_NOTE_LAYOUT_INPUTS.text.some(
(key) => (prevText as any)[key] !== textElement[key],
))
);
};
/**
* Applies `getStickyNoteLayout` inside an immutable elements array (property
* actions, paste styles, restore): the notes among `affectedIds` — or the
* notes whose labels are — get both halves merged into their clones. Elements
* that need no change keep their identity and version; when `prevElementsMap`
* is given, notes whose layout inputs did not change skip the fit entirely.
* Bound arrows are the caller's job once the result is installed.
*/
export const relayoutStickyNotes = <T extends ExcalidrawElement>(
elements: readonly T[],
affectedIds: ReadonlySet<ExcalidrawElement["id"]>,
opts?: { prevElementsMap?: ElementsMap },
): readonly T[] => {
if (!affectedIds.size) {
return elements;
}
const elementsMap = arrayToMap(elements);
const containerIds = new Set<ExcalidrawElement["id"]>();
for (const id of affectedIds) {
const element = elementsMap.get(id);
if (!element || element.isDeleted) {
continue;
}
if (isStickyNoteElement(element)) {
containerIds.add(element.id);
} else if (isTextElement(element) && element.containerId) {
const container = elementsMap.get(element.containerId);
if (container && !container.isDeleted && isStickyNoteElement(container)) {
containerIds.add(container.id);
}
}
}
if (!containerIds.size) {
return elements;
}
const replacements = new Map<ExcalidrawElement["id"], T>();
for (const id of containerIds) {
const container = elementsMap.get(id) as ExcalidrawStickyNoteElement;
const textElement = getBoundTextElement(container, elementsMap);
if (
opts?.prevElementsMap &&
!hasStickyNoteLayoutInputChanged(
container,
textElement,
opts.prevElementsMap,
)
) {
continue;
}
const layout = getStickyNoteLayout(container, textElement);
const nextContainer = newElementWith(container, layout.container);
if (nextContainer !== container) {
replacements.set(id, nextContainer as unknown as T);
}
if (textElement && layout.text) {
const nextText = newElementWith(textElement, layout.text);
if (nextText !== textElement) {
replacements.set(textElement.id, nextText as unknown as T);
}
}
}
if (!replacements.size) {
return elements;
}
return elements.map((element) => replacements.get(element.id) ?? element);
};
+105 -21
View File
@@ -3,6 +3,8 @@ import {
ARROW_LABEL_WIDTH_FRACTION,
BOUND_TEXT_PADDING,
DEFAULT_FONT_SIZE,
STICKY_NOTE_BODY_INSET_Y,
STICKY_NOTE_PADDING,
TEXT_ALIGN,
VERTICAL_ALIGN,
getFontString,
@@ -19,12 +21,15 @@ import {
updateOriginalContainerCache,
} from "./containerCache";
import { LinearElementEditor } from "./linearElementEditor";
import { getPositionAfterHeightChange } from "./sizeHelpers";
import { updateStickyNoteLayout } from "./stickyNote";
import { measureText } from "./textMeasurements";
import { wrapText } from "./textWrapping";
import {
isBoundToContainer,
isArrowElement,
isStickyNoteElement,
isTextElement,
} from "./typeChecks";
@@ -50,6 +55,14 @@ export const redrawTextBoundingBox = (
) => {
const elementsMap = scene.getNonDeletedElementsMap();
if (container && isStickyNoteElement(container)) {
// the sticky fit owns both halves (label + note geometry). `textElement`
// may be an uncommitted clone (font actions clone before install), so it
// is passed explicitly instead of looked up in the scene
updateStickyNoteLayout(container, scene, { text: textElement });
return;
}
let maxWidth = undefined;
if (!isProdEnv()) {
@@ -145,7 +158,14 @@ export const handleBindTextResize = (
transformHandleType: MaybeTransformHandleType,
shouldMaintainAspectRatio = false,
shouldResizeFromCenter = false,
flipByY = false,
) => {
if (isStickyNoteElement(container)) {
// resize callers pass their intents to `updateStickyNoteLayout` directly
// and own the bound-arrow pass; this is the fallback for generic callers
updateStickyNoteLayout(container, scene, { bindings: false });
return;
}
const elementsMap = scene.getNonDeletedElementsMap();
const boundTextElementId = getBoundTextElementId(container);
if (!boundTextElementId) {
@@ -190,24 +210,24 @@ export const handleBindTextResize = (
container.type,
);
const diff = containerHeight - container.height;
// fix the y coord when resizing from ne/nw/n
// Crossing the opposite edge swaps the anchor for text-driven growth.
const shouldResizeFromTop =
transformHandleType === "n" ||
transformHandleType === "ne" ||
transformHandleType === "nw";
(transformHandleType === "n" ||
transformHandleType === "ne" ||
transformHandleType === "nw") !== flipByY;
let offsetY = 0;
if (!isArrowElement(container)) {
if (shouldResizeFromCenter) {
offsetY = diff / 2;
} else if (shouldResizeFromTop) {
offsetY = diff;
}
}
scene.mutateElement(container, {
height: containerHeight,
y: container.y - offsetY,
...(!isArrowElement(container) &&
getPositionAfterHeightChange(
container,
containerHeight,
shouldResizeFromCenter
? "center"
: shouldResizeFromTop
? "bottom"
: "top",
)),
});
}
@@ -248,6 +268,18 @@ export const computeBoundTextPosition = (
y = containerCoords.y;
} else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
y = containerCoords.y + (maxContainerHeight - boundTextElement.height);
} else if (isStickyNoteElement(container)) {
// a note's label body ends above the creation-date footer, but a label
// centered in that body sits visibly high — center it in the whole
// padded note while it stays clear of the footer, and only push it up
// against the body's bottom once it would overlap
const paddedHeight = container.height - STICKY_NOTE_PADDING * 2;
y =
containerCoords.y +
Math.min(
(paddedHeight - boundTextElement.height) / 2,
maxContainerHeight - boundTextElement.height,
);
} else {
y =
containerCoords.y +
@@ -264,10 +296,17 @@ export const computeBoundTextPosition = (
const angle = (container.angle ?? 0) as Radians;
if (angle !== 0) {
const contentCenter = pointFrom(
containerCoords.x + maxContainerWidth / 2,
containerCoords.y + maxContainerHeight / 2,
);
// A sticky's footer makes its body asymmetric. The body still rotates
// about the note's center, rather than about its own (higher) center.
const contentCenter = isStickyNoteElement(container)
? pointFrom(
container.x + container.width / 2,
container.y + container.height / 2,
)
: pointFrom(
containerCoords.x + maxContainerWidth / 2,
containerCoords.y + maxContainerHeight / 2,
);
const textCenter = pointFrom(
x + boundTextElement.width / 2,
y + boundTextElement.height / 2,
@@ -355,8 +394,11 @@ export const getContainerCenter = (
};
export const getContainerCoords = (container: ExcalidrawElement) => {
let offsetX = BOUND_TEXT_PADDING;
let offsetY = BOUND_TEXT_PADDING;
const padding = isStickyNoteElement(container)
? STICKY_NOTE_PADDING
: BOUND_TEXT_PADDING;
let offsetX = padding;
let offsetY = padding;
if (container.type === "ellipse") {
// The derivation of coordinates is explained in https://github.com/excalidraw/excalidraw/pull/6172
@@ -401,6 +443,35 @@ export const getBoundTextElementPosition = (
}
};
/**
* Returns the text element with its accurate coords. An arrow label's
* position is derived from the arrow at render time rather than kept in
* sync on the element itself (see getBoundTextElementPosition), so
* consumers reading a label's coords directly must go through this helper.
*/
export const getTextElementWithAccuratePosition = <
T extends ExcalidrawTextElement,
>(
textElement: T,
elementsMap: ElementsMap,
): T => {
if (!textElement.containerId) {
return textElement;
}
const container = elementsMap.get(textElement.containerId);
if (!container || !isArrowElement(container)) {
return textElement;
}
return {
...textElement,
...LinearElementEditor.getBoundTextElementPosition(
container,
textElement as ExcalidrawTextElementWithContainer,
elementsMap,
),
};
};
export const shouldAllowVerticalAlign = (
selectedElements: readonly ExcalidrawElement[],
elementsMap: ElementsMap,
@@ -436,6 +507,7 @@ export const suppportsHorizontalAlign = (
const VALID_CONTAINER_TYPES = new Set([
"rectangle",
"stickynote",
"ellipse",
"diamond",
"arrow",
@@ -487,7 +559,13 @@ export const getBoundTextMaxWidth = (
// Math.round(width / 2) - https://github.com/excalidraw/excalidraw/pull/6265
return Math.round(width / 2) - BOUND_TEXT_PADDING * 2;
}
return width - BOUND_TEXT_PADDING * 2;
return (
width -
(isStickyNoteElement(container)
? STICKY_NOTE_PADDING
: BOUND_TEXT_PADDING) *
2
);
};
export const getBoundTextMaxHeight = (
@@ -495,6 +573,10 @@ export const getBoundTextMaxHeight = (
boundTextElement: ExcalidrawTextElementWithContainer,
) => {
const { height } = container;
if (isStickyNoteElement(container)) {
// the label body ends above the creation-date footer
return Math.max(0, height - STICKY_NOTE_BODY_INSET_Y);
}
if (isArrowElement(container)) {
const containerHeight = height - BOUND_TEXT_PADDING * 8 * 2;
if (containerHeight <= 0) {
@@ -531,3 +613,5 @@ export const getTextFromElements = (
.join(separator);
return text;
};
export const DEFAULT_BOUND_TEXT_LABEL_POSITION = 0.5;
+101 -14
View File
@@ -11,30 +11,44 @@ import {
assertNever,
cloneJSON,
getFontString,
getUpdatedTimestamp,
isDevEnv,
toBrandedType,
getLineHeight,
DEFAULT_STICKY_NOTE_SIZE,
isTransparent,
DEFAULT_ZOOM,
} from "@excalidraw/common";
import type { MarkOptional } from "@excalidraw/common/utility-types";
import type { Zoom } from "@excalidraw/excalidraw/types";
import { bindBindingElement } from "./binding";
import {
newArrowElement,
newElement,
newEmbeddableElement,
newFrameElement,
newFreeDrawElement,
newIframeElement,
newImageElement,
newLinearElement,
newMagicFrameElement,
newTextElement,
type ElementConstructorOpts,
newStickyNoteElement,
normalizeStickyNoteGeometry,
} from "./newElement";
import { normalizeStickyNoteStrokeColor } from "./stickyNote";
import { measureText, normalizeText } from "./textMeasurements";
import { isArrowElement } from "./typeChecks";
import { isArrowElement, isStickyNoteElement } from "./typeChecks";
import { syncInvalidIndices } from "./fractionalIndex";
import { redrawTextBoundingBox } from "./textElement";
import {
DEFAULT_BOUND_TEXT_LABEL_POSITION,
redrawTextBoundingBox,
} from "./textElement";
import { LinearElementEditor } from "./linearElementEditor";
@@ -63,8 +77,19 @@ import type {
Ordered,
TextAlign,
VerticalAlign,
ExcalidrawStickyNoteElement,
} from "./types";
/**
* Options for elements generated from a skeleton fragment (bound labels and
* binding endpoints). Such elements are always constructed fresh, hence they
* never carry a creation time of their own.
*/
type FragmentConstructorOpts = MarkOptional<
Omit<ElementConstructorOpts, "created">,
"x" | "y"
>;
export type ValidLinearElement = {
type: "arrow" | "line";
x: number;
@@ -75,7 +100,7 @@ export type ValidLinearElement = {
fontFamily?: FontFamilyValues;
textAlign?: TextAlign;
verticalAlign?: VerticalAlign;
} & MarkOptional<ElementConstructorOpts, "x" | "y">;
} & FragmentConstructorOpts;
end?:
| (
| (
@@ -115,9 +140,9 @@ export type ValidLinearElement = {
text: string;
}
) &
Partial<ExcalidrawTextElement>)
Partial<Omit<ExcalidrawTextElement, "created">>)
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
FragmentConstructorOpts;
start?:
| (
| (
@@ -157,9 +182,9 @@ export type ValidLinearElement = {
text: string;
}
) &
Partial<ExcalidrawTextElement>)
Partial<Omit<ExcalidrawTextElement, "created">>)
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
FragmentConstructorOpts;
} & Partial<ExcalidrawLinearElement>;
export type ValidContainer =
@@ -172,9 +197,21 @@ export type ValidContainer =
fontFamily?: FontFamilyValues;
textAlign?: TextAlign;
verticalAlign?: VerticalAlign;
} & MarkOptional<ElementConstructorOpts, "x" | "y">;
} & FragmentConstructorOpts;
} & ElementConstructorOpts;
/**
* A sticky note: an always-filled note whose label auto-fits. `label.fontSize`
* is the font ceiling the fit shrinks from; the note grows past its height
* (kept as `baseHeight`) only once the label hits the minimum font size.
*/
export type ValidStickyNote = {
type: "stickynote";
id?: ExcalidrawStickyNoteElement["id"];
label?: Extract<ValidContainer, { label?: unknown }>["label"];
} & ElementConstructorOpts &
Partial<Pick<ExcalidrawStickyNoteElement, "baseHeight">>;
export type ExcalidrawElementSkeleton =
| Extract<
Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
@@ -186,6 +223,7 @@ export type ExcalidrawElementSkeleton =
y: number;
} & Partial<ExcalidrawLinearElement>)
| ValidContainer
| ValidStickyNote
| ValidLinearElement
| ({
type: "text";
@@ -220,9 +258,19 @@ const DEFAULT_DIMENSION = 100;
const bindTextToContainer = (
container: ExcalidrawElement,
textProps: { text: string } & MarkOptional<ElementConstructorOpts, "x" | "y">,
textProps: { text: string } & FragmentConstructorOpts,
scene: Scene,
) => {
// a note and its label share one ink: a label that sets its own color
// gives it to the note (the footer paints with it); transparent falls
// back to the note's
const stickyInk = isStickyNoteElement(container)
? normalizeStickyNoteStrokeColor(
textProps.strokeColor && !isTransparent(textProps.strokeColor)
? textProps.strokeColor
: container.strokeColor,
)
: null;
const textElement: ExcalidrawTextElement = newTextElement({
x: 0,
y: 0,
@@ -230,7 +278,10 @@ const bindTextToContainer = (
verticalAlign: VERTICAL_ALIGN.MIDDLE,
...textProps,
containerId: container.id,
strokeColor: textProps.strokeColor || container.strokeColor,
strokeColor: stickyInk ?? (textProps.strokeColor || container.strokeColor),
labelPosition: isArrowElement(container)
? DEFAULT_BOUND_TEXT_LABEL_POSITION
: null,
});
Object.assign(container, {
@@ -238,6 +289,9 @@ const bindTextToContainer = (
type: "text",
id: textElement.id,
}),
...(stickyInk && stickyInk !== container.strokeColor
? { strokeColor: stickyInk }
: null),
});
redrawTextBoundingBox(textElement, container, scene);
@@ -251,6 +305,7 @@ const bindLinearElementToElement = (
end: ValidLinearElement["end"],
elementStore: ElementStore,
scene: Scene,
zoom: Zoom,
): {
linearElement: ExcalidrawLinearElement;
startBoundElement?: ExcalidrawElement;
@@ -338,6 +393,7 @@ const bindLinearElementToElement = (
"orbit",
"start",
scene,
zoom,
);
}
}
@@ -414,6 +470,7 @@ const bindLinearElementToElement = (
"orbit",
"end",
scene,
zoom,
);
}
}
@@ -525,11 +582,14 @@ export const convertToExcalidrawElements = (
const oldToNewElementIdMap = new Map<string, string>();
// Create individual elements
// regenerated ids mean new instances, hence a fresh creation time as well
const created = getUpdatedTimestamp();
for (const element of elements) {
let excalidrawElement: ExcalidrawElement;
const originalId = element.id;
if (opts?.regenerateIds !== false) {
Object.assign(element, { id: randomId() });
Object.assign(element, { id: randomId(), created });
}
switch (element.type) {
@@ -628,10 +688,32 @@ export const convertToExcalidrawElements = (
});
break;
}
case "freedraw":
case "iframe":
case "freedraw": {
excalidrawElement = newFreeDrawElement({ ...element });
break;
}
case "iframe": {
excalidrawElement = newIframeElement({ ...element });
break;
}
case "stickynote": {
const width = element.width || DEFAULT_STICKY_NOTE_SIZE;
const height = element.height || DEFAULT_STICKY_NOTE_SIZE;
// finalized geometry (min size, baseHeight ≤ height) — only a
// pointer-down draft is exempt from it
excalidrawElement = normalizeStickyNoteGeometry(
newStickyNoteElement({
...element,
type: "stickynote",
width,
height,
baseHeight: element.baseHeight ?? height,
}),
);
break;
}
case "embeddable": {
excalidrawElement = element;
excalidrawElement = newEmbeddableElement({ ...element });
break;
}
@@ -668,8 +750,11 @@ export const convertToExcalidrawElements = (
case "rectangle":
case "ellipse":
case "diamond":
case "stickynote":
case "arrow": {
if (element.label?.text) {
// for a sticky note this runs the sticky fit (via
// `redrawTextBoundingBox`): the label's font size becomes its ceiling
let [container, text] = bindTextToContainer(
excalidrawElement,
element?.label,
@@ -702,6 +787,7 @@ export const convertToExcalidrawElements = (
originalEnd,
elementStore,
scene,
DEFAULT_ZOOM,
);
container = linearElement;
elementStore.add(linearElement);
@@ -727,6 +813,7 @@ export const convertToExcalidrawElements = (
end,
elementStore,
scene,
DEFAULT_ZOOM,
);
elementStore.add(linearElement);
+18 -1
View File
@@ -29,6 +29,7 @@ import type {
ExcalidrawLineElement,
ExcalidrawFlowchartNodeElement,
ExcalidrawLinearElementSubType,
ExcalidrawStickyNoteElement,
} from "./types";
export const isInitializedImageElement = <T extends ExcalidrawElement>(
@@ -69,6 +70,12 @@ export const isTextElement = <T extends ExcalidrawElement>(
return element != null && element.type === "text";
};
export const isStickyNoteElement = <T extends ExcalidrawElement>(
element: T | null | undefined,
): element is T & ExcalidrawStickyNoteElement => {
return element != null && element.type === "stickynote";
};
export const isFrameElement = <T extends ExcalidrawElement>(
element: T | null,
): element is T & ExcalidrawFrameElement => {
@@ -182,6 +189,7 @@ export const isBindableElement = <T extends ExcalidrawElement>(
element != null &&
(!element.locked || includeLocked === true) &&
(element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "diamond" ||
element.type === "ellipse" ||
element.type === "image" ||
@@ -199,6 +207,7 @@ export const isRectanguloidElement = <T extends ExcalidrawElement>(
return (
element != null &&
(element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "diamond" ||
element.type === "image" ||
element.type === "iframe" ||
@@ -217,6 +226,7 @@ export const isRectangularElement = <T extends ExcalidrawElement>(
return (
element != null &&
(element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "image" ||
element.type === "text" ||
element.type === "iframe" ||
@@ -235,6 +245,7 @@ export const isTextBindableContainer = <T extends ExcalidrawElement>(
element != null &&
(!element.locked || includeLocked === true) &&
(element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "diamond" ||
element.type === "ellipse" ||
isArrowElement(element))
@@ -252,6 +263,7 @@ export const isExcalidrawElement = (
case "text":
case "diamond":
case "rectangle":
case "stickynote":
case "iframe":
case "embeddable":
case "ellipse":
@@ -276,6 +288,7 @@ export const isFlowchartNodeElement = <T extends ExcalidrawElement>(
): element is T & ExcalidrawFlowchartNodeElement => {
return (
element.type === "rectangle" ||
element.type === "stickynote" ||
element.type === "ellipse" ||
element.type === "diamond"
);
@@ -313,7 +326,10 @@ export const isUsingAdaptiveRadius = (type: string) =>
type === "image";
export const isUsingProportionalRadius = (type: string) =>
type === "line" || type === "arrow" || type === "diamond";
type === "line" ||
type === "arrow" ||
type === "diamond" ||
type === "stickynote";
export const canApplyRoundnessTypeToElement = (
roundnessType: RoundnessType,
@@ -397,6 +413,7 @@ export const canBecomePolygon = (
export const isEligibleFrameChildType = (type: ElementOrToolType) => {
switch (type) {
case "rectangle":
case "stickynote":
case "diamond":
case "ellipse":
case "arrow":
+37 -1
View File
@@ -76,6 +76,11 @@ type _ExcalidrawElementBase = Readonly<{
boundElements: readonly BoundElement[] | null;
/** epoch (ms) timestamp of last element update */
updated: number;
/** Client wall-clock creation time in epoch milliseconds; null if unknown.
Preserved for this element's lifetime, including edits and undo/redo,
and excluded from `ElementUpdate` (mutateElement / newElementWith).
Duplicating an element starts a new lifetime. Not an ordering clock. */
created: number | null;
link: string | null;
locked: boolean;
customData?: Record<string, any>;
@@ -89,6 +94,16 @@ export type ExcalidrawRectangleElement = _ExcalidrawElementBase & {
type: "rectangle";
};
export type ExcalidrawStickyNoteElement = _ExcalidrawElementBase &
Readonly<{
type: "stickynote";
/**
* The height the user set, from which the layout derives `height`: the
* note grows above it to fit its label and never shrinks below it
*/
baseHeight: number;
}>;
export type ExcalidrawDiamondElement = _ExcalidrawElementBase & {
type: "diamond";
};
@@ -185,11 +200,13 @@ export type ExcalidrawGenericElement =
export type ExcalidrawFlowchartNodeElement =
| ExcalidrawRectangleElement
| ExcalidrawStickyNoteElement
| ExcalidrawDiamondElement
| ExcalidrawEllipseElement;
export type ExcalidrawRectanguloidElement =
| ExcalidrawRectangleElement
| ExcalidrawStickyNoteElement
| ExcalidrawImageElement
| ExcalidrawTextElement
| ExcalidrawFreeDrawElement
@@ -205,6 +222,7 @@ export type ExcalidrawRectanguloidElement =
*/
export type ExcalidrawElement =
| ExcalidrawGenericElement
| ExcalidrawStickyNoteElement
| ExcalidrawTextElement
| ExcalidrawLinearElement
| ExcalidrawArrowElement
@@ -237,10 +255,19 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
type: "text";
fontSize: number;
fontFamily: FontFamilyValues;
/**
* The font size the user picked, from which the layout derives `fontSize`.
* Today only sticky note labels have one: the auto-fit shrinks below it
* and never above it (compare `baseHeight`, which the note grows above).
* `null` for every other text. Read it through `getBaseFontSize` —
* generic binding repair can detach a label without clearing this, so
* the container decides its meaning.
*/
baseFontSize: number | null;
text: string;
textAlign: TextAlign;
verticalAlign: VerticalAlign;
containerId: ExcalidrawGenericElement["id"] | null;
containerId: ExcalidrawTextContainer["id"] | null;
originalText: string;
/**
* If `true` the width will fit the text. If `false`, the text will
@@ -254,10 +281,18 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
* with font size (using `getLineHeightInPx` helper).
*/
lineHeight: number & { _brand: "unitlessLineHeight" };
/**
* Position of text bound to a linear element (such as an arrow),
* expressed as a normalized arc-length parameter (0–1) along the
* container's whole path. Independent of how the path is segmented,
* so it survives midpoint insertion and other geometry changes.
* */
labelPosition?: number | null;
}>;
export type ExcalidrawBindableElement =
| ExcalidrawRectangleElement
| ExcalidrawStickyNoteElement
| ExcalidrawDiamondElement
| ExcalidrawEllipseElement
| ExcalidrawTextElement
@@ -269,6 +304,7 @@ export type ExcalidrawBindableElement =
export type ExcalidrawTextContainer =
| ExcalidrawRectangleElement
| ExcalidrawStickyNoteElement
| ExcalidrawDiamondElement
| ExcalidrawEllipseElement
| ExcalidrawArrowElement;
+214 -65
View File
@@ -8,6 +8,7 @@ import {
import {
bezierEquation,
clamp,
curve,
curveCatmullRomCubicApproxPoints,
curveOffsetPoints,
@@ -26,7 +27,7 @@ import {
type GlobalPoint,
} from "@excalidraw/math";
import type { Curve, LineSegment, LocalPoint } from "@excalidraw/math";
import type { Curve, LineSegment, LocalPoint, Radians } from "@excalidraw/math";
import type {
AppState,
@@ -40,13 +41,14 @@ import { generateLinearCollisionShape } from "./shape";
import { hitElementItself, isPointInElement } from "./collision";
import { LinearElementEditor } from "./linearElementEditor";
import { isRectangularElement } from "./typeChecks";
import { maxBindingDistance_simple } from "./binding";
import { isElbowArrow, isRectangularElement } from "./typeChecks";
import { getBindingGap, maxBindingDistance_simple } from "./binding";
import {
getGlobalFixedPointForBindableElement,
normalizeFixedPoint,
} from "./binding";
import { getStickyNoteCornerRadius } from "./stickyNote";
import type {
ElementsMap,
@@ -59,6 +61,8 @@ import type {
ExcalidrawRectanguloidElement,
} from "./types";
export type LinearPathSegment = LineSegment<GlobalPoint> | Curve<GlobalPoint>;
type ElementShape = [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]];
const ElementShapesCache = new WeakMap<
@@ -125,7 +129,7 @@ const setElementShapesCacheEntry = <T extends ExcalidrawElement>(
export function deconstructLinearOrFreeDrawElement(
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, 0);
if (cachedShape) {
@@ -133,8 +137,8 @@ export function deconstructLinearOrFreeDrawElement(
}
const ops = generateLinearCollisionShape(element, elementsMap);
const lines = [];
const curves = [];
const lines: LineSegment<GlobalPoint>[] = [];
const curves: Curve<GlobalPoint>[] = [];
for (let idx = 0; idx < ops.length; idx += 1) {
const op = ops[idx];
@@ -193,12 +197,43 @@ export function deconstructLinearOrFreeDrawElement(
}
}
const shape = [lines, curves] as ElementShape;
const shape: ElementShape = [lines, curves];
setElementShapesCacheEntry(element, shape, 0);
return shape;
}
export function getLinearElementPathSegments(
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
elementsMap: ElementsMap,
): LinearPathSegment[] {
// For now, model elbow arrows as their unrounded logical path. Rounded
// joints can be incorporated once the path model supports mixed straight
// and curved segments.
if (isElbowArrow(element)) {
return element.points
.slice(1)
.map((point, index) =>
lineSegment<GlobalPoint>(
pointFrom<GlobalPoint>(
element.x + element.points[index][0],
element.y + element.points[index][1],
),
pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
),
);
}
const [lines, curves] = deconstructLinearOrFreeDrawElement(
element,
elementsMap,
);
// Non-elbow paths currently contain only one segment type. Mixed paths
// should consume an ordered operation stream instead of these type buckets.
return curves.length > 0 ? curves : lines;
}
/**
* Get the building components of a rectanguloid element in the form of
* line segments and curves **unrotated**.
@@ -210,17 +245,17 @@ export function deconstructLinearOrFreeDrawElement(
export function deconstructRectanguloidElement(
element: ExcalidrawRectanguloidElement,
offset: number = 0,
): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, offset);
if (cachedShape) {
return cachedShape;
}
let radius = getCornerRadius(
Math.min(element.width, element.height),
element,
);
let radius =
element.type === "stickynote"
? getStickyNoteCornerRadius(element)
: getCornerRadius(Math.min(element.width, element.height), element);
if (radius === 0) {
radius = 0.01;
@@ -422,7 +457,7 @@ export function getDiamondBaseCorners(
export function deconstructDiamondElement(
element: ExcalidrawDiamondElement,
offset: number = 0,
): [LineSegment<GlobalPoint>[], Curve<GlobalPoint>[]] {
): ElementShape {
const cachedShape = getElementShapesCacheEntry(element, offset);
if (cachedShape) {
@@ -597,67 +632,179 @@ const getDiagonalsForBindableElement = (
return [diagonalOne, diagonalTwo];
};
export const getSnapOutlineMidPoint = (
point: GlobalPoint,
/**
* `onAxis` is true for the midpoints on the element's axes (the side midpoints,
* or a diamond's vertices), whose direction from the center is unambiguous,
* and false for a diamond's edge midpoints
*/
const getSnappedMidpointForElbowArrow = (
element: ExcalidrawBindableElement,
point: GlobalPoint,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
) => {
const center = elementCenterPoint(element, elementsMap);
const sideMidpoints =
element.type === "diamond"
? getDiamondBaseCorners(element).map((curve) => {
const point = bezierEquation(curve, 0.5);
const rotatedPoint = pointRotateRads(point, center, element.angle);
center: GlobalPoint,
horizontalThreshold: number,
verticalThreshold: number,
): { point: GlobalPoint; onAxis: boolean } | undefined => {
const { x, y, width, height, angle } = element;
const nonRotated = pointRotateRads(point, center, -angle as Radians);
return pointFrom<GlobalPoint>(rotatedPoint[0], rotatedPoint[1]);
})
: [
// RIGHT midpoint
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + element.width,
element.y + element.height / 2,
),
const bindingGap = getBindingGap(element);
if (pointDistance(center, nonRotated) < bindingGap) {
return undefined;
}
const [right, bottom, left, top] = getAllMidpoints(element, elementsMap);
if (
nonRotated[0] <= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
return { point: left, onAxis: true };
} else if (
nonRotated[1] <= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
return { point: top, onAxis: true };
} else if (
nonRotated[0] >= x + width / 2 &&
nonRotated[1] > center[1] - verticalThreshold &&
nonRotated[1] < center[1] + verticalThreshold
) {
return { point: right, onAxis: true };
} else if (
nonRotated[1] >= y + height / 2 &&
nonRotated[0] > center[0] - horizontalThreshold &&
nonRotated[0] < center[0] + horizontalThreshold
) {
return { point: bottom, onAxis: true };
} else if (element.type === "diamond") {
// Elbow arrows can also snap to the midpoints of a diamond's edges
const threshold = Math.max(horizontalThreshold, verticalThreshold);
const edgeMidpoints = [
// top-left, top-right, bottom-left, bottom-right
[x + width / 4, y + height / 4, -1, -1],
[x + (3 * width) / 4, y + height / 4, 1, -1],
[x + width / 4, y + (3 * height) / 4, -1, 1],
[x + (3 * width) / 4, y + (3 * height) / 4, 1, 1],
] as const;
for (const [edgeX, edgeY, dirX, dirY] of edgeMidpoints) {
// the snap zone sits a binding gap outside the edge
const zoneCenter = pointFrom<GlobalPoint>(
edgeX + dirX * bindingGap,
edgeY + dirY * bindingGap,
);
if (pointDistance(zoneCenter, nonRotated) < threshold) {
return {
point: pointRotateRads(
pointFrom<GlobalPoint>(edgeX, edgeY),
center,
element.angle,
angle,
),
// BOTTOM midpoint
pointRotateRads(
pointFrom<GlobalPoint>(
element.x + element.width / 2,
element.y + element.height,
),
center,
element.angle,
),
// LEFT midpoint
pointRotateRads(
pointFrom<GlobalPoint>(element.x, element.y + element.height / 2),
center,
element.angle,
),
// TOP midpoint
pointRotateRads(
pointFrom<GlobalPoint>(element.x + element.width / 2, element.y),
center,
element.angle,
),
];
const candidate = sideMidpoints.find(
(midpoint) =>
pointDistance(point, midpoint) <=
maxBindingDistance_simple(zoom) + element.strokeWidth / 2 &&
onAxis: false,
};
}
}
}
return undefined;
};
const getSnappedMidpointIndexForSimpleArrow = (
element: ExcalidrawBindableElement,
point: GlobalPoint,
elementsMap: ElementsMap,
threshold: number,
) => {
const baseMidpoints = getAllMidpoints(element, elementsMap);
for (let i = 0; i < baseMidpoints.length; i++) {
if (
pointDistance(baseMidpoints[i], point) <= threshold &&
!hitElementItself({
point,
element,
threshold: 0,
elementsMap,
overrideShouldTestInside: true,
}),
})
) {
return i;
}
}
return -1;
};
export const getAllMidpoints = (
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
): GlobalPoint[] => {
const center = elementCenterPoint(element, elementsMap);
if (element.type === "diamond") {
return getDiamondBaseCorners(element).map((curve) =>
pointRotateRads(bezierEquation(curve, 0.5), center, element.angle),
);
}
return [
pointFrom(element.width, element.height / 2),
pointFrom(element.width / 2, element.height),
pointFrom(0, element.height / 2),
pointFrom(element.width / 2, 0),
].map(([x, y]) =>
pointRotateRads(
pointFrom<GlobalPoint>(element.x + x, element.y + y),
center,
element.angle,
),
);
};
export const getElbowArrowSnapMidPoint = (
point: GlobalPoint,
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
) => {
const TOLERANCE = 0.05;
const maxDistance = maxBindingDistance_simple(zoom) + element.strokeWidth / 2;
return getSnappedMidpointForElbowArrow(
element,
point,
elementsMap,
elementCenterPoint(element, elementsMap),
clamp(TOLERANCE * element.width, 5, maxDistance),
clamp(TOLERANCE * element.height, 5, maxDistance),
);
};
export const getSnapOutlineMidPoint = (
point: GlobalPoint,
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
zoom: AppState["zoom"],
arrow: { elbowed: boolean },
): GlobalPoint | undefined => {
if (arrow.elbowed) {
return getElbowArrowSnapMidPoint(point, element, elementsMap, zoom)?.point;
}
const maxDistance = maxBindingDistance_simple(zoom) + element.strokeWidth / 2;
const idx = getSnappedMidpointIndexForSimpleArrow(
element,
point,
elementsMap,
maxDistance,
);
return candidate;
return idx === -1 ? undefined : getAllMidpoints(element, elementsMap)[idx];
};
export const projectFixedPointOntoDiagonal = (
@@ -670,22 +817,24 @@ export const projectFixedPointOntoDiagonal = (
isMidpointSnappingEnabled: boolean = true,
): GlobalPoint | null => {
invariant(arrow.points.length >= 2, "Arrow must have at least two points");
if (arrow.width < 3 && arrow.height < 3) {
return null;
}
if (isMidpointSnappingEnabled) {
const sideMidPoint = getSnapOutlineMidPoint(
point,
element,
elementsMap,
zoom,
arrow,
);
if (sideMidPoint) {
return sideMidPoint;
}
}
// Projection needs a meaningful arrow direction
if (arrow.width < 3 && arrow.height < 3) {
return null;
}
// Do the projection onto the diagonals (or center lines
// for non-rectangular shapes)
const [diagonalOne, diagonalTwo] = getDiagonalsForBindableElement(
+1 -13
View File
@@ -10,9 +10,6 @@ import { getElementsInGroup } from "./groups";
import { syncMovedIndices } from "./fractionalIndex";
import { getSelectedElements } from "./selection";
import { getBoundTextElement, getContainerElement } from "./textElement";
import { getHoveredElementForBinding } from "./collision";
import { getNonDeletedElements } from ".";
import type { Scene } from "./Scene";
import type {
@@ -159,17 +156,8 @@ export const moveArrowAboveBindable = (
elements: readonly OrderedExcalidrawElement[],
elementsMap: NonDeletedSceneElementsMap,
scene: Scene,
hit?: NonDeletedExcalidrawElement,
hoveredElement: NonDeletedExcalidrawElement,
): readonly OrderedExcalidrawElement[] => {
const hoveredElement = hit
? hit
: getHoveredElementForBinding(
point,
// SAFETY: callers that omit `hit` pass non-deleted elements
getNonDeletedElements(elements),
elementsMap,
);
if (!hoveredElement) {
return elements;
}
@@ -17,7 +17,7 @@ exports[`Test Linear Elements > Test bound text element > should match styles fo
class="excalidraw-wysiwyg"
data-type="wysiwyg"
dir="auto"
style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; max-height: 992.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"
style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 26.25px; left: 35px; top: 7.5px; transform-origin: 5px 12.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; font: Emoji 20px 20px; line-height: 1.25; font-family: Excalifont, Xiaolai, sans-serif, Segoe UI Emoji;"
tabindex="0"
wrap="off"
/>
+292 -3
View File
@@ -1,4 +1,4 @@
import { KEYS, arrayToMap } from "@excalidraw/common";
import { KEYS, ROUNDNESS, arrayToMap, DEFAULT_ZOOM } from "@excalidraw/common";
import { pointFrom } from "@excalidraw/math";
@@ -16,7 +16,14 @@ import {
import { defaultLang, setLanguage } from "@excalidraw/excalidraw/i18n";
import { bindBindingElement, updateBoundElements } from "../src/binding";
import type { Radians } from "@excalidraw/math";
import {
bindBindingElement,
getBindingGap,
updateBoundElements,
} from "../src/binding";
import { getAllMidpoints } from "../src/utils";
import { getTransformHandles } from "../src/transformHandles";
import {
getTextEditor,
@@ -237,6 +244,285 @@ describe("binding for simple arrows", () => {
expect(h.state.multiElement).not.toBe(null);
expect(h.state.activeTool.type).toBe("arrow");
});
it("inside -> inside stays in multi-point mode when the pointer moves on", () => {
const end: [number, number] = [INSIDE[0] + 50, INSIDE[1] + 50];
drawSelfArrow(INSIDE, end);
// nudge within the commit zone of the point just placed
mouse.moveTo(end[0] + 2, end[1] + 1);
expect(h.state.multiElement).not.toBe(null);
expect(h.state.activeTool.type).toBe("arrow");
expect(h.state.multiElement!.points.length).toBe(3);
});
it("bend point inside a shape the arrow doesn't start on stays in multi-point mode when the pointer moves on", () => {
UI.clickTool("arrow");
mouse.reset();
mouse.clickAt(...MIDDLE);
mouse.moveTo(...INSIDE);
mouse.clickAt(...INSIDE);
mouse.moveTo(INSIDE[0] + 2, INSIDE[1] + 1);
expect(h.state.multiElement).not.toBe(null);
expect(h.state.activeTool.type).toBe("arrow");
expect(h.state.multiElement!.points.length).toBe(2);
});
});
describe("binding to frames", () => {
// frame spans x:200..600, y:200..600, child rect x:300..400, y:300..400
beforeEach(async () => {
mouse.reset();
await act(() => setLanguage(defaultLang));
await render(<Excalidraw handleKeyboardGlobally={true} />);
const frame = API.createElement({
id: "frame",
type: "frame",
x: 200,
y: 200,
width: 400,
height: 400,
});
const child = API.createElement({
id: "child",
type: "rectangle",
x: 300,
y: 300,
width: 100,
height: 100,
frameId: frame.id,
});
API.setElements([frame, child]);
});
const drawArrow = (end: [number, number]) => {
UI.clickTool("arrow");
mouse.reset();
mouse.downAt(50, 50);
mouse.moveTo(end[0] - 10, end[1] - 10);
mouse.moveTo(...end);
mouse.up();
return h.elements[h.elements.length - 1] as ExcalidrawArrowElement;
};
it("doesn't bind an arrow ending in the frame's empty interior", () => {
const arrow = drawArrow([500, 500]);
expect(arrow.endBinding).toBe(null);
});
it("binds an arrow ending on a frame child to the child", () => {
const arrow = drawArrow([350, 350]);
expect(arrow.endBinding?.elementId).toBe("child");
});
it("binds an arrow ending just outside the frame to the frame", () => {
const arrow = drawArrow([500, 610]);
expect(arrow.endBinding?.elementId).toBe("frame");
expect(arrow.endBinding?.mode).toBe("orbit");
});
it("keeps an elbow arrow drawn inside the frame where it was drawn", () => {
UI.clickTool("arrow");
UI.clickOnTestId("elbow-arrow");
mouse.reset();
mouse.downAt(250, 250);
mouse.moveTo(400, 450);
mouse.moveTo(550, 550);
mouse.up();
const arrow = h.elements[h.elements.length - 1] as ExcalidrawArrowElement;
expect(arrow.elbowed).toBe(true);
// no self-orbit binding to the frame, which would route the arrow
// around the frame's outside
expect(arrow.startBinding).toBe(null);
expect(arrow.endBinding).toBe(null);
expect(arrow.frameId).toBe("frame");
expect([arrow.x, arrow.y]).toEqual([250, 250]);
expect(arrow.points[arrow.points.length - 1]).toEqual([300, 300]);
});
});
describe("binding at an ellipse's center", () => {
beforeEach(async () => {
mouse.reset();
await act(() => setLanguage(defaultLang));
await render(<Excalidraw handleKeyboardGlobally={true} />);
});
it("binds an arrow dropped at a circle's exact center", () => {
const circle = API.createElement({
type: "ellipse",
x: 100,
y: -100,
width: 200,
height: 200,
});
API.setElements([circle]);
UI.clickTool("arrow");
mouse.reset();
mouse.downAt(-100, 0);
mouse.moveTo(100, 0);
mouse.moveTo(200, 0);
mouse.up();
const arrow = h.elements[h.elements.length - 1] as ExcalidrawArrowElement;
expect(arrow.endBinding?.elementId).toBe(circle.id);
});
});
describe("midpoint snapping on diamonds", () => {
beforeEach(async () => {
mouse.reset();
await act(() => setLanguage(defaultLang));
await render(<Excalidraw handleKeyboardGlobally={true} />);
});
for (const rounded of [false, true]) {
for (const elbowed of [false, true]) {
it(`${
elbowed ? "elbow" : "simple"
} arrow ends a binding gap outside the ${
rounded ? "rounded" : "sharp"
} left vertex`, () => {
const diamond = API.createElement({
type: "diamond",
x: 100,
y: -100,
width: 200,
height: 200,
roundness: rounded ? { type: ROUNDNESS.PROPORTIONAL_RADIUS } : null,
}) as ExcalidrawBindableElement;
API.setElements([diamond]);
const [, , left] = getAllMidpoints(diamond, arrayToMap([diamond]));
UI.clickTool("arrow");
if (elbowed) {
UI.clickOnTestId("elbow-arrow");
}
mouse.reset();
mouse.downAt(-200, left[1]);
mouse.moveTo(left[0] - 50, left[1]);
// near (not on) the vertex, so the end snaps to it
mouse.moveTo(left[0] - 4, left[1] + 2);
mouse.up();
const arrow = h.elements[
h.elements.length - 1
] as ExcalidrawArrowElement;
const [endX, endY] = arrow.points[arrow.points.length - 1];
expect(arrow.endBinding?.elementId).toBe(diamond.id);
expect(arrow.x + endX).toBeCloseTo(
left[0] - getBindingGap(diamond),
0,
);
expect(arrow.y + endY).toBeCloseTo(left[1], 0);
});
}
it(`elbow arrow binds above the ${
rounded ? "rounded" : "sharp"
} top vertex when the pointer is slightly inside`, () => {
const diamond = API.createElement({
type: "diamond",
x: 100,
y: -100,
width: 300,
height: 300,
roundness: rounded ? { type: ROUNDNESS.PROPORTIONAL_RADIUS } : null,
}) as ExcalidrawBindableElement;
API.setElements([diamond]);
const [, , , top] = getAllMidpoints(diamond, arrayToMap([diamond]));
UI.clickTool("arrow");
UI.clickOnTestId("elbow-arrow");
mouse.reset();
mouse.downAt(top[0] - 300, top[1] - 100);
mouse.moveTo(top[0] - 50, top[1] - 50);
// inside the diamond, a bit right of the vertex
mouse.moveTo(top[0] + 3, top[1] + 10);
mouse.up();
const arrow = h.elements[
h.elements.length - 1
] as ExcalidrawArrowElement;
const points = arrow.points;
const [endX, endY] = points[points.length - 1];
expect(arrow.endBinding?.elementId).toBe(diamond.id);
expect(arrow.x + endX).toBeCloseTo(top[0], 0);
expect(arrow.y + endY).toBeCloseTo(top[1] - getBindingGap(diamond), 0);
// the last segment comes straight down into the vertex
expect(points[points.length - 2][0]).toBeCloseTo(endX);
});
}
it("elbow arrow binds next to the tip of a thin rotated diamond", () => {
const diamond = API.createElement({
type: "diamond",
x: 0,
y: 0,
width: 600,
height: 100,
angle: ((15 * Math.PI) / 180) as Radians,
roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },
}) as ExcalidrawBindableElement;
API.setElements([diamond]);
const [right] = getAllMidpoints(diamond, arrayToMap([diamond]));
UI.clickTool("arrow");
UI.clickOnTestId("elbow-arrow");
mouse.reset();
mouse.downAt(right[0] + 300, right[1] + 300);
mouse.moveTo(right[0] + 50, right[1] + 50);
// just outside the right tip
mouse.moveTo(right[0] + 4, right[1] + 1);
mouse.up();
const arrow = h.elements[h.elements.length - 1] as ExcalidrawArrowElement;
const [endX, endY] = arrow.points[arrow.points.length - 1];
expect(arrow.endBinding?.elementId).toBe(diamond.id);
// a binding gap away, not on another edge of the diamond
expect(
Math.hypot(arrow.x + endX - right[0], arrow.y + endY - right[1]),
).toBeLessThan(getBindingGap(diamond) + 2);
});
it("elbow arrow snaps to a diamond's edge midpoint", () => {
const diamond = API.createElement({
type: "diamond",
x: 100,
y: -100,
width: 200,
height: 200,
}) as ExcalidrawBindableElement;
API.setElements([diamond]);
// midpoint of the top-left edge
const edgeMidpoint = [150, -50] as const;
UI.clickTool("arrow");
UI.clickOnTestId("elbow-arrow");
mouse.reset();
mouse.downAt(-200, -50);
mouse.moveTo(100, -60);
// near (not on) the edge midpoint
mouse.moveTo(edgeMidpoint[0] - 9, edgeMidpoint[1] - 3);
mouse.up();
const arrow = h.elements[h.elements.length - 1] as ExcalidrawArrowElement;
const [, endY] = arrow.points[arrow.points.length - 1];
expect(arrow.endBinding?.elementId).toBe(diamond.id);
expect(arrow.y + endY).toBeCloseTo(edgeMidpoint[1], 0);
});
});
describe("when arrow is outside of shape", () => {
@@ -480,6 +766,9 @@ describe("binding for simple arrows", () => {
const elX = handles[0] + handles[2] / 2;
const elY = handles[1] + handles[3] / 2;
// move first, as a real pointer would — the hover state from the spot
// where arrow creation finished must clear before the pointerdown
mouse.moveTo(elX, elY);
mouse.downAt(elX, elY);
mouse.moveTo(300, 400);
mouse.up();
@@ -794,7 +1083,7 @@ describe("binding to a point-like (sub-pixel) element", () => {
}) as NonDeleted<ExcalidrawArrowElement>;
API.setElements([rect, arrow]);
bindBindingElement(arrow, rect, "orbit", "end", h.scene);
bindBindingElement(arrow, rect, "orbit", "end", h.scene, DEFAULT_ZOOM);
const endBinding = arrow.endBinding as FixedPointBinding;
expect(endBinding.elementId).toBe(rect.id);
+728 -3
View File
@@ -1,13 +1,43 @@
import { arrayToMap, reseed } from "@excalidraw/common";
import { type GlobalPoint, type LocalPoint, pointFrom } from "@excalidraw/math";
import {
ROUNDNESS,
arrayToMap,
getSizeFromPoints,
reseed,
} from "@excalidraw/common";
import {
type GlobalPoint,
type LocalPoint,
lineSegment,
pointFrom,
pointRotateRads,
} from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { UI } from "@excalidraw/excalidraw/tests/helpers/ui";
import "@excalidraw/utils/test-utils";
import { render } from "@excalidraw/excalidraw/tests/test-utils";
import type { Zoom } from "@excalidraw/excalidraw/types";
import * as distance from "../src/distance";
import { hitElementItself } from "../src/collision";
import { getElementBounds } from "../src/bounds";
import {
getAllHoveredElementAtPoint,
getHoveredElementForBinding,
hitElementItself,
intersectElementWithLineSegment,
isPointInElement,
} from "../src/collision";
import { mutateElement } from "../src/mutateElement";
import { newFreeDrawElement } from "../src/newElement";
import { getAllMidpoints } from "../src/utils";
import type {
ExcalidrawDiamondElement,
NonDeletedExcalidrawElement,
NonDeletedSceneElementsMap,
Ordered,
} from "../src/types";
describe("check rotated elements can be hit:", () => {
beforeEach(async () => {
@@ -217,4 +247,699 @@ describe("hitElementItself cache", () => {
}),
).toBe(true);
});
it("rechecks a bound label when only its arrow changes", () => {
const arrow = API.createElement({
type: "arrow",
x: 200,
y: 200,
width: 300,
height: 0,
points: [pointFrom(0, 0), pointFrom(300, 0)],
});
const label = API.createElement({
type: "text",
text: "label",
x: 325,
y: 187.5,
width: 50,
height: 25,
containerId: arrow.id,
});
API.setElements([arrow, label]);
API.updateElement(arrow, {
boundElements: [{ id: label.id, type: "text" }],
});
const elementsMap = window.h.scene.getNonDeletedElementsMap();
const labelVersion = label.version;
const point = pointFrom<GlobalPoint>(350, 200);
expect(
hitElementItself({ point, element: label, threshold: 1, elementsMap }),
).toBe(true);
API.updateElement(arrow, { x: 500 });
expect(label.version).toBe(labelVersion);
expect(
hitElementItself({ point, element: label, threshold: 1, elementsMap }),
).toBe(false);
expect(
hitElementItself({
point: pointFrom<GlobalPoint>(650, 200),
element: label,
threshold: 1,
elementsMap,
}),
).toBe(true);
});
});
describe("freedraw collision matches the rendered stroke width", () => {
// A straight, horizontal stroke centered on y === 0.
const points = Array.from({ length: 21 }, (_, i) =>
pointFrom<LocalPoint>(i * 5, 0),
);
const createFreeDraw = (variability: "variable" | "constant") =>
API.createElement({
type: "freedraw",
x: 0,
y: 0,
strokeWidth: 10,
points,
strokeOptions: { variability, streamline: 0.5 },
});
const distanceAt = (
element: ReturnType<typeof createFreeDraw>,
x: number,
y: number,
) =>
distance.distanceToElement(
element,
arrayToMap([element]),
pointFrom<GlobalPoint>(x, y),
);
it("treats a point on the centerline as a direct hit for both modes", () => {
expect(distanceAt(createFreeDraw("variable"), 50, 0)).toBe(0);
expect(distanceAt(createFreeDraw("constant"), 50, 0)).toBe(0);
});
it("hits across the body of a thick stroke, not just near the centerline", () => {
expect(distanceAt(createFreeDraw("variable"), 50, 20)).toBe(0);
});
it("uses a wider hit area for variable-width than for constant-width strokes", () => {
const offset = 20;
const variableDistance = distanceAt(createFreeDraw("variable"), 50, offset);
const constantDistance = distanceAt(createFreeDraw("constant"), 50, offset);
expect(variableDistance).toBe(0);
expect(constantDistance).toBeGreaterThan(0);
expect(variableDistance).toBeLessThan(constantDistance);
});
it("does not hit points clearly outside even the widest stroke", () => {
expect(distanceAt(createFreeDraw("variable"), 50, 45)).toBeGreaterThan(0);
});
it("hits thick ink outside the centerline bounds", () => {
const hitAt = (
element: ReturnType<typeof createFreeDraw>,
x: number,
y: number,
) =>
hitElementItself({
element,
elementsMap: arrayToMap([element]),
point: pointFrom<GlobalPoint>(x, y),
threshold: 1,
});
// The centerline bounds have zero height, far below the ink's reach.
expect(hitAt(createFreeDraw("variable"), 50, 20)).toBe(true);
expect(hitAt(createFreeDraw("variable"), 50, -20)).toBe(true);
expect(hitAt(createFreeDraw("constant"), 50, 10)).toBe(true);
expect(hitAt(createFreeDraw("constant"), 50, 20)).toBe(false);
expect(hitAt(createFreeDraw("variable"), 50, 45)).toBe(false);
});
it("hits the start cap of a short stroke reaching past its stroke size", () => {
// Under 3px long, perfect-freehand draws the start cap around the first
// point from the last point's outline, reaching past the stroke size.
const element = newFreeDrawElement({
type: "freedraw",
x: 0,
y: 0,
strokeWidth: 1,
simulatePressure: false,
pressures: [1, 1, 1],
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(0.01, 0),
pointFrom<LocalPoint>(2.9, 0),
],
strokeOptions: { variability: "variable", streamline: 0.5 },
});
const elementsMap = arrayToMap([element]);
const point = pointFrom<GlobalPoint>(0.1, 4.9);
expect(distance.distanceToElement(element, elementsMap, point)).toBe(0);
// The hit threshold at 30x zoom.
expect(
hitElementItself({ element, elementsMap, point, threshold: 0.6 }),
).toBe(true);
});
});
const createLoop = ({
angle = 0,
backgroundColor = "#ffc9c9",
variability = "variable",
points = Array.from({ length: 81 }, (_, i) =>
pointFrom<LocalPoint>(
80 + 80 * Math.cos((i / 80) * 2 * Math.PI),
40 + 40 * Math.sin((i / 80) * 2 * Math.PI),
),
),
}: {
angle?: number;
backgroundColor?: string;
variability?: "variable" | "constant";
points?: LocalPoint[];
} = {}) =>
API.createElement({
type: "freedraw",
x: 300,
y: 200,
...getSizeFromPoints(points),
angle,
strokeWidth: 2,
backgroundColor,
fillStyle: "solid",
points,
strokeOptions: { variability, streamline: 0.5 },
});
// The fill contour does not depend on the stroke; only its interplay with the
// stroke geometry is tested per stroke variability.
describe.each(["variable", "constant"] as const)(
"%s freedraw loop containment",
(variability) => {
it.each([0, Math.PI / 4])(
"hits the fill independently of the stroke at angle %s",
(angle) => {
const element = createLoop({ angle, variability });
const elementsMap = arrayToMap([element]);
const point = pointRotateRads(
pointFrom<GlobalPoint>(400, 250),
pointFrom<GlobalPoint>(380, 240),
element.angle,
);
// Checking the fill must not replace the cached stroke geometry.
expect(
distance.distanceToElement(element, elementsMap, point),
).toBeGreaterThan(10);
expect(isPointInElement(point, element, elementsMap)).toBe(true);
expect(
hitElementItself({ element, elementsMap, point, threshold: 1 }),
).toBe(true);
expect(
distance.distanceToElement(element, elementsMap, point),
).toBeGreaterThan(10);
},
);
it.each([0, Math.PI / 4])(
"does not hit the interior of a transparent loop at angle %s",
(angle) => {
const element = createLoop({
angle,
backgroundColor: "transparent",
variability,
});
const elementsMap = arrayToMap([element]);
const point = pointRotateRads(
pointFrom<GlobalPoint>(400, 250),
pointFrom<GlobalPoint>(380, 240),
element.angle,
);
// Warm the fill cache first; it must not replace the stroke geometry.
isPointInElement(point, element, elementsMap);
expect(
hitElementItself({ element, elementsMap, point, threshold: 1 }),
).toBe(false);
},
);
it("does not treat the empty corners of the loop bounds as fill", () => {
const element = createLoop({ variability });
const elementsMap = arrayToMap([element]);
const point = pointFrom<GlobalPoint>(310, 210);
expect(isPointInElement(point, element, elementsMap)).toBe(false);
expect(
hitElementItself({ element, elementsMap, point, threshold: 1 }),
).toBe(false);
});
},
);
describe("freedraw loop fill containment", () => {
it.each([0, Math.PI / 4])(
"hits the center and axes of a loop with curve junctions at angle %s",
(angle) => {
const element = createLoop({ angle });
const elementsMap = arrayToMap([element]);
const center = pointFrom<GlobalPoint>(380, 240);
for (const point of [
center,
pointFrom<GlobalPoint>(400, 240),
pointFrom<GlobalPoint>(380, 250),
]) {
expect(
isPointInElement(
pointRotateRads(point, center, element.angle),
element,
elementsMap,
),
).toBe(true);
}
},
);
it.each([0, Math.PI / 4])(
"implicitly closes the fill of an unsnapped loop at angle %s",
(angle) => {
const element = createLoop({ angle });
const elementsMap = arrayToMap([element]);
mutateElement(element, elementsMap, {
points: [
...element.points.slice(0, -1),
pointFrom<LocalPoint>(160, 36),
],
});
const point = pointRotateRads(
pointFrom<GlobalPoint>(440, 239.5),
pointFrom<GlobalPoint>(380, 240),
element.angle,
);
expect(isPointInElement(point, element, elementsMap)).toBe(true);
},
);
it("rotates around the unrotated bounds center of an asymmetric loop", () => {
const element = createLoop({
angle: Math.PI / 4,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(200, 0),
pointFrom<LocalPoint>(0, 100),
pointFrom<LocalPoint>(0, 0),
],
});
const point = pointRotateRads(
pointFrom<GlobalPoint>(330, 205),
pointFrom<GlobalPoint>(400, 250),
element.angle,
);
expect(isPointInElement(point, element, arrayToMap([element]))).toBe(true);
});
it("hits smoothed fill outside the rotated bounds of the points", () => {
const element = createLoop({
angle: (2 * Math.PI) / 3,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(200, 0),
pointFrom<LocalPoint>(0, 100),
pointFrom<LocalPoint>(0, 0),
],
});
const elementsMap = arrayToMap([element]);
// Outside the raw triangle, inside the curve bulging past its hypotenuse.
const point = pointRotateRads(
pointFrom<GlobalPoint>(436, 240),
pointFrom<GlobalPoint>(400, 250),
element.angle,
);
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
expect(
point[0] < x1 || point[0] > x2 || point[1] < y1 || point[1] > y2,
).toBe(true);
expect(isPointInElement(point, element, elementsMap)).toBe(true);
expect(
hitElementItself({ element, elementsMap, point, threshold: 1 }),
).toBe(true);
});
it.each([
{
name: "a three-point retraced path",
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 100),
pointFrom<LocalPoint>(0, 0),
],
point: pointFrom<GlobalPoint>(350, 250),
},
{
name: "a loop that simplifies to two identical points",
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(0.3, 0),
pointFrom<LocalPoint>(0.3, 0.3),
pointFrom<LocalPoint>(0, 0.3),
pointFrom<LocalPoint>(0, 0),
],
point: pointFrom<GlobalPoint>(300.15, 200.15),
},
])("contains nothing for $name", ({ points, point }) => {
const element = createLoop({ points });
expect(isPointInElement(point, element, arrayToMap([element]))).toBe(false);
});
it("preserves the curved fill of a nearly closed three-point path", () => {
const element = createLoop({
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 100),
pointFrom<LocalPoint>(3, 0),
],
});
expect(
isPointInElement(
pointFrom<GlobalPoint>(350, 250),
element,
arrayToMap([element]),
),
).toBe(true);
});
it("includes the smoothed fill beyond the raw-point polygon", () => {
const element = createLoop({
points: [
pointFrom<LocalPoint>(200, 100),
pointFrom<LocalPoint>(100, 200),
pointFrom<LocalPoint>(0, 100),
pointFrom<LocalPoint>(100, 0),
pointFrom<LocalPoint>(200, 100),
],
});
expect(
isPointInElement(
pointFrom<GlobalPoint>(305, 285),
element,
arrayToMap([element]),
),
).toBe(true);
});
it("uses even-odd fill for a self-intersecting loop", () => {
const element = createLoop({
points: Array.from({ length: 6 }, (_, i) => {
const angle = -Math.PI / 2 + (((i * 2) % 5) / 5) * 2 * Math.PI;
return pointFrom<LocalPoint>(
100 + 95 * Math.cos(angle),
100 + 95 * Math.sin(angle),
);
}),
});
expect(
isPointInElement(
pointFrom<GlobalPoint>(400, 300),
element,
arrayToMap([element]),
),
).toBe(false);
});
it("invalidates the fill contour when points change on the same element", () => {
const element = createLoop();
const elementsMap = arrayToMap([element]);
const point = pointFrom<GlobalPoint>(415, 255);
const version = element.version;
expect(isPointInElement(point, element, elementsMap)).toBe(true);
// Preserve the bounds so a stale contour cannot hide behind that pre-check.
mutateElement(element, elementsMap, {
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(160, 0),
pointFrom<LocalPoint>(0, 80),
pointFrom<LocalPoint>(0, 0),
],
});
expect(element.version).toBeGreaterThan(version);
expect(isPointInElement(point, element, elementsMap)).toBe(false);
});
});
describe("binding hit tests", () => {
type SceneElement = Ordered<NonDeletedExcalidrawElement>;
const zoom = (value: number) => ({ value } as Zoom);
const hitTest = (
elements: SceneElement[],
point: GlobalPoint,
zoomValue = 1,
) => {
const elementsMap = arrayToMap(elements) as NonDeletedSceneElementsMap;
return {
hovered: getHoveredElementForBinding(
point,
elements,
elementsMap,
zoom(zoomValue),
)?.id,
all: getAllHoveredElementAtPoint(
point,
elements,
elementsMap,
zoom(zoomValue),
).map((element) => element.id),
};
};
it("both use the zoom-aware binding distance", () => {
const rect = API.createElement({
id: "rect",
type: "rectangle",
x: 0,
y: 0,
width: 100,
height: 100,
}) as SceneElement;
// 20px outside the right edge
const point = pointFrom<GlobalPoint>(120, 50);
// 15px binding distance at zoom 1
expect(hitTest([rect], point, 1)).toEqual({ hovered: undefined, all: [] });
// 25px binding distance at zoom 0.4
expect(hitTest([rect], point, 0.4)).toEqual({
hovered: "rect",
all: ["rect"],
});
});
it("both skip elements hidden behind an opaque element", () => {
const hidden = API.createElement({
id: "hidden",
type: "rectangle",
x: 30,
y: 30,
width: 40,
height: 40,
index: "a0" as SceneElement["index"],
}) as SceneElement;
const cover = (backgroundColor: string) =>
API.createElement({
id: "cover",
type: "rectangle",
x: 0,
y: 0,
width: 100,
height: 100,
backgroundColor,
index: "a1" as SceneElement["index"],
}) as SceneElement;
const point = pointFrom<GlobalPoint>(50, 50);
expect(hitTest([hidden, cover("#ffc9c9")], point)).toEqual({
hovered: "cover",
all: ["cover"],
});
const transparent = hitTest([hidden, cover("transparent")], point);
expect(transparent.hovered).toBe("hidden");
expect(transparent.all).toEqual(["cover", "hidden"]);
});
it("an image, and a locked opaque element, hide what's behind them", () => {
const hidden = API.createElement({
id: "hidden",
type: "rectangle",
x: 30,
y: 30,
width: 40,
height: 40,
index: "a0" as SceneElement["index"],
}) as SceneElement;
const point = pointFrom<GlobalPoint>(50, 50);
const image = API.createElement({
id: "image",
type: "image",
x: 0,
y: 0,
width: 100,
height: 100,
index: "a1" as SceneElement["index"],
}) as SceneElement;
expect(hitTest([hidden, image], point)).toEqual({
hovered: "image",
all: ["image"],
});
const locked = (backgroundColor: string) =>
API.createElement({
id: "locked",
type: "rectangle",
x: 0,
y: 0,
width: 100,
height: 100,
backgroundColor,
locked: true,
index: "a1" as SceneElement["index"],
}) as SceneElement;
// can't bind to the locked element, nor through it
expect(hitTest([hidden, locked("#ffc9c9")], point)).toEqual({
hovered: undefined,
all: [],
});
// a transparent locked element hides nothing
expect(hitTest([hidden, locked("transparent")], point)).toEqual({
hovered: "hidden",
all: ["hidden"],
});
});
describe("overlapping elements", () => {
const rect = (id: string, x: number, y: number, w: number, h: number) =>
API.createElement({
id,
type: "rectangle",
x,
y,
width: w,
height: h,
}) as SceneElement;
it("binds to the container's edge next to a nested element", () => {
const container = rect("container", 0, 0, 200, 200);
// 18px inside the container's left edge
const child = rect("child", 18, 80, 60, 40);
// 5px inside the container's edge, 13px outside the child
expect(
hitTest([container, child], pointFrom<GlobalPoint>(5, 100)).hovered,
).toBe("container");
// closer to the child's outline than to the container's
expect(
hitTest([container, child], pointFrom<GlobalPoint>(10, 100)).hovered,
).toBe("child");
});
it("binds to a smaller element straddling the container's edge when inside both", () => {
const container = rect("container", 0, 0, 200, 200);
const badge = rect("badge", -30, 80, 60, 40);
// 3px inside the container's edge, inside the badge
expect(
hitTest([container, badge], pointFrom<GlobalPoint>(3, 92)).hovered,
).toBe("badge");
// 5px outside the container's edge, inside the badge: the closer
// container outline wins
expect(
hitTest([container, badge], pointFrom<GlobalPoint>(-5, 108)).hovered,
).toBe("container");
});
});
it("binds at a circle's exact center, where an opaque circle still occludes", () => {
const hidden = API.createElement({
id: "hidden",
type: "rectangle",
x: 90,
y: 90,
width: 20,
height: 20,
index: "a0" as SceneElement["index"],
}) as SceneElement;
const circle = (backgroundColor: string) =>
API.createElement({
id: "circle",
type: "ellipse",
x: 0,
y: 0,
width: 200,
height: 200,
backgroundColor,
index: "a1" as SceneElement["index"],
}) as SceneElement;
const center = pointFrom<GlobalPoint>(100, 100);
expect(hitTest([circle("transparent")], center).hovered).toBe("circle");
expect(hitTest([hidden, circle("#ffc9c9")], center)).toEqual({
hovered: "circle",
all: ["circle"],
});
});
});
describe("ellipse outline hit test", () => {
it("doesn't hit a transparent ellipse's outline from its center line", () => {
const ellipse = API.createElement({
type: "ellipse",
x: 0,
y: 0,
width: 400,
height: 100,
backgroundColor: "transparent",
});
// on the horizontal center line, ~50px from the outline
expect(
hitElementItself({
point: pointFrom<GlobalPoint>(210, 50),
element: ellipse,
threshold: 10,
elementsMap: arrayToMap([ellipse]),
}),
).toBe(false);
});
});
describe("intersectElementWithLineSegment", () => {
it("hits a rounded diamond corner along a line through its apex", () => {
const diamond = API.createElement({
type: "diamond",
x: 100,
y: -100,
width: 200,
height: 200,
roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },
}) as ExcalidrawDiamondElement;
const elementsMap = arrayToMap([diamond]);
const [, , left] = getAllMidpoints(diamond, elementsMap);
// the offset corner is split into several curves, and this line passes
// exactly through the joint of two of them
const hits = intersectElementWithLineSegment(
diamond,
elementsMap,
lineSegment(
pointFrom<GlobalPoint>(200, left[1]),
pointFrom<GlobalPoint>(-200, left[1]),
),
6,
);
expect(hits.length).toBeGreaterThan(0);
expect(hits[0][0]).toBeCloseTo(left[0] - 6, 0);
expect(hits[0][1]).toBeCloseTo(left[1]);
});
});
+225 -20
View File
@@ -3,11 +3,7 @@ import { vi } from "vitest";
import { KEYS, cloneJSON } from "@excalidraw/common";
import {
Excalidraw,
exportToCanvas,
exportToSvg,
} from "@excalidraw/excalidraw";
import { Excalidraw, exportScene } from "@excalidraw/excalidraw";
import {
actionFlipHorizontal,
actionFlipVertical,
@@ -117,6 +113,38 @@ describe("Enter and leave the crop editor", () => {
Keyboard.keyDown(KEYS.ESCAPE);
expect(h.state.croppingElementId).toBe(null);
});
it("leave the editor by clicking where the rotation handle would be", () => {
const image = h.elements[0];
Keyboard.keyDown(KEYS.ENTER);
// (the editor draws no rotation handle)
mouse.clickAt(image.x + image.width / 2, image.y - 16);
expect(h.state.croppingElementId).toBe(null);
});
it("stay in the editor on shift-clicking the image", () => {
const image = h.elements[0];
Keyboard.keyDown(KEYS.ENTER);
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.clickAt(image.x + 50, image.y + 50);
});
expect(h.state.croppingElementId).toBe(image.id);
expect(h.state.selectedElementIds).toEqual({ [image.id]: true });
});
it("stay in the editor on clicking a crop handle", () => {
const image = h.elements[0];
Keyboard.keyDown(KEYS.ENTER);
// the east handle
mouse.clickAt(image.x + image.width, image.y + image.height / 2);
expect(h.state.croppingElementId).toBe(image.id);
});
});
describe("Crop an image", () => {
@@ -136,6 +164,174 @@ describe("Crop an image", () => {
expect(image.height).toBeLessThan(initialHeight);
});
it("In the crop editor, dragging a handle crops the image, and dragging the image moves it within its crop (along one axis with shift)", () => {
const image = API.createElement({
type: "image",
width: 200,
height: 100,
fileId: "file",
});
API.setElements([image]);
// the file loaded, at twice the element's size
const htmlImage = new Image();
Object.defineProperties(htmlImage, {
naturalWidth: { value: 400 },
naturalHeight: { value: 200 },
});
h.app.imageCache.set(image.fileId!, {
image: htmlImage,
mimeType: "image/png",
});
API.setSelectedElements([image]);
Keyboard.keyDown(KEYS.ENTER);
expect(h.state.croppingElementId).toBe(image.id);
UI.resize(image, "nw", [50, 25]);
expect(API.getElement(image)).toMatchObject({ x: 50, y: 25, width: 150 });
expect(API.getElement(image).crop).toMatchObject({ x: 100, y: 50 });
// 20px to the right = 40px of the file, at twice the element's size
mouse.downAt(100, 50);
mouse.move(20, 0);
mouse.upAt();
expect(API.getElement(image)).toMatchObject({ x: 50, y: 25, width: 150 });
expect(API.getElement(image).crop).toMatchObject({ x: 60, y: 50 });
Keyboard.withModifierKeys({ shift: true }, () => {
mouse.downAt(100, 50);
mouse.move(10, 4);
mouse.upAt();
});
expect(API.getElement(image).crop).toMatchObject({ x: 40, y: 50 });
// dragged past the file's edge, it moves back as soon as dragged back
mouse.downAt(100, 50);
mouse.move(40, 0);
expect(API.getElement(image).crop).toMatchObject({ x: 0 });
mouse.move(-10, 0);
mouse.upAt();
expect(API.getElement(image).crop).toMatchObject({ x: 20, y: 50 });
});
it("In the crop editor, alt-dragging a handle crops the image from its center", () => {
const image = API.createElement({
type: "image",
width: 200,
height: 100,
fileId: "file",
});
API.setElements([image]);
// the file loaded, at twice the element's size
const htmlImage = new Image();
Object.defineProperties(htmlImage, {
naturalWidth: { value: 400 },
naturalHeight: { value: 200 },
});
h.app.imageCache.set(image.fileId!, {
image: htmlImage,
mimeType: "image/png",
});
API.setSelectedElements([image]);
Keyboard.keyDown(KEYS.ENTER);
// as resizing, pressing alt mid-drag crops about the center the drag
// started with, and releasing it, from the opposite side again
mouse.downAt(200, 50);
mouse.moveTo(170, 50);
expect(API.getElement(image)).toMatchObject({ x: 0, width: 170 });
Keyboard.withModifierKeys({ alt: true }, () => {
Keyboard.keyDown(KEYS.ALT);
});
expect(API.getElement(image)).toMatchObject({ x: 30, width: 140 });
Keyboard.keyUp(KEYS.ALT);
expect(API.getElement(image)).toMatchObject({ x: 0, width: 170 });
mouse.moveTo(200, 50);
mouse.upAt();
UI.resize(image, "e", [-30, 0], { alt: true });
expect(API.getElement(image)).toMatchObject({ x: 30, width: 140 });
// 30px off each side = 60px of the file, at twice the element's size
expect(API.getElement(image).crop).toMatchObject({ x: 60, width: 280 });
// keeping the aspect ratio too
UI.resize(image, "e", [-35, 0], { alt: true, shift: true });
expect(API.getElement(image)).toMatchObject({
x: 65,
y: 25,
width: 70,
height: 50,
});
});
it("In the crop editor, double-clicking a handle uncrops its side(s), mirrored with alt", () => {
// the middle of an image twice the element's size, at (0, 0)
const image = API.createElement({
type: "image",
x: 50,
y: 25,
width: 100,
height: 50,
fileId: "file",
});
API.setElements([image]);
API.updateElement(image, {
crop: {
x: 100,
y: 50,
width: 200,
height: 100,
naturalWidth: 400,
naturalHeight: 200,
},
});
// bound near the image's south-east corner
const arrow = UI.createElement("arrow", {
x: 140,
y: 300,
width: 0,
height: -230,
});
API.setSelectedElements([image]);
Keyboard.keyDown(KEYS.ENTER);
// the north-east handle
mouse.doubleClickAt(150, 25);
expect(API.getElement(image)).toMatchObject({
x: 50,
y: 0,
width: 150,
height: 75,
});
expect(API.getElement(image).crop).toMatchObject({ y: 0, width: 300 });
// the arrow following the image
const { x, points } = API.getElement(arrow);
expect(x + points[1][0]).toBeCloseTo(185);
Keyboard.undo();
expect(API.getElement(image)).toMatchObject({ y: 25, width: 100 });
// the west handle, and so the east one
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.doubleClickAt(50, 50);
});
expect(API.getElement(image)).toMatchObject({
x: 0,
y: 25,
width: 200,
height: 50,
});
expect(API.getElement(image).crop).toMatchObject({ x: 0, width: 400 });
});
it("Cropping has minimal sizes", async () => {
const image = h.elements[0] as ExcalidrawImageElement;
const initialWidth = image.width;
@@ -272,13 +468,12 @@ describe("Cropping and other features", async () => {
initialWidth / 2,
initialHeight / 2,
]);
const cropBeforeResizing = image.crop;
const cropBeforeResizingCloned = cloneJSON(image.crop) as ImageCrop;
expect(cropBeforeResizing).not.toBe(null);
expect(image.crop).not.toBe(null);
UI.crop(image, "e", naturalWidth, naturalHeight, [200, 0]);
expect(cropBeforeResizing).toBe(image.crop);
compareCrops(cropBeforeResizingCloned, image.crop!);
const cropBeforeResizing = image.crop;
UI.resize(image, "s", [0, -100]);
expect(cropBeforeResizing).toBe(image.crop);
@@ -333,23 +528,33 @@ describe("Cropping and other features", async () => {
Keyboard.keyDown(KEYS.ESCAPE);
const widthToHeightRatio = image.width / image.height;
const canvas = await exportToCanvas({
elements: [image],
// @ts-ignore
appState: h.state,
files: h.app.files,
exportPadding: 0,
const canvas = await exportScene({
type: "canvas",
data: {
elements: [image],
// @ts-ignore
appState: h.state,
files: h.app.files,
},
config: {
padding: 0,
},
});
const exportedCanvasRatio = canvas.width / canvas.height;
expect(widthToHeightRatio).toBeCloseTo(exportedCanvasRatio);
const svg = await exportToSvg({
elements: [image],
// @ts-ignore
appState: h.state,
files: h.app.files,
exportPadding: 0,
const svg = await exportScene({
type: "svg",
data: {
elements: [image],
// @ts-ignore
appState: h.state,
files: h.app.files,
},
config: {
padding: 0,
},
});
const svgWidth = svg.getAttribute("width");
const svgHeight = svg.getAttribute("height");
+281 -1
View File
@@ -1,12 +1,292 @@
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { arrayToMap } from "@excalidraw/common";
import { pointFrom } from "@excalidraw/math";
import type { ObservedAppState } from "@excalidraw/excalidraw/types";
import type { LinearElementEditor } from "@excalidraw/element";
import type { SceneElementsMap } from "@excalidraw/element/types";
import type {
ExcalidrawTextElement,
FractionalIndex,
SceneElementsMap,
} from "@excalidraw/element/types";
import { AppStateDelta, Delta, ElementsDelta } from "../src/delta";
import { mutateElement, newElementWith } from "../src/mutateElement";
describe("ElementsDelta", () => {
describe("visible changes", () => {
const apply = (before: SceneElementsMap, after: SceneElementsMap) =>
ElementsDelta.calculate(before, after).applyTo(before, before, {
excludedProperties: new Set(["version", "versionNonce"]),
});
const boundText = (
type: "rectangle" | "stickynote" | "arrow",
text = "",
) => {
const container = API.createElement({
type,
id: "container",
index: "a0" as FractionalIndex,
width: 250,
height: type === "arrow" ? 0 : 250,
baseHeight: type === "stickynote" ? 250 : undefined,
points:
type === "arrow" ? [pointFrom(0, 0), pointFrom(250, 0)] : undefined,
boundElements: [{ id: "label", type: "text" }],
});
const label: ExcalidrawTextElement = {
...API.createElement({
type: "text",
id: "label",
index: "a1" as FractionalIndex,
containerId: container.id,
fontSize: 20,
textAlign: "center",
verticalAlign: "middle",
}),
// API.createElement substitutes "test" for an empty string.
text,
originalText: text,
};
const before = arrayToMap([container, label]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(container, { boundElements: [] }),
newElementWith(label, { isDeleted: true }),
]) as SceneElementsMap;
return { container, label, before, after };
};
it.each(["rectangle", "stickynote"] as const)(
"ignores empty-label deletion and restoration on a %s",
(type) => {
const { before, after, container, label } = boundText(type);
const [deleted, deletionIsVisible] = apply(before, after);
expect(deletionIsVisible).toBe(false);
expect(deleted.get(label.id)?.isDeleted).toBe(true);
expect(deleted.get(container.id)?.boundElements).toEqual([]);
const [restored, restorationIsVisible] = apply(after, before);
expect(restorationIsVisible).toBe(false);
expect(restored.get(label.id)?.isDeleted).toBe(false);
expect(restored.get(container.id)?.boundElements).toEqual([
{ id: label.id, type: "text" },
]);
},
);
it("keeps deletion and restoration of nonempty labels visible", () => {
const { before, after } = boundText("stickynote", "hello");
expect(apply(before, after)[1]).toBe(true);
expect(apply(after, before)[1]).toBe(true);
});
it.each(["excluded", "already applied"])(
"ignores %s properties when deciding visibility",
(mode) => {
const element = API.createElement({
type: "rectangle",
index: "a0" as FractionalIndex,
});
const before = arrayToMap([element]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(element, { strokeColor: "red" }),
]) as SceneElementsMap;
const delta = ElementsDelta.calculate(before, after);
const current = mode === "excluded" ? before : after;
const [elements, isVisible] = delta.applyTo(current, current, {
excludedProperties: new Set([
"version",
"versionNonce",
...(mode === "excluded" ? ["strokeColor" as const] : []),
]),
});
expect(elements.get(element.id)?.strokeColor).toBe(
current.get(element.id)?.strokeColor,
);
expect(isVisible).toBe(false);
},
);
it("keeps snapshot restoration visible for a metadata-only update", () => {
const element = API.createElement({
type: "rectangle",
index: "a0" as FractionalIndex,
});
const before = arrayToMap([element]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(element, { version: element.version + 1 }),
]) as SceneElementsMap;
const delta = ElementsDelta.calculate(before, after);
const [elements, isVisible] = delta.applyTo(
new Map() as SceneElementsMap,
before,
);
expect(elements.get(element.id)?.isDeleted).toBe(false);
expect(isVisible).toBe(true);
});
it("keeps an arrow's empty-label gap visible", () => {
const { before, after } = boundText("arrow");
expect(apply(before, after)[1]).toBe(true);
expect(apply(after, before)[1]).toBe(true);
});
it("detects a container resized by restoring an empty label", () => {
const { container, label } = boundText("rectangle");
const smallContainer = newElementWith(container, {
width: 20,
height: 10,
boundElements: [],
});
const before = arrayToMap([
smallContainer,
newElementWith(label, { isDeleted: true }),
]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(smallContainer, {
boundElements: [{ id: label.id, type: "text" }],
}),
newElementWith(label, { isDeleted: false }),
]) as SceneElementsMap;
const [elements, isVisible] = apply(before, after);
expect(elements.get(container.id)?.height).toBeGreaterThan(10);
expect(isVisible).toBe(true);
});
it("detects a bound label repositioned by a container's redraw", () => {
const { container, label } = boundText("rectangle", "hello");
const misplacedLabel = newElementWith(label, { x: -100, y: -100 });
const before = arrayToMap([
container,
misplacedLabel,
]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(container, { version: container.version + 1 }),
misplacedLabel,
]) as SceneElementsMap;
const [elements, isVisible] = apply(before, after);
expect(elements.get(container.id)?.height).toBe(container.height);
expect(elements.get(label.id)?.x).not.toBe(-100);
expect(isVisible).toBe(true);
});
it("detects a bound arrow repositioned by a container's redraw", () => {
const container = API.createElement({
type: "rectangle",
id: "container",
index: "a0" as FractionalIndex,
boundElements: [{ id: "arrow", type: "arrow" }],
});
const arrow = API.createElement({
type: "arrow",
id: "arrow",
index: "a1" as FractionalIndex,
x: 200,
y: 50,
points: [pointFrom(0, 0), pointFrom(100, 0)],
startBinding: {
elementId: container.id,
mode: "orbit",
fixedPoint: [1, 0.5],
},
});
const before = arrayToMap([container, arrow]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(container, { version: container.version + 1 }),
arrow,
]) as SceneElementsMap;
const [elements, isVisible] = apply(before, after);
expect(elements.get(container.id)?.width).toBe(container.width);
expect(elements.get(arrow.id)?.x).not.toBe(200);
expect(isVisible).toBe(true);
});
it.each(["test", "development", "production"])(
"guards against untracked layout mutations in %s mode",
(mode) => {
const element = API.createElement({
type: "rectangle",
id: "changed",
index: "a0" as FractionalIndex,
});
const unrelated = API.createElement({
type: "rectangle",
id: "unrelated",
index: "a1" as FractionalIndex,
});
const before = arrayToMap([element, unrelated]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(element, { strokeColor: "red" }),
unrelated,
]) as SceneElementsMap;
// Simulate a future layout dependency missing from idsToCheck.
// Mutate the shared instance so the guard must snapshot version values.
const redraw = vi
.spyOn(ElementsDelta, "redrawElements")
.mockImplementationOnce((elements) => {
mutateElement(elements.get(unrelated.id)!, elements, {
x: unrelated.x + 1,
});
return elements;
});
const consoleError = vi
.spyOn(console, "error")
.mockImplementation(() => {});
vi.stubEnv("MODE", mode);
try {
if (mode === "production") {
expect(apply(before, after)[1]).toBe(true);
expect(consoleError).not.toHaveBeenCalled();
} else {
expect(() => apply(before, after)).toThrow(
'Redrawn element "unrelated" is missing from idsToCheck',
);
}
} finally {
redraw.mockRestore();
consoleError.mockRestore();
vi.unstubAllEnvs();
}
},
);
it("keeps an empty text element's arrow bindings visible", () => {
const label: ExcalidrawTextElement = {
...API.createElement({
type: "text",
id: "label",
index: "a0" as FractionalIndex,
boundElements: [{ id: "arrow", type: "arrow" }],
}),
text: "",
originalText: "",
};
const arrow = API.createElement({
type: "arrow",
id: "arrow",
index: "a1" as FractionalIndex,
startBinding: {
elementId: label.id,
mode: "orbit",
fixedPoint: [1, 0.5],
},
});
const before = arrayToMap([label, arrow]) as SceneElementsMap;
const after = arrayToMap([
newElementWith(label, { isDeleted: true, boundElements: [] }),
newElementWith(arrow, { startBinding: null }),
]) as SceneElementsMap;
expect(apply(before, after)[1]).toBe(true);
});
});
describe("elements delta calculation", () => {
it("should not throw when element gets removed but was already deleted", () => {
const element = API.createElement({
+228
View File
@@ -0,0 +1,228 @@
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { pointFrom } from "@excalidraw/math";
import type { PointerDownState } from "@excalidraw/excalidraw/types";
import type { LocalPoint } from "@excalidraw/math";
import { Scene } from "../src/Scene";
import { updateBoundElements } from "../src/binding";
import { dragSelectedElements } from "../src/dragElements";
import { syncInvalidIndices } from "../src/fractionalIndex";
import { LinearElementEditor } from "../src/linearElementEditor";
import type { NonDeletedExcalidrawElement } from "../src/types";
vi.mock("../src/binding", async (importOriginal) => {
const actual = await importOriginal<typeof import("../src/binding")>();
return {
...actual,
updateBoundElements: vi.fn(actual.updateBoundElements),
};
});
const pointerDownStateFor = (scene: Scene): PointerDownState => {
const state: Pick<PointerDownState, "originalElements"> = {
originalElements: new Map(
scene
.getNonDeletedElements()
.map((element) => [element.id, { ...element }]),
),
};
return state as PointerDownState;
};
const drag = (
scene: Scene,
selectedElements: NonDeletedExcalidrawElement[],
offset = { x: 20, y: 30 },
pointerDownState = pointerDownStateFor(scene),
) => {
dragSelectedElements(
pointerDownState,
selectedElements,
offset,
scene,
{ x: 0, y: 0 },
null,
);
};
const createBoundArrow = () => {
const rectangle = API.createElement({
id: "rectangle",
boundElements: [{ id: "arrow", type: "arrow" }],
});
const arrow = API.createElement({
type: "arrow",
id: "arrow",
x: 25,
y: 25,
width: 200,
height: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(200, 0)],
startBinding: {
elementId: rectangle.id,
fixedPoint: [0.25, 0.25],
mode: "inside",
},
});
const scene = new Scene(syncInvalidIndices([rectangle, arrow]));
return { scene, rectangle, arrow };
};
describe("dragSelectedElements", () => {
afterEach(() => {
vi.mocked(updateBoundElements).mockClear();
});
it("passes every bound-arrow update the same moved-element array", () => {
const selected = [0, 1, 2].map((i) =>
API.createElement({ x: i * 200, y: 0 }),
);
const scene = new Scene(syncInvalidIndices(selected));
drag(scene, selected);
const calls = vi.mocked(updateBoundElements).mock.calls;
expect(calls).toHaveLength(3);
// a fresh array per call misses the per-array id-set cache and rebuilds
// a selection-sized set for every element
const [[, , firstOptions]] = calls;
expect(firstOptions?.simultaneouslyUpdated).toEqual(selected);
for (const [, , options] of calls) {
expect(options?.simultaneouslyUpdated).toBe(
firstOptions?.simultaneouslyUpdated,
);
}
});
it("moves grouped elements and their bound label across z-order", () => {
const rectangle = API.createElement({
id: "rectangle",
groupIds: ["group"],
boundElements: [{ id: "label", type: "text" }],
});
const label = API.createElement({
type: "text",
id: "label",
containerId: rectangle.id,
x: 10,
y: 15,
width: 80,
height: 20,
groupIds: ["group"],
});
const unrelated = API.createElement({ x: 500, y: 600 });
const second = API.createElement({
x: 200,
y: 300,
groupIds: ["group"],
});
const scene = new Scene(
syncInvalidIndices([rectangle, label, unrelated, second]),
);
const order = scene.getNonDeletedElements().map((element) => element.id);
drag(scene, [rectangle, second]);
expect(scene.getNonDeletedElements().map(({ x, y }) => ({ x, y }))).toEqual(
[
{ x: 20, y: 30 },
{ x: 30, y: 45 },
{ x: 500, y: 600 },
{ x: 220, y: 330 },
],
);
expect(scene.getNonDeletedElements().map((element) => element.id)).toEqual(
order,
);
});
it("moves a frame and its children once even when a child is also selected", () => {
const frame = API.createElement({ type: "frame", width: 400, height: 400 });
const selectedChild = API.createElement({ x: 10, frameId: frame.id });
const otherChild = API.createElement({ x: 200, frameId: frame.id });
const elements = [selectedChild, otherChild, frame];
const scene = new Scene(syncInvalidIndices(elements));
const versions = elements.map((element) => element.version);
drag(scene, [frame, selectedChild]);
expect(elements.map(({ x, y }) => ({ x, y }))).toEqual([
{ x: 30, y: 40 },
{ x: 220, y: 230 },
{ x: 20, y: 30 },
]);
expect(elements.map((element) => element.version)).toEqual(
versions.map((version) => version + 1),
);
});
it("updates an unselected bound arrow", () => {
const { scene, rectangle, arrow } = createBoundArrow();
drag(scene, [rectangle]);
expect(rectangle).toMatchObject({ x: 20, y: 30 });
expect(
LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
0,
scene.getNonDeletedElementsMap(),
),
).toEqual([45, 55]);
expect(
LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
-1,
scene.getNonDeletedElementsMap(),
),
).toEqual([225, 25]);
expect(arrow.startBinding?.elementId).toBe(rectangle.id);
});
it("preserves bindings when translating an arrow with its attached element", () => {
const { scene, rectangle, arrow } = createBoundArrow();
const arrowVersion = arrow.version;
const originalPoints = arrow.points;
drag(scene, [rectangle, arrow]);
expect(arrow).toMatchObject({
x: 45,
y: 55,
startBinding: { elementId: rectangle.id },
version: arrowVersion + 1,
});
expect(arrow.points).toBe(originalPoints);
expect(rectangle.boundElements).toEqual([{ id: arrow.id, type: "arrow" }]);
});
it("unbinds a translated arrow from an unselected element", () => {
const { scene, rectangle, arrow } = createBoundArrow();
drag(scene, [arrow]);
expect(arrow).toMatchObject({ x: 45, y: 55, startBinding: null });
expect(rectangle).toMatchObject({ x: 0, y: 0, boundElements: [] });
});
it("does not mutate for unchanged coordinates", () => {
const rectangle = API.createElement({});
const second = API.createElement({ x: 200 });
const scene = new Scene(syncInvalidIndices([rectangle, second]));
const originalState = pointerDownStateFor(scene);
const versions = () => [rectangle.version, second.version];
const initial = versions();
drag(scene, [rectangle, second], { x: 0, y: 0 }, originalState);
expect(versions()).toEqual(initial);
drag(scene, [rectangle, second], { x: 20, y: 30 }, originalState);
const moved = versions();
expect(moved).toEqual(initial.map((version) => version + 1));
drag(scene, [rectangle, second], { x: 20, y: 30 }, originalState);
expect(versions()).toEqual(moved);
});
});
+459 -4
View File
@@ -2,9 +2,11 @@ import { pointFrom } from "@excalidraw/math";
import {
FONT_FAMILY,
KEYS,
ORIG_ID,
ROUNDNESS,
isPrimitive,
getUpdatedTimestamp,
} from "@excalidraw/common";
import { Excalidraw, mutateElement } from "@excalidraw/excalidraw";
@@ -15,18 +17,33 @@ import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { UI, Keyboard, Pointer } from "@excalidraw/excalidraw/tests/helpers/ui";
import { getTextEditor } from "@excalidraw/excalidraw/tests/queries/dom";
import {
GlobalTestState,
act,
assertElements,
fireEvent,
getCloneByOrigId,
render,
waitFor,
} from "@excalidraw/excalidraw/tests/test-utils";
import type { LocalPoint } from "@excalidraw/math";
import { duplicateElement, duplicateElements } from "../src/duplicate";
import {
deepCopyElement,
duplicateElement,
duplicateElements,
} from "../src/duplicate";
import type { ExcalidrawLinearElement } from "../src/types";
import { isBoundToContainer, isTextElement } from "../src/typeChecks";
import type {
ExcalidrawLinearElement,
ExcalidrawTextElement,
NonDeletedExcalidrawElement,
} from "../src/types";
const { h } = window;
const mouse = new Pointer("mouse");
@@ -43,6 +60,24 @@ const assertCloneObjects = (source: any, clone: any) => {
};
describe("duplicating single elements", () => {
it.each([123, 0, null])(
"preserves created=%s on a deep copy and resets it for a new instance",
(created) => {
const element = API.createElement({ type: "rectangle", created });
const cloned = deepCopyElement(element);
const duplicate = duplicateElement(null, new Map(), element);
expect(cloned).toEqual(element);
expect(duplicate).toMatchObject({
created: getUpdatedTimestamp(),
version: element.version,
versionNonce: element.versionNonce,
});
expect(duplicate.id).not.toBe(element.id);
expect(element.created).toBe(created);
},
);
it("clones arrow element", () => {
const element = API.createElement({
type: "arrow",
@@ -599,7 +634,7 @@ describe("duplication z-order", () => {
mouse.select(rectangle1);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle1.x + 5, rectangle1.y + 5);
mouse.up(rectangle1.x + 5, rectangle1.y + 5);
mouse.up(rectangle1.x + 10, rectangle1.y + 10);
});
assertElements(h.elements, [
@@ -665,7 +700,7 @@ describe("duplication z-order", () => {
mouse.select(rectangle1);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(rectangle1.x + 5, rectangle1.y + 5);
mouse.up(rectangle1.x + 5, rectangle1.y + 5);
mouse.up(rectangle1.x + 10, rectangle1.y + 10);
});
assertElements(h.elements, [
@@ -840,3 +875,423 @@ describe("duplication z-order", () => {
]);
});
});
describe("duplicating list items", () => {
beforeEach(async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
});
const duplicate = (texts: string[]) => {
const elements = texts.map((text, index) =>
API.createElement({ type: "text", text, y: index * 100 }),
);
API.setElements(elements);
API.setSelectedElements(elements);
act(() => {
h.app.actionManager.executeAction(actionDuplicateSelection);
});
// (each duplicate goes right after its original)
const duplicates = h.elements.filter(
(element) => h.state.selectedElementIds[element.id],
) as ExcalidrawTextElement[];
return duplicates.map((element) => {
expect(element).toMatchObject({ text: element.originalText });
return element.originalText;
});
};
it.each([
["1. foo", "2. foo"],
["1) foo", "2) foo"],
["(9) foo", "(10) foo"],
["[1] foo", "[2] foo"],
["09. foo", "10. foo"],
["0.", "1."],
[" b. foo", " c. foo"],
["A) foo", "B) foo"],
["(a) foo", "(b) foo"],
["(A) foo", "(B) foo"],
// below `i` alphabetically, from `i` up as roman numerals
["h. foo", "i. foo"],
["i. foo", "ii. foo"],
["viii) foo", "ix) foo"],
["(iv) foo", "(v) foo"],
["XXXIX. foo", "XL. foo"],
["l. foo", "li. foo"],
["1. step\n a. sub-step", "2. step\n a. sub-step"],
// lone numbers
["7", "8"],
[" 05 ", " 06 "],
// numbers up to 42
["41", "42"],
["42", "42"],
["2024", "2024"],
["(41) foo", "(42) foo"],
["42. foo", "42. foo"],
// not list items
["1.5 kg", "1.5 kg"],
["e.g. foo", "e.g. foo"],
["[a] foo", "[a] foo"],
["j. foo", "j. foo"],
["Ii. foo", "Ii. foo"],
["iiii. foo", "iiii. foo"],
["xcix. foo", "xcix. foo"],
["1. foo\n2. bar", "1. foo\n2. bar"],
])("advances the marker of %j", (text, expected) => {
expect(duplicate([text])).toEqual([expected]);
});
it("continues the list from the highest of the duplicated items", () => {
expect(duplicate(["5.", "1.", "3.", "a.", "1", "1"])).toEqual([
"8.",
"6.",
"7.",
"b.",
"2",
"3",
]);
});
it.each<[string, () => NonDeletedExcalidrawElement[], string[]]>([
[
"labeled containers",
() => [
...API.createTextContainer({ label: { text: "1." } }),
...API.createTextContainer({ label: { text: "2." } }),
],
["3.", "4."],
],
// several list items only if they're just markers
[
"list items with text",
() => [
API.createElement({ type: "text", text: "1. aa" }),
API.createElement({ type: "text", text: "2. bb" }),
API.createElement({ type: "text", text: "3. cc" }),
],
["1. aa", "2. bb", "3. cc"],
],
// along with anything else, list items are copied as they are
[
"a labeled container and another element",
() => [
...API.createTextContainer({ label: { text: "1. foo" } }),
API.createElement({ type: "rectangle" }),
],
["1. foo"],
],
[
"a list item and another text",
() => [
API.createElement({ type: "text", text: "1. foo" }),
API.createElement({ type: "text", text: "foo" }),
],
["1. foo", "foo"],
],
[
"a list item and another element",
() => [
API.createElement({ type: "text", text: "1. foo" }),
API.createElement({ type: "rectangle" }),
],
["1. foo"],
],
])("duplicating %s", (_, createElements, expected) => {
const elements = createElements();
API.setElements(elements);
API.setSelectedElements(
elements.filter((element) => !isBoundToContainer(element)),
);
act(() => {
h.app.actionManager.executeAction(actionDuplicateSelection);
});
expect(
elements
.filter(isTextElement)
.map(
(text) =>
(getCloneByOrigId(text.id) as ExcalidrawTextElement).originalText,
),
).toEqual(expected);
});
it("stops letters at `i` (the switch to roman numerals)", () => {
expect(duplicate(["g.", "h."])).toEqual(["i.", "h."]);
});
it.each([
["rectangle", "9. foo", "10. foo"],
["stickynote", "9. foo", "10. foo"],
["ellipse", "3", "4"],
] as const)(
"advances the marker of a %s label %j",
(type, text, expected) => {
const container = API.createElement({ type });
const label = API.createElement({
type: "text",
text,
containerId: container.id,
});
API.setElements([container, label]);
h.app.scene.mutateElement(container, {
boundElements: [{ type: "text", id: label.id }],
});
API.setSelectedElements([container]);
act(() => {
h.app.actionManager.executeAction(actionDuplicateSelection);
});
assertElements(h.elements, [
{ id: container.id },
{ id: label.id, originalText: text },
{ [ORIG_ID]: container.id, selected: true },
{
[ORIG_ID]: label.id,
containerId: getCloneByOrigId(container.id).id,
originalText: expected,
},
]);
},
);
it("undo reverts the marker before the duplication", () => {
const text = API.createElement({ type: "text", text: "1. foo" });
API.setElements([text]);
API.setSelectedElements([text]);
act(() => {
h.app.actionManager.executeAction(actionDuplicateSelection);
});
// (undo loses the ORIG_ID)
const { id } = getCloneByOrigId(text.id);
Keyboard.undo();
assertElements(h.elements, [
{ id: text.id, originalText: "1. foo" },
{ id, selected: true, originalText: "1. foo" },
]);
Keyboard.undo();
assertElements(h.elements, [{ id: text.id }, { id, isDeleted: true }]);
});
it("alt-drag advances the markers from the start of the drag, undoably", async () => {
const [container, label] = API.createTextContainer({
label: { text: "9. foo" },
});
API.setElements([container, label]);
API.setSelectedElements([container]);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(container.x + 5, container.y + 5);
mouse.move(50, 50);
});
expect(getCloneByOrigId(label.id)).toMatchObject({
originalText: "10. foo",
});
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.up();
});
// (undo loses the ORIG_ID)
const duplicate = getCloneByOrigId(container.id);
const duplicateLabel = getCloneByOrigId(label.id);
expect(duplicateLabel).toMatchObject({ originalText: "10. foo" });
// on to editing the item's text
const editor = await getTextEditor();
expect(h.state.editingTextElement?.id).toBe(duplicateLabel.id);
expect(editor.value).toBe("10. foo");
await waitFor(() =>
expect([editor.selectionStart, editor.selectionEnd]).toEqual([4, 7]),
);
Keyboard.exitTextEditor(editor);
Keyboard.undo();
assertElements(h.elements, [
{ id: container.id },
{ id: label.id, originalText: "9. foo" },
{ id: duplicate.id, selected: true, x: duplicate.x, y: duplicate.y },
{ id: duplicateLabel.id, originalText: "9. foo" },
]);
Keyboard.redo();
assertElements(h.elements, [
{ id: container.id },
{ id: label.id },
{ id: duplicate.id, selected: true },
{ id: duplicateLabel.id, originalText: "10. foo" },
]);
});
it("alt-drag doesn't edit a list item without text", () => {
const text = API.createElement({ type: "text", text: "1" });
API.setElements([text]);
API.setSelectedElements([text]);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(text.x + 5, text.y + 5);
mouse.up(50, 50);
});
expect(getCloneByOrigId(text.id)).toMatchObject({ originalText: "2" });
expect(h.state.editingTextElement).toBe(null);
});
it("alt-drag doesn't edit the list item when the drag gets interrupted", () => {
const text = API.createElement({ type: "text", text: "1. foo" });
API.setElements([text]);
API.setSelectedElements([text]);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.down(text.x + 5, text.y + 5);
mouse.move(50, 50);
});
fireEvent.pointerCancel(GlobalTestState.interactiveCanvas, {
pointerId: 1,
});
expect(getCloneByOrigId(text.id)).toMatchObject({ originalText: "2. foo" });
expect(h.state.editingTextElement).toBe(null);
});
it("leaves the texts of a duplicated frame as they are", () => {
const frame = API.createElement({ type: "frame", width: 500 });
const text = API.createElement({
type: "text",
text: "1. foo",
frameId: frame.id,
});
API.setElements([text, frame]);
API.setSelectedElements([frame]);
act(() => {
h.app.actionManager.executeAction(actionDuplicateSelection);
});
assertElements(h.elements, [
{ id: text.id },
{ id: frame.id },
{ [ORIG_ID]: text.id, originalText: "1. foo" },
{ [ORIG_ID]: frame.id, selected: true },
]);
});
});
describe("alt-dragging the text being edited", () => {
beforeEach(async () => {
await render(<Excalidraw handleKeyboardGlobally={true} />);
});
/** alt-presses the text editor, which hands the press over to the canvas */
const altPressTextEditor = async (x: number, y: number) => {
const editor = await getTextEditor();
// (the editor takes pointer downs from the next frame on)
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
mouse.restorePosition(x, y);
fireEvent.pointerDown(editor, {
clientX: x,
clientY: y,
pointerType: "mouse",
pointerId: 1,
button: 0,
altKey: true,
});
expect(h.state.editingTextElement).toBe(null);
};
it.each([
["foo", "foo", "foo"],
// a list item's text only, as when alt-dragged on the canvas
["1. foo", "2. foo", "foo"],
])(
"duplicates %j, editing the duplicate %j with %j selected",
async (text, duplicateText, selectedText) => {
const element = API.createElement({ type: "text", text });
API.setElements([element]);
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
await altPressTextEditor(element.x + 5, element.y + 5);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.moveTo(element.x + 5, element.y + 50);
mouse.up();
});
const duplicate = getCloneByOrigId(element.id);
expect(duplicate).toMatchObject({ originalText: duplicateText });
const duplicateEditor = await getTextEditor();
expect(h.state.editingTextElement?.id).toBe(duplicate.id);
await waitFor(() =>
expect(
duplicateEditor.value.slice(
duplicateEditor.selectionStart,
duplicateEditor.selectionEnd,
),
).toBe(selectedText),
);
},
);
// the editor reaches past the text's bounds, over its resize handles
it("duplicates the text when pressed past its bounds", async () => {
const element = API.createElement({
type: "text",
text: "foo\nbar\nbaz\nqux\nquux",
});
API.setElements([element]);
API.setSelectedElements([element]);
Keyboard.keyPress(KEYS.ENTER);
// (as laid out by the editor)
const { x, y, width, height, fontSize } = h
.elements[0] as ExcalidrawTextElement;
await altPressTextEditor(x + 5, y + height + 3);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.moveTo(x + 5, y + height + 100);
mouse.up();
});
assertElements(h.elements, [
{ id: element.id, x, y, width, height, fontSize },
{ id: getCloneByOrigId(element.id).id, width, height, fontSize },
]);
});
// the label is over the arrow's midpoint handle
it("duplicates a labeled arrow when pressed on its label", async () => {
const [arrow, label] = API.createLabeledArrow();
API.setElements([arrow, label]);
const { x, y, width, height, points } = arrow as ExcalidrawLinearElement;
mouse.clickAt(x + width / 4, y + height / 4);
// (its editor keeps what the last press grabbed)
mouse.clickAt(x + width / 2, y + height / 2);
expect(
h.state.selectedLinearElement?.initialState.segmentMidpoint.value,
).not.toBe(null);
Keyboard.keyPress(KEYS.ENTER);
expect(h.state.editingTextElement?.id).toBe(label.id);
await altPressTextEditor(x + width / 2, y + height / 2);
Keyboard.withModifierKeys({ alt: true }, () => {
mouse.moveTo(x + width / 2, y + height + 100);
mouse.up();
});
assertElements(h.elements, [
{ id: arrow.id, x, y, points },
{ id: label.id },
{ id: getCloneByOrigId(arrow.id).id, points },
{ id: getCloneByOrigId(label.id).id },
]);
});
});
+17 -3
View File
@@ -1,4 +1,4 @@
import { ARROW_TYPE } from "@excalidraw/common";
import { ARROW_TYPE, DEFAULT_ZOOM } from "@excalidraw/common";
import { pointFrom } from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw";
import { actionSelectAll } from "@excalidraw/excalidraw/actions";
@@ -188,8 +188,22 @@ describe("elbow arrow routing", () => {
}) as NonDeleted<ExcalidrawElbowArrowElement>;
API.setElements([rectangle1, rectangle2, arrow]);
bindBindingElement(arrow, rectangle1, "orbit", "start", h.scene);
bindBindingElement(arrow, rectangle2, "orbit", "end", h.scene);
bindBindingElement(
arrow,
rectangle1,
"orbit",
"start",
h.scene,
DEFAULT_ZOOM,
);
bindBindingElement(
arrow,
rectangle2,
"orbit",
"end",
h.scene,
DEFAULT_ZOOM,
);
expect(arrow.startBinding).not.toBe(null);
expect(arrow.endBinding).not.toBe(null);
+12
View File
@@ -95,6 +95,18 @@ describe("YouTube timestamp parsing", () => {
expect(result?.intrinsicSize).toEqual({ w: 315, h: 560 });
});
it("should handle YouTube live URLs", () => {
const url = "https://www.youtube.com/live/dQw4w9WgXcQ?si=abc&t=30";
const result = getEmbedLink(url);
expect(result?.type).toBe("video");
if (result?.type === "video" || result?.type === "generic") {
expect(result.link).toBe(
"https://www.youtube.com/embed/dQw4w9WgXcQ?enablejsapi=1&start=30",
);
}
});
it("should handle playlist URLs with timestamps", () => {
const url =
"https://www.youtube.com/playlist?list=PLrAXtmRdnEQy1KbG5lbfgQ0-PKQY6FKYZ&t=60";
+104 -1
View File
@@ -8,13 +8,14 @@ import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { Keyboard, Pointer, UI } from "@excalidraw/excalidraw/tests/helpers/ui";
import { getTextEditor } from "@excalidraw/excalidraw/tests/queries/dom";
import {
act,
getCloneByOrigId,
render,
} from "@excalidraw/excalidraw/tests/test-utils";
import { getSelectedElements } from "@excalidraw/excalidraw/scene";
import { elementOverlapsWithFrame } from "../src/frame";
import { elementOverlapsWithFrame, shouldApplyFrameClip } from "../src/frame";
import type {
ExcalidrawElement,
@@ -156,6 +157,108 @@ describe("adding elements to frames", () => {
).toBe(true);
});
it("should add a group a new frame matches edge to edge", () => {
// a hair outside, as snapping the frame to it leaves it
const rects = [
[100 - 1e-8, 100],
[200, 100 + 1e-8],
].map(([x, width]) =>
API.createElement({
type: "rectangle",
x,
y: 100,
width,
height: 100,
strokeWidth: 4,
groupIds: ["group"],
}),
);
API.setElements(rects);
act(() => h.app.setActiveTool({ type: "frame" }));
mouse.downAt(100, 100);
mouse.moveTo(300, 200);
mouse.up();
const newFrame = h.elements.find((el) => el.type === "frame");
expect(newFrame).toMatchObject({ x: 100, y: 100, width: 200 });
expect(
rects.map((rect) => h.elements.find((el) => el.id === rect.id)?.frameId),
).toEqual([newFrame!.id, newFrame!.id]);
});
it("should add a group a resized frame matches edge to edge", () => {
// a hair outside, as snapping the frame to it leaves it
const rects = [
[160, 40],
[200, 50 + 1e-8],
].map(([x, width]) =>
API.createElement({
type: "rectangle",
x,
y: 0,
width,
height: 100,
groupIds: ["group"],
}),
);
API.setElements([frame, ...rects]);
mouse.clickAt(0, 0);
mouse.downAt(frame.x + frame.width, frame.y + frame.height);
mouse.moveTo(250, 100);
mouse.up();
expect(
rects.map((rect) => h.elements.find((el) => el.id === rect.id)?.frameId),
).toEqual([frame.id, frame.id]);
});
it("should clip a frame's child to it, even if inside it (but for its stroke)", () => {
const child = API.createElement({
type: "rectangle",
x: 1e-7,
y: 1e-7,
width: 150 - 2e-7,
height: 100 - 2e-7,
frameId: frame.id,
});
API.setElements([child, frame]);
expect(
shouldApplyFrameClip(
child,
frame as ExcalidrawFrameLikeElement,
h.state,
arrayToMap(h.elements),
),
).toBe(true);
});
it("should not clip a child dragged out of its frame", () => {
const child = API.createElement({
type: "rectangle",
x: 300,
width: 50,
height: 50,
frameId: frame.id,
});
API.setElements([child, frame]);
expect(
shouldApplyFrameClip(
child,
frame as ExcalidrawFrameLikeElement,
{
...h.state,
selectedElementIds: { [child.id]: true },
selectedElementsAreBeingDragged: true,
},
arrayToMap(h.elements),
),
).toBe(false);
});
it("should not add a newly created element to a frame behind a non-frame element", () => {
const cover = API.createElement({
id: "cover",
@@ -3,6 +3,7 @@ import { act, queryByTestId, queryByText } from "@testing-library/react";
import { vi } from "vitest";
import {
CURSOR_TYPE,
ROUNDNESS,
VERTICAL_ALIGN,
KEYS,
@@ -31,6 +32,7 @@ import * as textElementUtils from "../src/textElement";
import { getBoundTextElementPosition, getBoundTextMaxWidth } from "../src";
import { LinearElementEditor } from "../src";
import { newArrowElement } from "../src";
import { getLinearElementPathSegments } from "../src/utils";
import {
getTextEditor,
@@ -213,13 +215,15 @@ describe("Test Linear Elements", () => {
createTwoPointerLinearElement("line");
const line = h.elements[0] as ExcalidrawLinearElement;
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`5`);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`6`);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`5`);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toEqual(2);
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(`8`);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`10`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
expect(line.points.length).toEqual(3);
expect(line.points).toMatchInlineSnapshot(`
@@ -422,6 +426,40 @@ describe("Test Linear Elements", () => {
await getTextEditor();
});
it("updates the hovered handles together (midpoint, then endpoint)", () => {
createTwoPointerLinearElement("arrow");
mouse.moveTo(midpoint[0], midpoint[1]);
expect(
h.state.selectedLinearElement?.segmentMidPointHoveredCoords,
).not.toBe(null);
mouse.moveTo(p2[0], p2[1]);
expect(h.state.selectedLinearElement).toMatchObject({
hoverPointIndex: 1,
segmentMidPointHoveredCoords: null,
});
});
it("doesn't highlight the arrow's midpoint while its label is edited", async () => {
createTwoPointerLinearElement("arrow");
mouse.moveTo(midpoint[0], midpoint[1]);
expect(
h.state.selectedLinearElement?.segmentMidPointHoveredCoords,
).not.toBe(null);
mouse.doubleClickAt(midpoint[0], midpoint[1]);
await getTextEditor();
expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(
null,
);
// (beside the editor)
mouse.moveTo(midpoint[0] + 8, midpoint[1]);
expect(h.state.selectedLinearElement?.segmentMidPointHoveredCoords).toBe(
null,
);
});
it.each([
["start", null],
["start", "triangle"],
@@ -502,7 +540,7 @@ describe("Test Linear Elements", () => {
// drag line from midpoint
drag(midpoint, pointFrom(midpoint[0] + delta, midpoint[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`12`,
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -543,7 +581,7 @@ describe("Test Linear Elements", () => {
fireEvent.click(screen.getByTitle("Round"));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`10`,
`11`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`6`);
@@ -604,7 +642,7 @@ describe("Test Linear Elements", () => {
drag(startPoint, endPoint);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`12`,
`13`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -672,7 +710,7 @@ describe("Test Linear Elements", () => {
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`15`,
`18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
@@ -723,7 +761,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] - delta, hitCoords[1] - delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`12`,
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -764,7 +802,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`12`,
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -812,7 +850,7 @@ describe("Test Linear Elements", () => {
deletePoint(points[2]);
expect(line.points.length).toEqual(3);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`18`,
`22`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`10`);
@@ -870,7 +908,7 @@ describe("Test Linear Elements", () => {
),
);
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`15`,
`18`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`9`);
expect(line.points.length).toEqual(5);
@@ -968,7 +1006,7 @@ describe("Test Linear Elements", () => {
drag(hitCoords, pointFrom(hitCoords[0] + delta, hitCoords[1] + delta));
expect(renderInteractiveScene.mock.calls.length).toMatchInlineSnapshot(
`12`,
`14`,
);
expect(renderStaticScene.mock.calls.length).toMatchInlineSnapshot(`7`);
@@ -1202,6 +1240,93 @@ describe("Test Linear Elements", () => {
});
});
describe("Test getPointAtPathParameter", () => {
it("should survive midpoint insertion", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(100, 0)],
roundness: null,
});
API.setElements([arrow]);
const before = LinearElementEditor.getPointAtPathParameter(
arrow,
0.25,
arrayToMap(h.elements),
)!;
expect(before[0]).toBeCloseTo(25);
expect(before[1]).toBeCloseTo(0);
// inserting a midpoint re-segments the path but must not move the
// point at the same normalized arc-length parameter
act(() => {
h.app.scene.mutateElement(arrow, {
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(50, 0),
pointFrom<LocalPoint>(100, 0),
],
});
});
const after = LinearElementEditor.getPointAtPathParameter(
arrow,
0.25,
arrayToMap(h.elements),
)!;
expect(after[0]).toBeCloseTo(before[0]);
expect(after[1]).toBeCloseTo(before[1]);
});
it("should use the unrounded logical path of elbow arrows", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 100,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 0),
pointFrom<LocalPoint>(100, 100),
],
elbowed: true,
});
API.setElements([arrow]);
const elementsMap = arrayToMap(h.elements);
// Until mixed paths are supported, elbow arrows are treated as the
// straight segments between their logical points.
const segments = getLinearElementPathSegments(arrow, elementsMap);
expect(segments).toHaveLength(2);
for (let i = 1; i < segments.length; i++) {
const prevEnd = segments[i - 1][segments[i - 1].length - 1];
expect(segments[i][0][0]).toBeCloseTo(prevEnd[0]);
expect(segments[i][0][1]).toBeCloseTo(prevEnd[1]);
}
const expectedPoints = [
pointFrom<GlobalPoint>(0, 0),
pointFrom<GlobalPoint>(50, 0),
pointFrom<GlobalPoint>(100, 0),
pointFrom<GlobalPoint>(100, 50),
pointFrom<GlobalPoint>(100, 100),
];
for (const [index, parameter] of [0, 0.25, 0.5, 0.75, 1].entries()) {
const point = LinearElementEditor.getPointAtPathParameter(
arrow,
parameter,
elementsMap,
);
expect(point).toEqual(expectedPoints[index]);
}
});
});
it("should match styles for text editor", async () => {
createTwoPointerLinearElement("arrow");
Keyboard.keyPress(KEYS.ENTER);
@@ -1325,7 +1450,7 @@ describe("Test Linear Elements", () => {
expect({ width: container.width, height: container.height })
.toMatchInlineSnapshot(`
{
"height": 130,
"height": 150,
"width": "366.11716",
}
`);
@@ -1354,11 +1479,11 @@ describe("Test Linear Elements", () => {
).toMatchInlineSnapshot(`
[
20,
35,
45,
"501.11716",
95,
220,
"205.45894",
"52.50000",
145,
]
`);
});
@@ -1469,6 +1594,7 @@ describe("Test Linear Elements", () => {
"nw",
false,
false,
false,
);
expect(
wrapText(
@@ -1543,6 +1669,8 @@ describe("Test Linear Elements", () => {
contextMenu = document.querySelector(".context-menu");
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
expect(container.boundElements).toEqual([]);
// the arrow is selected along with the freed label
expect(h.state.selectedLinearElement).toBe(null);
expect(text).toEqual(
expect.objectContaining({
containerId: null,
@@ -1577,6 +1705,272 @@ describe("Test Linear Elements", () => {
expect(label.x).toBe(0);
expect(label.y).toBe(0);
});
describe("dragging the label along the arrow", () => {
// a tall label, so its lower half is beyond the arrow's hit threshold:
// there the pointer is over the label but not over the arrow's path
const createArrowWithTallLabel = () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 60,
}),
labelPosition: 0.5,
} as ExcalidrawTextElementWithContainer;
return {
label,
arrow: {
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
};
};
// covers the label and the arrow's segment midpoint handle, but not the
// arrow's start point, so the arrow can still be selected by clicking it
const createOccluder = () =>
API.createElement({
type: "rectangle",
x: 30,
y: 5,
width: 30,
height: 50,
backgroundColor: "#ff0000",
fillStyle: "solid",
});
// inside the label, off the arrow's path
const labelOnlyPoint = pointFrom<GlobalPoint>(40, 45);
it("treats a point handle under the label as the handle, on hover and on pointer down", () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 30,
}),
// centered on the end point
labelPosition: 1,
} as ExcalidrawTextElementWithContainer;
API.setElements([
{
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
label,
]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// inside the label and within the end point's handle radius, but
// farther from the arrow's path than the arrow's own hit threshold
const point = pointFrom<GlobalPoint>(p2[0], p2[1] + 9);
mouse.moveTo(point[0], point[1]);
expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
expect(GlobalTestState.interactiveCanvas.style.cursor).toBe(
CURSOR_TYPE.POINTER,
);
drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(1);
expect(
(h.elements[0] as ExcalidrawLinearElement).points[1][0],
).toBeCloseTo(p2[0] - p1[0] + 40);
});
it("keeps the arrow selected when a point handle is grabbed beyond the arrow's tip", () => {
const arrow = API.createElement({
type: "arrow",
x: p1[0],
y: p1[1],
width: p2[0] - p1[0],
height: 0,
points: [pointFrom(0, 0), pointFrom(p2[0] - p1[0], 0)],
});
API.setElements([arrow]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// past the end point along the arrow: inside the handle radius, but
// outside the arrow's own hit area
const point = pointFrom<GlobalPoint>(p2[0] + 9, p2[1]);
mouse.moveTo(point[0], point[1]);
expect(h.state.selectedLinearElement?.hoverPointIndex).toBe(1);
drag(point, pointFrom<GlobalPoint>(point[0] + 40, point[1]));
expect(h.state.selectionElement).toBeNull();
expect(h.state.selectedElementIds[arrow.id]).toBe(true);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect(
(h.elements[0] as ExcalidrawLinearElement).points[1][0],
).toBeCloseTo(p2[0] - p1[0] + 40);
});
it("grabs the label when the covering element is below the arrow", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([createOccluder(), arrow, label]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
expect(
(h.elements[2] as ExcalidrawTextElementWithContainer).labelPosition,
).toBeCloseTo(0.75);
});
it("does not grab the label when it is covered by an element above the arrow", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label, createOccluder()]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
drag(labelOnlyPoint, pointFrom<GlobalPoint>(50, 45));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
it("grabs an elbow arrow's label lying over an intermediate route point", () => {
const arrow = API.createElement({
type: "arrow",
x: 0,
y: 0,
width: 100,
height: 100,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 0),
pointFrom<LocalPoint>(100, 100),
],
elbowed: true,
});
const label = {
...API.createElement({
type: "text",
text: "label",
containerId: arrow.id,
width: 30,
height: 30,
}),
// the arc-length middle of this symmetric elbow sits on the
// rounded corner, right next to the route point at (100, 0)
labelPosition: 0.5,
} as ExcalidrawTextElementWithContainer;
API.setElements([
{
...arrow,
boundElements: [{ type: "text", id: label.id } as const],
},
label,
]);
mouse.reset();
// (not by a click, whose pointerup would normalize — reroute — this
// hand-built elbow arrow)
act(() => h.app.selection.select(arrow.id));
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
// inside the label AND within the hit radius of the route point at
// (100, 0) — pre-fix the route point swallowed this pointerdown and
// the label never moved
const grabPoint = pointFrom<GlobalPoint>(97, 3);
drag(
grabPoint,
pointFrom<GlobalPoint>(grabPoint[0] - 40, grabPoint[1]),
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).not.toBe(0.5);
});
it("gives the segment midpoint handle precedence over the label on top of it", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
2,
);
// the label sits centered on the midpoint knob; dragging there must
// bend the arrow, not slide the label
drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
3,
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
it("leaves the segment midpoint handle grabbable under a covered label", () => {
const { arrow, label } = createArrowWithTallLabel();
API.setElements([arrow, label, createOccluder()]);
mouse.reset();
mouse.clickAt(p1[0], p1[1]);
expect(h.state.selectedLinearElement?.elementId).toBe(arrow.id);
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
2,
);
// the midpoint handle sits under the label, which is itself covered
drag(midpoint, pointFrom<GlobalPoint>(midpoint[0], midpoint[1] + 40));
expect(
h.state.selectedLinearElement?.initialState.segmentMidpoint.value,
).not.toBeNull();
expect((h.elements[0] as ExcalidrawLinearElement).points.length).toBe(
3,
);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).labelPosition,
).toBe(0.5);
});
});
});
describe("Test moving linear element points", () => {
+52
View File
@@ -0,0 +1,52 @@
import * as common from "@excalidraw/common";
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { newElement, newLinearElement } from "../src/newElement";
import { mutateElement, newElementWith } from "../src/mutateElement";
describe("element creation time", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it.each([
"rectangle",
"diamond",
"ellipse",
"text",
"line",
"arrow",
"freedraw",
"image",
"frame",
"magicframe",
"embeddable",
"iframe",
] as const)("initializes a new %s before any capture", (type) => {
vi.spyOn(common, "getUpdatedTimestamp").mockReturnValue(123);
const element = API.createElement({ type });
expect(element.created).toBe(123);
vi.mocked(common.getUpdatedTimestamp).mockReturnValue(456);
const edited = newElementWith(element, { x: 50 });
mutateElement(edited, new Map(), { y: 50 });
expect(edited).toMatchObject({ created: 123, updated: 456 });
});
it.each([123, 0, null])(
"preserves explicit created=%s when reconstructing the same element",
(created) => {
const original = newElement({
type: "rectangle",
x: 0,
y: 0,
created,
});
const converted = newLinearElement({ ...original, type: "line" });
expect(converted).toMatchObject({ id: original.id, created });
},
);
});
+200 -25
View File
@@ -1,4 +1,9 @@
import { pointFrom } from "@excalidraw/math";
import {
bezierEquation,
isCurve,
pointDistance,
pointFrom,
} from "@excalidraw/math";
import { Excalidraw } from "@excalidraw/excalidraw";
import {
@@ -12,14 +17,19 @@ import {
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { UI, Keyboard, Pointer } from "@excalidraw/excalidraw/tests/helpers/ui";
import {
act,
render,
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
import type { GlobalPoint } from "@excalidraw/math";
import type { LocalPoint } from "@excalidraw/math";
import { isLinearElement } from "../src/typeChecks";
import { resizeSingleElement } from "../src/resizeElements";
import { distanceToElement } from "../src/distance";
import { getLinearElementPathSegments } from "../src/utils";
import { LinearElementEditor } from "../src/linearElementEditor";
import { getElementPointsCoords } from "../src/bounds";
import { computeContainerDimensionForBoundText } from "../src/textElement";
@@ -229,6 +239,45 @@ describe("generic element", () => {
expect(label.fontSize).toEqual(20);
});
describe.each(["rectangle", "ellipse", "diamond"] as const)(
"%s with a label",
(type) => {
it.each([false, true])(
"flips horizontally while resizing (proportional: %s)",
async (proportional) => {
const container = UI.createElement(type, {
width: 200,
height: 100,
});
const label = await UI.editText(container, "Hello");
UI.resize(container, proportional ? "se" : "e", [-500, 0], {
shift: proportional,
});
expect(container.x).toBeCloseTo(-300);
expect(container.y).toBeCloseTo(0);
expect(container.width).toBeCloseTo(300);
expect(container.height).toBeCloseTo(proportional ? 150 : 100);
expect(label.x + label.width / 2).toBeCloseTo(
container.x + container.width / 2,
0,
);
expect(label.y + label.height / 2).toBeCloseTo(
container.y + container.height / 2,
0,
);
expect(label.angle).toBe(0);
if (proportional) {
expect(label.fontSize).toBeGreaterThan(20);
} else {
expect(label.fontSize).toBe(20);
}
},
);
},
);
it.each<{ handle: TransformHandleDirection; move: [number, number] }>([
{ handle: "n", move: [0, 100] },
{ handle: "s", move: [0, -100] },
@@ -258,6 +307,47 @@ describe("generic element", () => {
expect(rectangle.height).toBeCloseTo(minContainerHeight);
},
);
it("keeps the flipped corner anchored while wrapped text sets the minimum height", async () => {
const rectangle = UI.createElement("rectangle", {
width: 200,
height: 200,
});
const label = await UI.editText(rectangle, "first second third fourth");
const originalElements = arrayToMap(
h.app.scene.getNonDeletedElements().map((element) => ({ ...element })),
);
const originalRectangle = originalElements.get(rectangle.id)!;
let minHeight = 0;
// One SE drag crosses the top edge, stays below the wrapped text's
// minimum height, then grows far enough for the pointer to control it.
for (const nextHeight of [-10, -40, -80, -200]) {
act(() => {
resizeSingleElement(
80,
nextHeight,
h.app.scene.getNonDeletedElement(rectangle.id)!,
originalRectangle,
originalElements,
h.app.scene,
"se",
);
});
expect(rectangle.x).toBe(originalRectangle.x);
expect(rectangle.y + rectangle.height).toBe(originalRectangle.y);
expect(label.y).toBeGreaterThan(rectangle.y);
expect(label.y + label.height).toBeLessThan(
rectangle.y + rectangle.height,
);
if (nextHeight === -10) {
minHeight = rectangle.height;
expect(minHeight).toBeGreaterThan(80);
}
expect(rectangle.height).toBe(Math.max(minHeight, -nextHeight));
}
});
});
describe.each(["line", "freedraw"] as const)("%s element", (type) => {
@@ -490,37 +580,86 @@ describe("arrow element", () => {
});
const label = await UI.editText(arrow, "Hello");
const elementsMap = arrayToMap(h.elements);
UI.resize(arrow, "se", [50, 30]);
let labelPos = LinearElementEditor.getBoundTextElementPosition(
arrow,
label,
elementsMap,
);
expect(labelPos.x + label.width / 2).toBeCloseTo(
arrow.x + arrow.points[2][0],
);
expect(labelPos.y + label.height / 2).toBeCloseTo(
arrow.y + arrow.points[2][1],
);
// independently locate the arc-length midpoint by densely sampling the
// path, so a regression in the arc-length inversion the production code
// uses cannot cancel out of the comparison
const sampledPathMidpoint = (): GlobalPoint => {
const samples: GlobalPoint[] = [];
for (const segment of getLinearElementPathSegments(arrow, elementsMap)) {
for (let i = 0; i <= 1000; i++) {
const t = i / 1000;
samples.push(
isCurve(segment)
? bezierEquation(segment, t)
: pointFrom<GlobalPoint>(
segment[0][0] + t * (segment[1][0] - segment[0][0]),
segment[0][1] + t * (segment[1][1] - segment[0][1]),
),
);
}
}
const cumulative = [0];
for (let i = 1; i < samples.length; i++) {
cumulative.push(
cumulative[i - 1] + pointDistance(samples[i - 1], samples[i]),
);
}
const half = cumulative[cumulative.length - 1] / 2;
return samples[cumulative.findIndex((length) => length >= half)];
};
// the label defaults to the arc-length midpoint of the arrow's path and
// keeps that normalized position through resizes
const expectLabelAtPathMidpoint = () => {
const labelPos = LinearElementEditor.getBoundTextElementPosition(
arrow,
label,
elementsMap,
);
const centerX = labelPos.x + label.width / 2;
const centerY = labelPos.y + label.height / 2;
const pathMidpoint = sampledPathMidpoint();
expect(label.labelPosition).toBe(0.5);
expect(centerX).toBeCloseTo(pathMidpoint[0], 0);
expect(centerY).toBeCloseTo(pathMidpoint[1], 0);
expect(
distanceToElement(arrow, elementsMap, pointFrom(centerX, centerY)),
).toBeLessThan(0.5);
};
expectLabelAtPathMidpoint();
UI.resize(arrow, "se", [50, 30]);
expectLabelAtPathMidpoint();
expect(label.angle).toBeCloseTo(0);
expect(label.fontSize).toEqual(20);
UI.resize(arrow, "w", [20, 0]);
labelPos = LinearElementEditor.getBoundTextElementPosition(
arrow,
label,
elementsMap,
);
expect(labelPos.x + label.width / 2).toBeCloseTo(
arrow.x + arrow.points[2][0],
);
expect(labelPos.y + label.height / 2).toBeCloseTo(
arrow.y + arrow.points[2][1],
);
expectLabelAtPathMidpoint();
expect(label.angle).toBeCloseTo(0);
expect(label.fontSize).toEqual(20);
const { x, width, height } = arrow;
const latestArrow = h.app.scene.getNonDeletedElement(arrow.id)!;
act(() => {
resizeSingleElement(
-2 * width,
2 * height,
latestArrow,
{ ...latestArrow },
arrayToMap(h.elements.map((element) => ({ ...element }))),
h.app.scene,
"se",
{ shouldMaintainAspectRatio: true },
);
});
expect(getBoundsFromPoints(arrow)[2]).toBeCloseTo(x);
expect(arrow.width).toBeCloseTo(2 * width);
expect(label.fontSize).toBeCloseTo(40);
expect(label.angle).toBeCloseTo(0);
expectLabelAtPathMidpoint();
});
it("flips the fixed point binding on negative resize for single bindable", () => {
@@ -595,6 +734,18 @@ describe("text element", () => {
expect(text.fontSize).toBeCloseTo(fontSize * scale);
});
it("resizes by a corner following the axis it grows most", async () => {
const text = UI.createElement("text");
await UI.editText(text, "hello\nworld");
const { width, height, fontSize } = text;
const scale = 60 / width + 1;
UI.resize(text, "se", [60, 5]);
expect(text.width).toBeCloseTo(width * scale);
expect(text.height).toBeCloseTo(height * scale);
expect(text.fontSize).toBeCloseTo(fontSize * scale);
});
// TODO enable this test after adding single text element flipping
it.skip("flips while resizing", async () => {
const text = UI.createElement("text");
@@ -866,6 +1017,30 @@ describe("image element", () => {
});
describe("multiple selection", () => {
it("keeps a flipped text container anchored when its label requires extra height", async () => {
const rectangle = UI.createElement("rectangle", {
position: 0,
width: 200,
height: 35,
});
const label = await UI.editText(rectangle, "hello");
const other = UI.createElement("rectangle", {
x: 300,
y: 0,
size: 100,
});
const originalHeight = rectangle.height;
// Halve the selection and flip vertically. Padding does not scale with
// the font, so even a single-line label needs extra container height.
UI.resize([rectangle, other], "se", [-200, -150], { shift: true });
expect(label.fontSize).toBeCloseTo(10);
expect(label.text).toBe("hello");
expect(rectangle.height).toBeGreaterThan(originalHeight / 2);
expect(rectangle.y + rectangle.height).toBeCloseTo(0);
});
it("resizes with generic elements", async () => {
const rectangle = UI.createElement("rectangle", {
position: 0,
+2 -2
View File
@@ -18,9 +18,9 @@ import {
unmountComponent,
} from "@excalidraw/excalidraw/tests/test-utils";
import type { AppState } from "@excalidraw/excalidraw/types";
import { selectGroupsForSelectedElements } from "@excalidraw/excalidraw/components/App.selection";
import { selectGroupsForSelectedElements } from "../src/groups";
import type { AppState } from "@excalidraw/excalidraw/types";
import type {
ExcalidrawElement,
+62
View File
@@ -13,8 +13,70 @@ Please add the latest change on the top under the correct section.
## Unreleased
### Export API: `exportScene` (2026-10-18) [#12347](https://github.com/excalidraw/excalidraw/pull/12347)
Breaking. `exportToCanvas`, `exportToBlob` and `exportToSvg` (in both `@excalidraw/excalidraw` and `@excalidraw/utils`) are replaced by a single `exportScene`, and every rendering option moved from `appState` into an explicit `config`.
- `exportScene({ type, data, config })` with `type` `"canvas"`, `"png"`, `"jpeg"` or `"svg"` resolves to an `HTMLCanvasElement`, a `Blob` or an `SVGSVGElement`. `exportToClipboard({ type: "png" | "svg" | "json", data, config })` stays. Types: `ExportSceneData`, `ExportSceneConfig`, `ExportSceneOptions`.
- `data` is `{ elements, appState?, files? }`, the shape of a `.excalidraw` file. Only the scene settings a file stores are read from `appState`: `viewBackgroundColor` as the default background, and the grid settings that `embedScene` embeds. Any other key is ignored, so passing a live `appState` can't affect the output.
- Migration:
| Before | Now |
| --- | --- |
| `exportToCanvas({ elements, appState, files, … })` | `exportScene({ type: "canvas", data: { elements, appState, files }, config })` |
| `exportToBlob({ …, mimeType, quality })` | `exportScene({ type: "png" \| "jpeg", …, config })` — `quality` is JPEG-only |
| `exportToSvg({ … })` | `exportScene({ type: "svg", … })` |
| `appState.exportBackground: false` | `config.canvasBackgroundColor: false` (a color string overrides the background; JPEG always gets one) |
| `appState.exportWithDarkMode` | `config.theme: "dark"` |
| `appState.exportScale` | `config.scale` (also multiplies a `maxWidthOrHeight` result) |
| `appState.exportEmbedScene` | `config.embedScene` (png, svg) |
| `appState.frameRendering` | `config.frames: { name?, outline?, clip? }` |
| `exportPadding` | `config.padding` (default 10, as before) |
| `getDimensions: (w, h) => ({ width, height, scale })` | `config.width`/`height`, `maxWidthOrHeight` or `widthOrHeight`, plus `config.scale` — a number, or `(width, height) => number` receiving the export size at scale 1 (padding included), e.g. to cap the output by a pixel budget |
| `maxWidthOrHeight`, `exportingFrame`, `renderEmbeddables`, `skipInliningFonts`, `reuseImages` | same names, in `config` |
- New sizing options: `width`/`height` (only one given: the other follows the content's aspect ratio), `widthOrHeight` (scales the longest side to exactly that size), `fit: "contain" | "none"` and `position: "center" | "topLeft"` within a `width`/`height` frame, and `x`/`y`/`origin` to export a region (cropped, with padding on all sides). The size options are mutually exclusive in the types, and `fit`, `position` and `x`/`y` only combine with `width`/`height`.
- `config.environment` for non-browser hosts: `createCanvas` (e.g. `node-canvas`) and `loadFonts`.
- Canvas dimensions are rounded instead of truncated, so float noise no longer costs a pixel (a 20.5px frame-label band now rounds up), and are at least 1px (flat content with no padding used to produce an empty canvas that couldn't be encoded).
- In dark exports, frame names now use the editor's dark frame-name color (they were dark-filtered twice and came out lighter).
### Selection API (2026-10-10) [#12258](https://github.com/excalidraw/excalidraw/pull/12258)
- New `excalidrawAPI.selection`: `select(elements, opts?)`, `add(elements, opts?)`, `remove(elements, opts?)` and `clear(opts?)`, taking elements or their ids, one or many. Missing and deleted elements are skipped.
- It follows the editor's rules: an element is selected with its group, a frame and its children aren't selected at the same time, and locked elements are skipped. Text editing and cropping end, and the link popup of a lone selected element with a link shows.
- Options: `deep` selects the elements themselves rather than their groups, editing their group if they share one (as Ctrl/Cmd+click does); `includeLocked` selects locked elements too; `captureUpdate` records the change for undo as for `updateScene()` — by default it's recorded along with the next undoable change.
- Like `updateScene()`, the change applies on the next render: read it back through `onChange()` or `getAppState()` after that. It works in view mode too, where the selection shows without the transform handles.
### Wheel navigation (2026-09-13) [#12099](https://github.com/excalidraw/excalidraw/pull/12099)
- Scrolling while holding the wheel (middle) mouse button zooms the canvas around the pointer, the same as ctrl/cmd+wheel — a wheel-button pan can be zoomed one-handed, without reaching for a modifier.
- New `appState.inputDevice` preference (`"auto" | "mouse" | "trackpad"`, default `"auto"`, persisted in browser storage) selecting the wheel mappings. With `"trackpad"` a plain wheel pans; with `"mouse"` a plain wheel zooms. Ctrl/cmd+wheel (how a pinch is delivered) zooms with either device. Shift+wheel pans horizontally, and ctrl/cmd+shift+wheel pans vertically. The wheel-button zoom above is unaffected. `"auto"` is reserved for detecting the device from the wheel events and resolves to `"trackpad"` until that is implemented (`resolveInputDevice()`). Set it from the new "Input device" radio in the main menu's preferences submenu, also exposed as `MainMenu.DefaultItems.Preferences.InputDevice`.
### Sticky notes (2026-09-06) [#12064](https://github.com/excalidraw/excalidraw/pull/12064)
- New `stickynote` element type and toolbar tool (`N`): an always-filled, flat-rendered note whose label auto-fits — the font shrinks from the user's size down to a minimum, and only then does the note grow in height (it never shrinks below the height the user gave it). Click to place a 250×250 note, drag to size it (previewed at the dragged size, snapped to a font-aware minimum on release); text editing starts right away.
- Element model: the note carries `baseHeight` (the user's height; `height ≥ baseHeight`), its label carries `baseFontSize` (the user's font ceiling, `null`/absent on any other text) while `fontSize` holds the fitted size. Read a text element's user-facing size through `getBaseFontSize(text, elementsMap)`.
- Sticky notes are their own color domain: new `appState.currentItemStickynoteStrokeColor` (the note's text color) and `appState.currentItemStickynoteBackgroundColor` defaults, and new customizable top-pick slots `appState.colorTopPicks.stickyNoteStroke` / `stickyNoteBackground`. The stroke and background pickers, both eyedroppers and paste-styles resolve their target (regular / sticky / mixed) at execution time. A note and its label share one ink (the stroke picker reads "Text color" for notes): coloring the label while editing colors the note too, binding a colored text gives the note its color, and the creation-date footer always paints in that ink.
- Skeleton API: `convertToExcalidrawElements([{ type: "stickynote", x, y, label?: { text, fontSize? } }])` creates a note (and fitted label); see the element-skeleton docs.
- Tools can be dragged out of the toolbar: drag the sticky note button onto the canvas to drop a default-sized note where you release it, previewed translucently while dragging (nothing reaches the scene, history or collaborators until the drop; Escape cancels). The mechanism is generic — other tools can opt in.
- Toolbar: on desktop and tablet the image tool moved into the "More tools" menu (still `9`; `UIOptions.tools.image` keeps hiding it; the mobile toolbar keeps its image slot), and tool badges now show the letter shortcuts (`R`, `T`, `N`, …) instead of the numbers, which are no longer contiguous. The number keys keep working.
- Each note shows its creation date (`element.created`) in a footer band — "7 Sep", or "7 Sep 2025" once the year differs — on canvas and in SVG/PNG exports. The band is reserved in the note's layout, so the label never overlaps it; notes without a timestamp keep the band empty.
- Resize semantics: a note's corners resize proportionally by default and scale the label's font ceiling with the note (Shift frees them); its edges resize freely by default (Shift constrains them). Drag-creation is proportional by default too (Shift frees it) and never touches the font ceiling. Width-only gestures keep the base height, height gestures set it, aspect-locked multi-select and Stats group edits scale the ceiling; flips preserve everything. Arrows bound to a note follow it as it grows.
## Excalidraw API
### `setViewport` stops following a collaborator (2026-09-26) [#12184](https://github.com/excalidraw/excalidraw/pull/12184)
- `setViewport` now asks to stop following a collaborator whenever it navigates (`onUserFollow` with `action: "UNFOLLOW"`, if `userToFollow` is set), as a user's pan or zoom does. `setViewport(null)` (clearing a lock) and a target that doesn't resolve don't navigate, and leave following alone.
### `onDuplicate` can replace and veto duplicates (2026-09-18) [#12124](https://github.com/excalidraw/excalidraw/pull/12124)
- `props.onDuplicate` may now return new objects for the duplicated elements in every duplication path. Previously the editor kept using the objects it created, so on paste (and library insert) the frame assignment and bound text redraw went to objects that were no longer in the scene, and alt-drag dragged an element that wasn't in the scene. The returned changes are now merged into the editor's duplicates, so they're part of the duplication's own undo entry and durable increment (no follow-up `updateScene` needed).
- When pasting or inserting onto a frame, the duplicates passed to `onDuplicate` already have their `frameId` set (and are ordered under the frame).
- Omitting a duplicate from the returned array (or returning it as deleted) now reliably prevents that element from being duplicated — previously pasting over a frame brought it back, and alt-drag broke. References to it from the remaining duplicates (bindings, `boundElements`, `frameId`) are cleared, and a bound text isn't duplicated without its container. If no duplicate remains, the duplication is cancelled and the returned elements are ignored: paste and the duplicate action do nothing, and alt-drag moves the original elements instead. When only some duplicates are vetoed during alt-drag, their originals stay where they were.
- `onDuplicate` may return `false` to prevent the duplication as a whole (same as omitting every duplicate, without having to find them).
- `onDuplicate` receives a third argument with lookups covering just the elements taking part in the duplication, so you don't have to derive them by scanning the scene: `{ duplicateElements, originalElements, origIdToDuplicateId, duplicateIdToOrigId }` — the duplicates by id, the elements they were made from by id, and their ids mapped in both directions (`duplicateIdToOrigId` to look up a duplicate's original while modifying it, `origIdToDuplicateId` e.g. for remapping element ids you keep in `customData`). On paste and library insert the originals are the inserted elements, which aren't part of the scene. The maps are read-only.
### Host-controlled active tool (2026-07-14) [#11665](https://github.com/excalidraw/excalidraw/pull/11665)
- Added `activeTool` prop (`{ type: ToolType } | { type: "custom"; customType: string }`) for forcing the active editor tool (controlled). While set, user- and API-driven tool switching is ignored — `setActiveTool` refuses non-matching activations with a console warning, non-forced toolbar buttons render disabled, and the tool-lock toggle (`Q`) is inert — and the editor snaps back if internal flows reset the tool (e.g. `restore()` on scene load). The forced tool behaves as if locked — it doesn't revert to selection after use and drawn elements aren't auto-selected — without mutating `appState.activeTool.locked`, so the user's persisted padlock preference stays untouched. Unset the prop to return tool control to the editor (the current tool stays active). The forced tool must be activatable to take effect — not disabled via `UIOptions.tools`, and (while non-interactive) allowed via `interaction.enabled.tools`; otherwise the editor stays on the `selection` tool and applies the forced tool once it becomes activatable. `image` cannot be forced (its activation opens the file picker). Composes with `interaction.enabled.tools` for presentation-style hosts: force `laser` for the presenter, `selection` + `interaction={false}` for viewers.
+250 -156
View File
@@ -4,8 +4,7 @@ import {
TEXT_ALIGN,
VERTICAL_ALIGN,
arrayToMap,
getFontString,
getStrokeWidthByKey,
isTransparent,
} from "@excalidraw/common";
import {
getOriginalContainerHeightFromCache,
@@ -15,21 +14,25 @@ import {
} from "@excalidraw/element";
import {
DEFAULT_BOUND_TEXT_LABEL_POSITION,
computeBoundTextPosition,
computeContainerDimensionForBoundText,
getBoundTextElement,
normalizeStickyNoteFontSize,
redrawTextBoundingBox,
updateStickyNoteLayout,
} from "@excalidraw/element";
import {
hasBoundTextElement,
isArrowElement,
isStickyNoteElement,
isTextBindableContainer,
isTextElement,
isUsingAdaptiveRadius,
} from "@excalidraw/element";
import { measureText } from "@excalidraw/element";
import { getNonDeletedElements } from "@excalidraw/element";
import { syncMovedIndices } from "@excalidraw/element";
@@ -37,20 +40,58 @@ import { newElement } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import type { Scene } from "@excalidraw/element";
import type {
ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextContainer,
ExcalidrawTextElement,
ExcalidrawTextElementWithContainer,
NonDeleted,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type { Mutable } from "@excalidraw/common/utility-types";
import type { Radians } from "@excalidraw/math";
import { getDefaultAppState } from "../appState";
import { getSelectionStateForElements } from "../components/App.selection";
import { register } from "./register";
import type { AppState } from "../types";
import type { ActionResult } from "./types";
import type { AppClassProperties, AppState } from "../types";
/**
* Frees the container's text as it rendered: wrapped the same, at a fixed
* width.
*/
export const unbindTextFromContainer = (
container: ExcalidrawElement,
boundTextElement: ExcalidrawTextElementWithContainer,
scene: Scene,
) => {
const { x, y } = computeBoundTextPosition(
container,
boundTextElement,
scene.getNonDeletedElementsMap(),
);
scene.mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null,
autoResize: false,
baseFontSize: null,
x,
y,
labelPosition: null,
});
scene.mutateElement(container, {
boundElements: container.boundElements?.filter(
(ele) => ele.id !== boundTextElement.id,
),
});
};
export const actionUnbindText = register({
name: "unbindText",
@@ -64,44 +105,39 @@ export const actionUnbindText = register({
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
const elementsMap = app.scene.getNonDeletedElementsMap();
const freedTextElements: NonDeletedExcalidrawElement[] = [];
selectedElements.forEach((element) => {
const boundTextElement = getBoundTextElement(element, elementsMap);
if (boundTextElement) {
const { width, height } = measureText(
boundTextElement.originalText,
getFontString(boundTextElement),
boundTextElement.lineHeight,
);
freedTextElements.push(boundTextElement);
const originalContainerHeight = getOriginalContainerHeightFromCache(
element.id,
);
resetOriginalContainerCache(element.id);
const { x, y } = computeBoundTextPosition(
element,
boundTextElement,
elementsMap,
);
app.scene.mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null,
width,
height,
text: boundTextElement.originalText,
x,
y,
});
app.scene.mutateElement(element, {
boundElements: element.boundElements?.filter(
(ele) => ele.id !== boundTextElement.id,
),
height: originalContainerHeight
? originalContainerHeight
: element.height,
});
unbindTextFromContainer(element, boundTextElement, app.scene);
if (isStickyNoteElement(element)) {
// an empty note sits at its base height; bound arrows follow
updateStickyNoteLayout(element, app.scene);
} else {
app.scene.mutateElement(element, {
height: originalContainerHeight
? originalContainerHeight
: element.height,
});
}
}
});
return {
elements,
appState,
appState: {
...appState,
// the freed texts stay selected along with their former containers
...getSelectionStateForElements(
[...selectedElements, ...freedTextElements],
getNonDeletedElements(elements),
appState,
),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
@@ -142,7 +178,7 @@ export const actionBindText = register({
const selectedElements = app.scene.getSelectedElements(appState);
let textElement: ExcalidrawTextElement;
let container: ExcalidrawTextContainer;
let container: NonDeleted<ExcalidrawTextContainer>;
if (
isTextElement(selectedElements[0]) &&
@@ -152,35 +188,85 @@ export const actionBindText = register({
container = selectedElements[1];
} else {
textElement = selectedElements[1] as ExcalidrawTextElement;
container = selectedElements[0] as ExcalidrawTextContainer;
container = selectedElements[0] as NonDeleted<ExcalidrawTextContainer>;
}
app.scene.mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,
});
app.scene.mutateElement(container, {
boundElements: (container.boundElements || []).concat({
type: "text",
id: textElement.id,
}),
});
const originalContainerHeight = container.height;
redrawTextBoundingBox(textElement, container, app.scene);
// overwritting the cache with original container height so
// it can be restored when unbind
updateOriginalContainerCache(container.id, originalContainerHeight);
return {
elements: pushTextAboveContainer(elements, container, textElement),
appState: { ...appState, selectedElementIds: { [container.id]: true } },
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
return bindTextToContainer(elements, appState, textElement, container, app);
},
});
/**
* A note and its label share one ink: the text the user styled wins, unless it
* is transparent (a note's label never is).
*/
export const getStickyNoteInk = (
textElement: ExcalidrawTextElement,
container: ExcalidrawElement,
) =>
isStickyNoteElement(container)
? isTransparent(textElement.strokeColor)
? container.strokeColor
: textElement.strokeColor
: null;
/** binds the text to the (label-less) container, selecting the container */
export const bindTextToContainer = (
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
textElement: ExcalidrawTextElement,
container: NonDeleted<ExcalidrawTextContainer>,
app: AppClassProperties,
): ActionResult => {
const stickyInk = getStickyNoteInk(textElement, container);
app.scene.mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,
labelPosition: isArrowElement(container)
? DEFAULT_BOUND_TEXT_LABEL_POSITION
: null,
...(stickyInk
? {
baseFontSize: normalizeStickyNoteFontSize(
textElement.baseFontSize ?? textElement.fontSize,
),
strokeColor: stickyInk,
}
: null),
});
app.scene.mutateElement(container, {
boundElements: (container.boundElements || []).concat({
type: "text",
id: textElement.id,
}),
// the footer paints with the note's ink
...(stickyInk ? { strokeColor: stickyInk } : null),
});
const originalContainerHeight = container.height;
redrawTextBoundingBox(textElement, container, app.scene);
// overwritting the cache with original container height so
// it can be restored when unbind
updateOriginalContainerCache(container.id, originalContainerHeight);
const nextElements = pushTextAboveContainer(elements, container, textElement);
return {
elements: nextElements,
appState: {
...appState,
// with the line editor of an arrow
...getSelectionStateForElements(
[container],
getNonDeletedElements(nextElements),
appState,
),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
};
const pushTextAboveContainer = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
@@ -201,7 +287,7 @@ const pushTextAboveContainer = (
return updatedElements;
};
const pushContainerBelowText = (
export const pushContainerBelowText = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
textElement: ExcalidrawTextElement,
@@ -232,112 +318,120 @@ export const actionWrapTextInContainer = register({
);
return selectedElements.length > 0 && someTextElements;
},
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
let updatedElements: readonly ExcalidrawElement[] = elements.slice();
const containerIds: Mutable<AppState["selectedElementIds"]> = {};
perform: (elements, appState, _, app) =>
wrapTextsInContainers(
elements,
appState,
app.scene
.getSelectedElements(appState)
.filter(
(element): element is NonDeleted<ExcalidrawTextElement> =>
isTextElement(element) && !isBoundToContainer(element),
),
app,
),
});
for (const textElement of selectedElements) {
if (isTextElement(textElement) && !isBoundToContainer(textElement)) {
const container = newElement({
type: "rectangle",
backgroundColor: appState.currentItemBackgroundColor,
boundElements: [
...(textElement.boundElements || []),
{ id: textElement.id, type: "text" },
],
angle: textElement.angle,
fillStyle: appState.currentItemFillStyle,
strokeColor: appState.currentItemStrokeColor,
roughness: appState.currentItemRoughness,
strokeWidth: getStrokeWidthByKey(
"rectangle",
appState.currentItemStrokeWidthKey,
),
strokeStyle: appState.currentItemStrokeStyle,
roundness:
appState.currentItemRoundness === "round"
? {
type: isUsingAdaptiveRadius("rectangle")
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
opacity: 100,
locked: false,
x: textElement.x - BOUND_TEXT_PADDING,
y: textElement.y - BOUND_TEXT_PADDING,
width: computeContainerDimensionForBoundText(
textElement.width,
"rectangle",
),
height: computeContainerDimensionForBoundText(
textElement.height,
"rectangle",
),
groupIds: textElement.groupIds,
frameId: textElement.frameId,
});
/** wraps each (unbound) text in a new container, selecting the containers */
export const wrapTextsInContainers = (
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
textElements: readonly ExcalidrawTextElement[],
app: AppClassProperties,
): ActionResult => {
let updatedElements: readonly ExcalidrawElement[] = elements.slice();
const containerIds: Mutable<AppState["selectedElementIds"]> = {};
// update bindings
if (textElement.boundElements?.length) {
const linearElementIds = textElement.boundElements
.filter((ele) => ele.type === "arrow")
.map((el) => el.id);
const linearElements = updatedElements.filter((ele) =>
linearElementIds.includes(ele.id),
) as ExcalidrawLinearElement[];
linearElements.forEach((ele) => {
let startBinding = ele.startBinding;
let endBinding = ele.endBinding;
if (startBinding?.elementId === textElement.id) {
startBinding = {
...startBinding,
elementId: container.id,
};
for (const textElement of textElements) {
// a default rectangle (not the current item's style), drawn in the
// text's color
const container = newElement({
type: "rectangle",
boundElements: [
...(textElement.boundElements || []),
{ id: textElement.id, type: "text" },
],
angle: textElement.angle,
strokeColor: textElement.strokeColor,
roundness:
getDefaultAppState().currentItemRoundness === "round"
? {
type: isUsingAdaptiveRadius("rectangle")
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
x: textElement.x - BOUND_TEXT_PADDING,
y: textElement.y - BOUND_TEXT_PADDING,
width: computeContainerDimensionForBoundText(
textElement.width,
"rectangle",
),
height: computeContainerDimensionForBoundText(
textElement.height,
"rectangle",
),
groupIds: textElement.groupIds,
frameId: textElement.frameId,
});
if (endBinding?.elementId === textElement.id) {
endBinding = { ...endBinding, elementId: container.id };
}
// update bindings
if (textElement.boundElements?.length) {
const linearElementIds = textElement.boundElements
.filter((ele) => ele.type === "arrow")
.map((el) => el.id);
const linearElements = updatedElements.filter((ele) =>
linearElementIds.includes(ele.id),
) as ExcalidrawLinearElement[];
linearElements.forEach((ele) => {
let startBinding = ele.startBinding;
let endBinding = ele.endBinding;
if (startBinding || endBinding) {
app.scene.mutateElement(ele, {
startBinding,
endBinding,
});
}
});
if (startBinding?.elementId === textElement.id) {
startBinding = {
...startBinding,
elementId: container.id,
};
}
app.scene.mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
boundElements: null,
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
});
if (endBinding?.elementId === textElement.id) {
endBinding = { ...endBinding, elementId: container.id };
}
redrawTextBoundingBox(textElement, container, app.scene);
updatedElements = pushContainerBelowText(
[...updatedElements, container],
container,
textElement,
);
containerIds[container.id] = true;
}
if (startBinding || endBinding) {
app.scene.mutateElement(ele, {
startBinding,
endBinding,
});
}
});
}
return {
elements: updatedElements,
appState: {
...appState,
selectedElementIds: containerIds,
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
});
app.scene.mutateElement(textElement, {
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
boundElements: null,
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
});
redrawTextBoundingBox(textElement, container, app.scene);
updatedElements = pushContainerBelowText(
[...updatedElements, container],
container,
textElement,
);
containerIds[container.id] = true;
}
return {
elements: updatedElements,
appState: {
...appState,
selectedElementIds: containerIds,
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
};
+44 -24
View File
@@ -111,6 +111,8 @@ export const actionClearCanvas = register({
gridStep: appState.gridStep,
gridModeEnabled: appState.gridModeEnabled,
stats: appState.stats,
colorTopPicks: appState.colorTopPicks,
fontTopPicks: appState.fontTopPicks,
activeTool:
appState.activeTool.type === "image"
? {
@@ -153,17 +155,24 @@ export const actionZoomIn = register({
PanelComponent: ({ updateData }) => {
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
<IconButton
type="button"
className="zoom-in-button zoom-button"
icon={ZoomInIcon}
title={`${t("buttons.zoomIn")} — ${getShortcutKey("CtrlOrCmd++")}`}
aria-label={t("buttons.zoomIn")}
disabled={zoomValue >= MAX_ZOOM}
onClick={() => {
updateData(null);
}}
/>
<Tooltip
label={`${t("buttons.zoomIn")} — ${getShortcutKey("CtrlOrCmd++")}`}
className="zoom-in-button-wrapper"
delay
>
<IconButton
type="button"
className="zoom-in-button zoom-button"
icon={ZoomInIcon}
aria-label={t("buttons.zoomIn")}
// the shortcut used to reach AT via the (now removed) native title
aria-keyshortcuts={getShortcutKey("CtrlOrCmd++")}
disabled={zoomValue >= MAX_ZOOM}
onClick={() => {
updateData(null);
}}
/>
</Tooltip>
);
},
keyTest: (event) =>
@@ -200,17 +209,24 @@ export const actionZoomOut = register({
PanelComponent: ({ updateData }) => {
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
<IconButton
type="button"
className="zoom-out-button zoom-button"
icon={ZoomOutIcon}
title={`${t("buttons.zoomOut")} — ${getShortcutKey("CtrlOrCmd+-")}`}
aria-label={t("buttons.zoomOut")}
disabled={zoomValue <= MIN_ZOOM}
onClick={() => {
updateData(null);
}}
/>
<Tooltip
label={`${t("buttons.zoomOut")} — ${getShortcutKey("CtrlOrCmd+-")}`}
className="zoom-out-button-wrapper"
delay
>
<IconButton
type="button"
className="zoom-out-button zoom-button"
icon={ZoomOutIcon}
aria-label={t("buttons.zoomOut")}
// the shortcut used to reach AT via the (now removed) native title
aria-keyshortcuts={getShortcutKey("CtrlOrCmd+-")}
disabled={zoomValue <= MIN_ZOOM}
onClick={() => {
updateData(null);
}}
/>
</Tooltip>
);
},
keyTest: (event) =>
@@ -252,11 +268,15 @@ export const actionResetZoom = register({
PanelComponent: ({ updateData }) => {
const zoomValue = useAppStateValue((appState) => appState.zoom.value);
return (
<Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}>
<Tooltip
label={t("buttons.resetZoom")}
style={{ height: "100%" }}
className="reset-zoom-button-wrapper"
delay
>
<IconButton
type="button"
className="reset-zoom-button zoom-button"
title={t("buttons.resetZoom")}
aria-label={t("buttons.resetZoom")}
onClick={() => {
updateData(null);
@@ -89,7 +89,7 @@ export const actionPaste = register({
}
try {
app.pasteFromClipboard(createPasteEvent({ types }));
app.clipboard.pasteFromClipboard(createPasteEvent({ types }));
} catch (error: any) {
console.error(error);
return {
@@ -116,7 +116,13 @@ export const actionCut = register<ClipboardEvent | null>({
trackEvent: { category: "element" },
perform: (elements, appState, event, app) => {
actionCopy.perform(elements, appState, event, app);
return actionDeleteSelected.perform(elements, appState, null, app);
// the cut frame's children are on the clipboard with it, so go with it
return actionDeleteSelected.perform(
elements,
appState,
{ withFrameChildren: true },
app,
);
},
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X,
});
@@ -146,7 +152,6 @@ export const actionCopyAsSvg = register({
appState,
app.files,
{
...appState,
exportingFrame,
name: app.getName(),
},
@@ -213,7 +218,6 @@ export const actionCopyAsPng = register({
);
try {
await exportCanvas("clipboard", exportedElements, appState, app.files, {
...appState,
exportingFrame,
name: app.getName(),
});
@@ -4,6 +4,7 @@ import { Excalidraw } from "../index";
import { API } from "../tests/helpers/api";
import { act, assertElements, render } from "../tests/test-utils";
import { actionCut } from "./actionClipboard";
import { actionDeleteSelected } from "./actionDeleteSelected";
const { h } = window;
@@ -211,3 +212,67 @@ describe("deleting selected elements when frame selected should keep children +
]);
});
});
describe("cutting a selected frame takes its children along", () => {
beforeEach(async () => {
await render(<Excalidraw />);
});
const createFrameWithChildren = () => {
const f1 = API.createElement({ type: "frame" });
const r1 = API.createElement({ type: "rectangle", frameId: f1.id });
const r2 = API.createElement({ type: "rectangle", frameId: f1.id });
const t1 = API.createElement({
type: "text",
containerId: r2.id,
frameId: f1.id,
});
h.app.scene.mutateElement(r2, {
boundElements: [{ type: "text", id: t1.id }],
});
API.setElements([f1, r1, r2, t1]);
return { f1, r1, r2, t1 };
};
/** as on ctrl+x, with the clipboard data of the cut event */
const cut = () => {
const data = new Map<string, string>();
const event = {
clipboardData: {
setData: (type: string, value: string) => data.set(type, value),
getData: (type: string) => data.get(type),
},
} as unknown as ClipboardEvent;
act(() => {
h.app.actionManager.executeAction(actionCut, "keyboard", event);
});
};
it("frame only", async () => {
const { f1, r1, r2, t1 } = createFrameWithChildren();
API.setSelectedElements([f1]);
cut();
assertElements(h.elements, [
{ id: f1.id, isDeleted: true },
{ id: r1.id, isDeleted: true },
{ id: r2.id, isDeleted: true },
{ id: t1.id, isDeleted: true },
]);
});
it("frame + children selected", async () => {
const { f1, r1, r2, t1 } = createFrameWithChildren();
API.setSelectedElements([f1, r1, r2]);
cut();
assertElements(h.elements, [
{ id: f1.id, isDeleted: true },
{ id: r1.id, isDeleted: true },
{ id: r2.id, isDeleted: true },
{ id: t1.id, isDeleted: true },
]);
});
});
@@ -16,10 +16,7 @@ import {
} from "@excalidraw/element";
import { getFrameChildren } from "@excalidraw/element";
import {
getElementsInGroup,
selectGroupsForSelectedElements,
} from "@excalidraw/element";
import { getElementsInGroup } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
@@ -32,6 +29,8 @@ import { IconButton } from "../components/IconButton";
import { useStylesPanelMode } from "../components/App";
import { selectGroupsForSelectedElements } from "../components/App.selection";
import { register } from "./register";
import type { AppClassProperties, AppState } from "../types";
@@ -40,6 +39,8 @@ const deleteSelectedElements = (
elements: readonly ExcalidrawElement[],
appState: AppState,
app: AppClassProperties,
/** a deleted frame takes its children along, rather than leaving them */
withFrameChildren: boolean,
) => {
const framesToBeDeleted = new Set(
getSelectedElements(
@@ -47,6 +48,8 @@ const deleteSelectedElements = (
appState,
).map((el) => el.id),
);
const isChildOfDeletedFrame = (el: ExcalidrawElement) =>
!!el.frameId && framesToBeDeleted.has(el.frameId);
const selectedElementIds: Record<ExcalidrawElement["id"], true> = {};
@@ -54,7 +57,7 @@ const deleteSelectedElements = (
const processedElements = new Set<ExcalidrawElement["id"]>();
for (const frameId of framesToBeDeleted) {
for (const frameId of withFrameChildren ? [] : framesToBeDeleted) {
const frameChildren = getFrameChildren(elements, frameId);
for (const el of frameChildren) {
if (processedElements.has(el.id)) {
@@ -76,20 +79,24 @@ const deleteSelectedElements = (
let shouldSelectEditingGroup = true;
const nextElements = elements.map((el) => {
if (appState.selectedElementIds[el.id]) {
if (
appState.selectedElementIds[el.id] ||
(withFrameChildren && isChildOfDeletedFrame(el))
) {
const boundElement = isBoundToContainer(el)
? getContainerElement(el, elementsMap)
: null;
if (el.frameId && framesToBeDeleted.has(el.frameId)) {
if (!withFrameChildren && isChildOfDeletedFrame(el)) {
shouldSelectEditingGroup = false;
selectedElementIds[el.id] = true;
return el;
}
if (
boundElement?.frameId &&
framesToBeDeleted.has(boundElement?.frameId)
!withFrameChildren &&
boundElement &&
isChildOfDeletedFrame(boundElement)
) {
return el;
}
@@ -113,7 +120,7 @@ const deleteSelectedElements = (
}
// if deleting a frame, remove the children from it and select them
if (el.frameId && framesToBeDeleted.has(el.frameId)) {
if (isChildOfDeletedFrame(el)) {
shouldSelectEditingGroup = false;
if (!isBoundToContainer(el)) {
selectedElementIds[el.id] = true;
@@ -205,7 +212,9 @@ const handleGroupEditingState = (
return appState;
};
export const actionDeleteSelected = register({
export const actionDeleteSelected = register<{
withFrameChildren?: boolean;
} | null>({
name: "deleteSelectedElements",
label: "labels.delete",
icon: TrashIcon,
@@ -273,7 +282,12 @@ export const actionDeleteSelected = register({
}
let { elements: nextElements, appState: nextAppState } =
deleteSelectedElements(elements, appState, app);
deleteSelectedElements(
elements,
appState,
app,
!!formData?.withFrameChildren,
);
fixBindingsAfterDeletion(
nextElements,
@@ -2,7 +2,6 @@ import {
getElementsInGroup,
isSomeElementSelected,
makeNextSelectedElementIds,
selectGroupsForSelectedElements,
} from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import { KEYS, isWritableElement, updateActiveTool } from "@excalidraw/common";
@@ -11,6 +10,8 @@ import type { GroupId } from "@excalidraw/element/types";
import { TOGGLE_TOOLS } from "../components/Tools";
import { selectGroupsForSelectedElements } from "../components/App.selection";
import { register } from "./register";
import type { AppClassProperties, AppState } from "../types";
@@ -67,6 +68,7 @@ export const actionDeselect = register({
trackEvent: false,
perform: (_elements, appState, _, app) => {
const activeTool = getNextActiveTool(appState, app);
app.cursor.applyForTool(activeTool);
if (appState.editingGroupId) {
const nonDeletedElements = app.scene.getNonDeletedElements();
@@ -103,7 +105,6 @@ export const actionDeselect = register({
selectionElement: null,
showHyperlinkPopup: false,
suggestedBinding: null,
hoveredArrowTextAnchor: null,
frameToHighlight: null,
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
@@ -122,7 +123,6 @@ export const actionDeselect = register({
selectionElement: null,
showHyperlinkPopup: false,
suggestedBinding: null,
hoveredArrowTextAnchor: null,
frameToHighlight: null,
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
@@ -9,10 +9,7 @@ import { getNonDeletedElements } from "@excalidraw/element";
import { LinearElementEditor } from "@excalidraw/element";
import {
getSelectedElements,
getSelectionStateForElements,
} from "@excalidraw/element";
import { getSelectedElements } from "@excalidraw/element";
import { syncMovedIndices } from "@excalidraw/element";
@@ -29,6 +26,8 @@ import { getShortcutKey } from "../shortcut";
import { useStylesPanelMode } from "../components/App";
import { getSelectionStateForElements } from "../components/App.selection";
import { register } from "./register";
export const actionDuplicateSelection = register({
@@ -60,7 +59,7 @@ export const actionDuplicateSelection = register({
}
}
let { duplicatedElements, elementsWithDuplicates } = duplicateElements({
const duplication = duplicateElements({
type: "in-place",
elements,
idsOfElementsToDuplicate: arrayToMap(
@@ -82,16 +81,24 @@ export const actionDuplicateSelection = register({
},
});
if (app.props.onDuplicate && elementsWithDuplicates) {
const mappedElements = app.props.onDuplicate(
elementsWithDuplicates,
elements,
);
if (mappedElements) {
elementsWithDuplicates = mappedElements;
let { duplicatedElements, elementsWithDuplicates } = duplication;
if (app.props.onDuplicate) {
({ elements: elementsWithDuplicates, duplicatedElements } =
app.duplicate.runOnDuplicate(
duplication,
elementsWithDuplicates,
elements,
));
// host vetoed the duplication
if (!duplicatedElements.length) {
return false;
}
}
app.duplicate.advanceListMarkers(duplicatedElements);
return {
elements: syncMovedIndices(
elementsWithDuplicates,
@@ -47,6 +47,7 @@ import type { AppState } from "../types";
type FormData = {
event: PointerEvent;
sceneCoords: { x: number; y: number };
hitBoundText?: boolean;
};
export const actionFinalize = register<FormData>({
@@ -86,7 +87,10 @@ export const actionFinalize = register<FormData>({
if (
isBindingElement(element) &&
!appState.selectedLinearElement.segmentMidPointHoveredCoords
!appState.selectedLinearElement.segmentMidPointHoveredCoords &&
// a label drag along the arrow moves no endpoint, so it must not
// rebind either of them
!data.hitBoundText
) {
const newArrow = !!appState.newElement;
@@ -193,7 +197,6 @@ export const actionFinalize = register<FormData>({
},
selectionElement: null,
suggestedBinding: null,
hoveredArrowTextAnchor: null,
newElement: null,
multiElement: null,
},
@@ -202,9 +205,7 @@ export const actionFinalize = register<FormData>({
}
}
if (window.document.activeElement instanceof HTMLElement) {
focusContainer();
}
focusContainer();
// clean up pending gesture even if active tool is already not drawShape
const hadPendingSketch = app.drawShape.hasPendingGesture();
@@ -399,7 +400,6 @@ export const actionFinalize = register<FormData>({
multiElement: null,
editingTextElement: null,
suggestedBinding: null,
hoveredArrowTextAnchor: null,
frameToHighlight: null,
selectedElementIds: isDrawShapeTool
? {}
+165 -42
View File
@@ -1,26 +1,42 @@
import { getNonDeletedElements } from "@excalidraw/element";
import { mutateElement } from "@excalidraw/element";
import { newFrameElement } from "@excalidraw/element";
import { isFrameLikeElement } from "@excalidraw/element";
import {
isBoundToContainer,
isFrameLikeElement,
isImageElement,
} from "@excalidraw/element";
import {
addElementsToFrame,
removeAllElementsFromFrame,
} from "@excalidraw/element";
import { getFrameChildren } from "@excalidraw/element";
import { fixBindingsAfterDeletion } from "@excalidraw/element";
import { getElementsInGroup } from "@excalidraw/element";
import { getCommonBounds } from "@excalidraw/element";
import {
boundsContainBounds,
getCommonBounds,
getElementBounds,
} from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import type { ExcalidrawElement } from "@excalidraw/element/types";
import type {
ElementsMap,
ExcalidrawElement,
ExcalidrawFrameLikeElement,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import { getSelectionStateForElements } from "../components/App.selection";
import { getSelectedElements } from "../scene";
import { register } from "./register";
import type { AppClassProperties, UIAppState } from "../types";
import type { ActionResult } from "./types";
import type { AppClassProperties, AppState, UIAppState } from "../types";
const isSingleFrameSelected = (
appState: UIAppState,
@@ -122,9 +138,147 @@ export const actionupdateFrameRendering = register({
checked: (appState) => appState.frameRendering.enabled,
});
const FRAME_PADDING = 16;
/**
* The frame that wrapping the selection removes instead: the one frame the
* selection holds (along with any of its children), or, with no frame
* selected, the frame whose children are all selected.
*/
export const getFrameToUnwrap = (
selectedElements: readonly ExcalidrawElement[],
elementsMap: ElementsMap,
): ExcalidrawFrameLikeElement | null => {
const elements = selectedElements.filter(
(element) => !isBoundToContainer(element),
);
const frames = elements.filter((element) => isFrameLikeElement(element));
if (frames.length > 1) {
return null;
}
const frameId = frames[0]?.id ?? elements[0]?.frameId;
const frame = frameId ? elementsMap.get(frameId) : null;
if (!frame || frame.isDeleted || !isFrameLikeElement(frame)) {
return null;
}
const selectedChildren = elements.filter(
(element) => element.frameId === frame.id,
);
if (selectedChildren.length + frames.length !== elements.length) {
return null;
}
if (frames.length) {
return frame;
}
// with no frame selected, all of its children have to be
const children = getFrameChildren(elementsMap, frame.id).filter(
(element) => !element.isDeleted && !isBoundToContainer(element),
);
return children.length === selectedChildren.length ? frame : null;
};
/** removes the frame, keeping its children selected in its place */
export const unwrapFrame = (
elements: readonly ExcalidrawElement[],
appState: AppState,
frame: ExcalidrawFrameLikeElement,
app: AppClassProperties,
): ActionResult => {
const children = getNonDeletedElements(getFrameChildren(elements, frame.id));
removeAllElementsFromFrame(elements, frame);
app.scene.mutateElement(frame, { isDeleted: true });
fixBindingsAfterDeletion(elements, [frame]);
return {
elements,
appState: {
...appState,
...getSelectionStateForElements(
children,
getNonDeletedElements(elements),
{ ...appState, editingGroupId: null },
),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
};
/** wraps the selection in a new frame — edge to edge when it's an image */
export const wrapInFrame = (
elements: readonly ExcalidrawElement[],
appState: AppState,
selectedElements: NonDeletedExcalidrawElement[],
app: AppClassProperties,
): ActionResult => {
const elementsMap = app.scene.getNonDeletedElementsMap();
const bounds = getCommonBounds(selectedElements, elementsMap);
// an image framed along with what's drawn on it keeps no margin
const padding = selectedElements.some(
(element) =>
isImageElement(element) &&
boundsContainBounds(getElementBounds(element, elementsMap), bounds),
)
? 0
: FRAME_PADDING;
const [x1, y1, x2, y2] = bounds;
const frame = newFrameElement({
x: x1 - padding,
y: y1 - padding,
width: x2 - x1 + padding * 2,
height: y2 - y1 + padding * 2,
});
// for a selected partial group, we want to remove it from the remainder of the group
if (appState.editingGroupId) {
const elementsInGroup = getElementsInGroup(
selectedElements,
appState.editingGroupId,
);
for (const elementInGroup of elementsInGroup) {
const index = elementInGroup.groupIds.indexOf(appState.editingGroupId);
mutateElement(elementInGroup, elementsMap, {
groupIds: elementInGroup.groupIds.slice(0, index),
});
}
}
const nextElements = addElementsToFrame(
[...app.scene.getElementsIncludingDeleted(), frame],
selectedElements,
frame,
);
return {
elements: nextElements,
appState: {
...appState,
// dropping the line editor of a framed arrow
...getSelectionStateForElements(
[frame],
getNonDeletedElements(nextElements),
appState,
),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
};
export const actionWrapSelectionInFrame = register({
name: "wrapSelectionInFrame",
label: "labels.wrapSelectionInFrame",
label: (elements, appState, app) =>
getFrameToUnwrap(
app.scene.getSelectedElements(appState),
app.scene.getNonDeletedElementsMap(),
)
? "labels.removeFrame"
: "labels.wrapSelectionInFrame",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(elements, appState);
@@ -136,45 +290,14 @@ export const actionWrapSelectionInFrame = register({
},
perform: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(elements, appState);
const elementsMap = app.scene.getNonDeletedElementsMap();
const [x1, y1, x2, y2] = getCommonBounds(selectedElements, elementsMap);
const PADDING = 16;
const frame = newFrameElement({
x: x1 - PADDING,
y: y1 - PADDING,
width: x2 - x1 + PADDING * 2,
height: y2 - y1 + PADDING * 2,
});
// for a selected partial group, we want to remove it from the remainder of the group
if (appState.editingGroupId) {
const elementsInGroup = getElementsInGroup(
selectedElements,
appState.editingGroupId,
);
for (const elementInGroup of elementsInGroup) {
const index = elementInGroup.groupIds.indexOf(appState.editingGroupId);
mutateElement(elementInGroup, elementsMap, {
groupIds: elementInGroup.groupIds.slice(0, index),
});
}
}
const nextElements = addElementsToFrame(
[...app.scene.getElementsIncludingDeleted(), frame],
// selecting all of a frame's children unwraps them instead
const frameToUnwrap = getFrameToUnwrap(
selectedElements,
frame,
app.scene.getNonDeletedElementsMap(),
);
return {
elements: nextElements,
appState: {
selectedElementIds: { [frame.id]: true },
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
return frameToUnwrap
? unwrapFrame(elements, appState, frameToUnwrap, app)
: wrapInFrame(elements, appState, selectedElements, app);
},
});
+2 -1
View File
@@ -19,7 +19,6 @@ import { KEYS, randomId, arrayToMap } from "@excalidraw/common";
import {
getSelectedGroupIds,
selectGroup,
selectGroupsForSelectedElements,
getElementsInGroup,
addToGroup,
removeFromSelectedGroups,
@@ -45,6 +44,8 @@ import { isSomeElementSelected } from "../scene";
import { getShortcutKey } from "../shortcut";
import { selectGroupsForSelectedElements } from "../components/App.selection";
import { register } from "./register";
import type { AppClassProperties, UIAppState } from "../types";
@@ -71,6 +71,18 @@ describe("element locking", () => {
expect(hachureFillButton).toBe(null);
});
it("should not show fill style for sticky note tool", () => {
UI.clickTool("stickynote");
API.setAppState({
currentItemBackgroundColor: DEFAULT_ELEMENT_BACKGROUND_PICKS[1],
currentItemFillStyle: "hachure",
});
const hachureFillButton = queryByTestId(document.body, `fill-hachure`);
expect(hachureFillButton).toBe(null);
});
it("should show horizontal text align for text tool", () => {
UI.clickTool("text");
@@ -110,6 +122,19 @@ describe("element locking", () => {
expect(crossHatchButton).toBe(null);
});
it("should not show fill style for selected sticky note", () => {
const stickyNote = API.createElement({
type: "stickynote",
backgroundColor: DEFAULT_ELEMENT_BACKGROUND_PICKS[1],
fillStyle: "hachure",
});
API.setElements([stickyNote]);
API.setSelectedElements([stickyNote]);
const hachureFillButton = queryByTestId(document.body, `fill-hachure`);
expect(hachureFillButton).toBe(null);
});
it("should highlight common stroke width of selected elements", () => {
const rect1 = API.createElement({
type: "rectangle",
+162 -77
View File
@@ -6,10 +6,6 @@ import {
BUCKET_FILL_BACKGROUND_PICKS,
COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_PICKS,
getBucketFillBackgroundColor,
DEFAULT_ELEMENT_STROKE_COLOR_PALETTE,
DEFAULT_ELEMENT_STROKE_PICKS,
ARROW_TYPE,
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
@@ -32,8 +28,10 @@ import {
import {
canBecomePolygon,
normalizeStickyNote,
getNonDeletedElements,
isNonDeletedElement,
syncStickyNoteInk,
} from "@excalidraw/element";
import {
@@ -49,6 +47,8 @@ import { getArrowheadForPicker } from "@excalidraw/element";
import {
getBoundTextElement,
getBaseFontSize,
getBaseFontSizeUpdate,
redrawTextBoundingBox,
} from "@excalidraw/element";
@@ -58,11 +58,17 @@ import {
isElbowArrow,
isLinearElement,
isLineElement,
isStickyNoteElement,
isTextElement,
isUsingAdaptiveRadius,
} from "@excalidraw/element";
import { hasStrokeColor } from "@excalidraw/element";
import {
getColorTargetElement,
getColorUpdate,
hasFillStyle,
hasStrokeColor,
} from "@excalidraw/element";
import {
updateElbowArrowPoints,
@@ -165,6 +171,10 @@ import {
import { getShortcutKey } from "../shortcut";
import {
getColorTargetAppStateUpdates,
resolveColorTarget,
} from "./colorTargets";
import { register } from "./register";
import type { AppClassProperties, AppState, Primitive } from "../types";
@@ -204,7 +214,13 @@ export const changeProperty = (
"[NONDELETED][INVARIANT] changeProperty(): skipping deleted selected/editing element",
);
}
return callback(element as NonDeletedExcalidrawElement);
const nextElement = callback(element as NonDeletedExcalidrawElement);
// sticky notes keep their data invariants (never-transparent colors,
// solid fill, minimum size) whatever property was written; a no-op
// normalization returns the same object
return isStickyNoteElement(nextElement)
? normalizeStickyNote(nextElement)
: nextElement;
}
return element;
});
@@ -283,6 +299,7 @@ const changeFontSize = (
fallbackValue?: ExcalidrawTextElement["fontSize"],
) => {
const newFontSizes = new Set<number>();
const elementsMap = app.scene.getNonDeletedElementsMap();
const updatedElements = changeProperty(
elements,
@@ -291,15 +308,13 @@ const changeFontSize = (
if (isTextElement(oldElement)) {
const newFontSize = getNewFontSize(oldElement);
newFontSizes.add(newFontSize);
const container = app.scene.getContainerElement(oldElement);
let newElement: ExcalidrawTextElement = newElementWith(oldElement, {
fontSize: newFontSize,
});
redrawTextBoundingBox(
newElement,
app.scene.getContainerElement(oldElement),
app.scene,
let newElement: ExcalidrawTextElement = newElementWith(
oldElement,
getBaseFontSizeUpdate(oldElement, newFontSize, elementsMap),
);
redrawTextBoundingBox(newElement, container, app.scene);
newElement = offsetElementAfterFontResize(
oldElement,
@@ -341,58 +356,75 @@ const changeFontSize = (
// -----------------------------------------------------------------------------
export const actionChangeStrokeColor = register<
Pick<AppState, "currentItemStrokeColor">
Partial<AppState> & { color?: string }
>({
name: "changeStrokeColor",
label: "labels.stroke",
trackEvent: false,
perform: (elements, appState, value) => {
const { color, ...appStateUpdates } = value ?? {};
if (color === undefined) {
return {
appState: { ...appState, ...appStateUpdates },
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
}
// resolved from the state the action runs against — never from the
// render-time closure of the memoized picker (see `resolveColorTarget`)
const target = resolveColorTarget(appState, elements, "strokeColor");
const elementsMap = arrayToMap(elements);
return {
...(value?.currentItemStrokeColor && {
elements: changeProperty(
// a note and its label share one ink: coloring the label while editing
// it (no selection) colors the note too — the footer paints with it
elements: syncStickyNoteInk(
changeProperty(
elements,
appState,
(el) => {
return hasStrokeColor(el.type)
? newElementWith(el, {
strokeColor: value.currentItemStrokeColor,
})
: el;
},
(el) =>
hasStrokeColor(el.type)
? newElementWith(
el,
getColorUpdate(el, "strokeColor", color, elementsMap),
)
: el,
true,
),
}),
elementsMap,
),
appState: {
...appState,
...value,
...appStateUpdates,
...getColorTargetAppStateUpdates(target, color),
},
captureUpdate: !!value?.currentItemStrokeColor
? CaptureUpdateAction.IMMEDIATELY
: CaptureUpdateAction.EVENTUALLY,
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => {
PanelComponent: ({ elements, appState, updateData, app }) => {
const { stylesPanelMode } = getStylesPanelInfo(app);
const target = resolveColorTarget(appState, elements, "strokeColor");
// a note has no stroke: its "stroke" is the ink of its text and footer
const label =
target.kind === "sticky" ? t("labels.textColor") : t("labels.stroke");
return (
<>
{stylesPanelMode === "full" && (
<h3 aria-hidden="true">{t("labels.stroke")}</h3>
)}
{stylesPanelMode === "full" && <h3 aria-hidden="true">{label}</h3>}
<ColorPicker
topPicks={DEFAULT_ELEMENT_STROKE_PICKS}
palette={DEFAULT_ELEMENT_STROKE_COLOR_PALETTE}
topPicks={target.topPicks}
palette={target.palette}
customizableTopPicks={target.customizableTopPicks}
excludedColors={target.excludedColors}
type="elementStroke"
label={t("labels.stroke")}
label={label}
color={getFormValue(
elements,
app,
(element) => element.strokeColor,
true,
(hasSelection) =>
!hasSelection ? appState.currentItemStrokeColor : null,
(hasSelection) => (!hasSelection ? target.currentValue : null),
)}
onChange={(color) => updateData({ currentItemStrokeColor: color })}
onChange={(color) => updateData({ color })}
elements={elements}
appState={appState}
updateData={updateData}
@@ -403,27 +435,29 @@ export const actionChangeStrokeColor = register<
});
export const actionChangeBackgroundColor = register<
Pick<AppState, "currentItemBackgroundColor" | "viewBackgroundColor">
Partial<AppState> & { color?: string }
>({
name: "changeBackgroundColor",
label: "labels.changeBackground",
trackEvent: false,
perform: (elements, appState, value, app) => {
if (!value?.currentItemBackgroundColor) {
const { color, ...appStateUpdates } = value ?? {};
if (color === undefined) {
return {
appState: {
...appState,
...value,
},
appState: { ...appState, ...appStateUpdates },
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
}
const target = resolveColorTarget(appState, elements, "backgroundColor");
const elementsMap = arrayToMap(elements);
let nextElements;
const selectedElements = app.scene.getSelectedElements(appState);
const shouldEnablePolygon =
!isTransparent(value.currentItemBackgroundColor) &&
!isTransparent(color) &&
// `every` is vacuously true with nothing selected (editing text)
selectedElements.length > 0 &&
selectedElements.every(
(el) => isLineElement(el) && canBecomePolygon(el.points),
);
@@ -433,7 +467,7 @@ export const actionChangeBackgroundColor = register<
nextElements = elements.map((el) => {
if (selectedElementsMap.has(el.id) && isLineElement(el)) {
return newElementWith(el, {
backgroundColor: value.currentItemBackgroundColor,
backgroundColor: color,
...toggleLinePolygonState(el, true),
});
}
@@ -441,23 +475,49 @@ export const actionChangeBackgroundColor = register<
});
} else {
nextElements = changeProperty(elements, appState, (el) =>
newElementWith(el, {
backgroundColor: value.currentItemBackgroundColor,
}),
// a note's label passes the pick on to the note (below)
getColorTargetElement(el, "backgroundColor", elementsMap) === el
? newElementWith(
el,
getColorUpdate(el, "backgroundColor", color, elementsMap),
)
: el,
);
// editing a note's label (no selection): the label has no fill, the
// pick colors the note — text and background in one editing pass
const editingText =
appState.editingTextElement &&
elementsMap.get(appState.editingTextElement.id);
const editingTarget =
editingText &&
getColorTargetElement(editingText, "backgroundColor", elementsMap);
if (editingTarget && editingTarget !== editingText) {
nextElements = nextElements.map((el) =>
el.id === editingTarget.id
? newElementWith(
el,
getColorUpdate(el, "backgroundColor", color, elementsMap),
)
: el,
);
}
}
return {
elements: nextElements,
appState: {
...appState,
...value,
...appStateUpdates,
...getColorTargetAppStateUpdates(target, color),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => {
PanelComponent: ({ elements, appState, updateData, app }) => {
const { stylesPanelMode } = getStylesPanelInfo(app);
const target = resolveColorTarget(appState, elements, "backgroundColor");
// while editing a note's label the picker shows and sets the note's fill
const elementsMap = app.scene.getNonDeletedElementsMap();
return (
<>
@@ -465,21 +525,22 @@ export const actionChangeBackgroundColor = register<
<h3 aria-hidden="true">{t("labels.background")}</h3>
)}
<ColorPicker
topPicks={DEFAULT_ELEMENT_BACKGROUND_PICKS}
palette={DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE}
topPicks={target.topPicks}
palette={target.palette}
customizableTopPicks={target.customizableTopPicks}
excludedColors={target.excludedColors}
type="elementBackground"
label={t("labels.background")}
color={getFormValue(
elements,
app,
(element) => element.backgroundColor,
(element) =>
getColorTargetElement(element, "backgroundColor", elementsMap)
.backgroundColor,
true,
(hasSelection) =>
!hasSelection ? appState.currentItemBackgroundColor : null,
(hasSelection) => (!hasSelection ? target.currentValue : null),
)}
onChange={(color) =>
updateData({ currentItemBackgroundColor: color })
}
onChange={(color) => updateData({ color })}
elements={elements}
appState={appState}
updateData={updateData}
@@ -521,9 +582,13 @@ export const actionChangeBucketFillBackgroundColor = register<
// hidden rather than removed from the palette so the remaining
// colors keep their usual hotkeys (w for white etc.)
excludedColors={[COLOR_PALETTE.transparent]}
// customized independently of the background picker's picks even
// though both drive `currentItemBackgroundColor` — the bucket
// strip's defaults and use case differ (no transparent)
customizableTopPicks="bucketFill"
type="elementBackground"
label={t("labels.background")}
color={getBucketFillBackgroundColor(
color={app.bucketFill.getBucketFillBackgroundColor(
appState.currentItemBackgroundColor,
)}
onChange={(color) =>
@@ -552,9 +617,7 @@ export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({
);
return {
elements: changeProperty(elements, appState, (el) =>
newElementWith(el, {
fillStyle: value,
}),
hasFillStyle(el.type) ? newElementWith(el, { fillStyle: value }) : el,
),
appState: { ...appState, currentItemFillStyle: value },
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
@@ -562,9 +625,12 @@ export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({
},
PanelComponent: ({ elements, appState, updateData, app }) => {
const selectedElements = getSelectedElements(elements, appState);
const selectedFillStyleElements = selectedElements.filter((element) =>
hasFillStyle(element.type),
);
const allElementsZigZag =
selectedElements.length > 0 &&
selectedElements.every((el) => el.fillStyle === "zigzag");
selectedFillStyleElements.length > 0 &&
selectedFillStyleElements.every((el) => el.fillStyle === "zigzag");
return (
<fieldset>
@@ -599,7 +665,7 @@ export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({
elements,
app,
(element) => element.fillStyle,
(element) => element.hasOwnProperty("fillStyle"),
(element) => hasFillStyle(element.type),
(hasSelection) =>
hasSelection ? null : appState.currentItemFillStyle,
)}
@@ -607,7 +673,9 @@ export const actionChangeFillStyle = register<ExcalidrawElement["fillStyle"]>({
const nextValue =
event.altKey &&
value === "hachure" &&
selectedElements.every((el) => el.fillStyle === "hachure")
selectedFillStyleElements.every(
(el) => el.fillStyle === "hachure",
)
? "zigzag"
: value;
@@ -984,15 +1052,16 @@ export const actionChangeFontSize = register<ExcalidrawTextElement["fontSize"]>(
elements,
app,
(element) => {
const elementsMap = app.scene.getNonDeletedElementsMap();
if (isTextElement(element)) {
return element.fontSize;
return getBaseFontSize(element, elementsMap);
}
const boundTextElement = getBoundTextElement(
element,
app.scene.getNonDeletedElementsMap(),
elementsMap,
);
if (boundTextElement) {
return boundTextElement.fontSize;
return getBaseFontSize(boundTextElement, elementsMap);
}
return null;
},
@@ -1033,7 +1102,8 @@ export const actionDecreaseFontSize = register({
Math.round(
// get previous value before relative increase (doesn't work fully
// due to rounding and float precision issues)
(1 / (1 + FONT_SIZE_RELATIVE_INCREASE_STEP)) * element.fontSize,
(1 / (1 + FONT_SIZE_RELATIVE_INCREASE_STEP)) *
getBaseFontSize(element, app.scene.getNonDeletedElementsMap()),
),
);
},
@@ -1054,7 +1124,10 @@ export const actionIncreaseFontSize = register({
trackEvent: false,
perform: (elements, appState, value, app) => {
return changeFontSize(elements, appState, app, (element) =>
Math.round(element.fontSize * (1 + FONT_SIZE_RELATIVE_INCREASE_STEP)),
Math.round(
getBaseFontSize(element, app.scene.getNonDeletedElementsMap()) *
(1 + FONT_SIZE_RELATIVE_INCREASE_STEP),
),
);
},
keyTest: (event) => {
@@ -1070,7 +1143,10 @@ export const actionIncreaseFontSize = register({
type ChangeFontFamilyData = Partial<
Pick<
AppState,
"openPopup" | "currentItemFontFamily" | "currentHoveredFontFamily"
| "openPopup"
| "currentItemFontFamily"
| "currentHoveredFontFamily"
| "fontTopPicks"
>
> & {
/** cache of selected & editing elements populated on opened popup */
@@ -1246,8 +1322,9 @@ export const actionChangeFontFamily = register<{
fontFamily: nextFontFamily,
})}`;
const chars = Array.from(uniqueChars.values()).join();
const ownerDocument = app.props.ownerDocument ?? document;
if (skipFontFaceCheck || window.document.fonts.check(fontString, chars)) {
if (skipFontFaceCheck || ownerDocument.fonts.check(fontString, chars)) {
// we either skip the check (have at least one font face loaded) or do the check and find out all the font faces have loaded
for (const [element, container] of elementContainerMapping) {
// trigger synchronous redraw
@@ -1255,7 +1332,7 @@ export const actionChangeFontFamily = register<{
}
} else {
// otherwise try to load all font faces for the given chars and redraw elements once our font faces loaded
window.document.fonts.load(fontString, chars).then((fontFaces) => {
ownerDocument.fonts.load(fontString, chars).then((fontFaces) => {
for (const [element, container] of elementContainerMapping) {
// use latest element state to ensure we don't have closure over an old instance in order to avoid possible race conditions (i.e. font faces load out-of-order while rapidly switching fonts)
const latestElement = app.scene.getElement(element.id);
@@ -1367,7 +1444,9 @@ export const actionChangeFontFamily = register<{
isOpened={appState.openPopup === "fontFamily"}
selectedFontFamily={selectedFontFamily}
hoveredFontFamily={appState.currentHoveredFontFamily}
topPicks={appState.fontTopPicks}
compactMode={stylesPanelMode !== "full"}
onTopPicksChange={(fontTopPicks) => updateData({ fontTopPicks })}
onSelect={(fontFamily) => {
withCaretPositionPreservation(
() => {
@@ -1455,7 +1534,7 @@ export const actionChangeFontFamily = register<{
// Refocus text editor when font picker closes if we were editing text
if (isCompact && appState.editingTextElement) {
restoreCaretPosition(null); // Just refocus without saved position
restoreCaretPosition(null, app.ownerDocument); // Just refocus without saved position
}
}
}}
@@ -1677,7 +1756,7 @@ export const actionChangeRoundness = register<"sharp" | "round">({
return el;
}
return newElementWith(el, {
const nextElement = newElementWith(el, {
roundness:
value === "round"
? {
@@ -1687,6 +1766,8 @@ export const actionChangeRoundness = register<"sharp" | "round">({
}
: null,
});
return nextElement;
}),
appState: {
...appState,
@@ -2071,6 +2152,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
startElement,
"start",
elementsMap,
appState.zoom,
appState.isBindingEnabled,
),
}
@@ -2085,6 +2167,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
endElement,
"end",
elementsMap,
appState.zoom,
appState.isBindingEnabled,
),
}
@@ -2117,6 +2200,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
appState.bindMode === "inside" ? "inside" : "orbit",
"start",
app.scene,
appState.zoom,
);
}
}
@@ -2131,6 +2215,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
appState.bindMode === "inside" ? "inside" : "orbit",
"end",
app.scene,
appState.zoom,
);
}
}
@@ -4,8 +4,6 @@ import { isLinearElement, isTextElement } from "@excalidraw/element";
import { arrayToMap, KEYS } from "@excalidraw/common";
import { selectGroupsForSelectedElements } from "@excalidraw/element";
import { CaptureUpdateAction } from "@excalidraw/element";
import type {
@@ -14,6 +12,8 @@ import type {
NonDeleted,
} from "@excalidraw/element/types";
import { selectGroupsForSelectedElements } from "../components/App.selection";
import { selectAllIcon } from "../components/icons";
import { register } from "./register";
+132 -73
View File
@@ -5,18 +5,28 @@ import {
CODES,
KEYS,
getLineHeight,
arrayToMap,
} from "@excalidraw/common";
import { newElementWith } from "@excalidraw/element";
import { newElementWith, syncStickyNoteInk } from "@excalidraw/element";
import {
normalizeStickyNote,
hasBoundTextElement,
canApplyRoundnessTypeToElement,
getDefaultRoundnessTypeForElement,
isFrameLikeElement,
isArrowElement,
isExcalidrawElement,
getColorUpdate,
isNonDeletedElement,
isStickyNoteBoundText,
isStickyNoteElement,
isTextElement,
getBaseFontSize,
getBaseFontSizeUpdate,
relayoutStickyNotes,
updateBoundElements,
} from "@excalidraw/element";
import {
@@ -86,84 +96,133 @@ export const actionPasteStyles = register({
includeBoundTextElement: true,
});
const selectedElementIds = selectedElements.map((element) => element.id);
return {
elements: elements.map((element) => {
if (selectedElementIds.includes(element.id)) {
let elementStylesToCopyFrom = pastedElement;
if (isTextElement(element) && element.containerId) {
elementStylesToCopyFrom = boundTextElement;
}
if (!elementStylesToCopyFrom) {
return element;
}
let newElement = newElementWith(element, {
backgroundColor: elementStylesToCopyFrom?.backgroundColor,
strokeWidth: elementStylesToCopyFrom?.strokeWidth,
strokeColor: elementStylesToCopyFrom?.strokeColor,
strokeStyle: elementStylesToCopyFrom?.strokeStyle,
fillStyle: elementStylesToCopyFrom?.fillStyle,
opacity: elementStylesToCopyFrom?.opacity,
roughness: elementStylesToCopyFrom?.roughness,
roundness: elementStylesToCopyFrom.roundness
? canApplyRoundnessTypeToElement(
elementStylesToCopyFrom.roundness.type,
element,
)
? elementStylesToCopyFrom.roundness
: getDefaultRoundnessTypeForElement(element)
: null,
});
if (isTextElement(newElement)) {
const fontSize =
(elementStylesToCopyFrom as ExcalidrawTextElement).fontSize ||
DEFAULT_FONT_SIZE;
const fontFamily =
(elementStylesToCopyFrom as ExcalidrawTextElement).fontFamily ||
DEFAULT_FONT_FAMILY;
const newTextElement = newElementWith(newElement, {
fontSize,
fontFamily,
textAlign:
(elementStylesToCopyFrom as ExcalidrawTextElement).textAlign ||
DEFAULT_TEXT_ALIGN,
lineHeight:
(elementStylesToCopyFrom as ExcalidrawTextElement).lineHeight ||
getLineHeight(fontFamily),
const elementsMap = arrayToMap(elements);
// whether the copied text was a sticky label is decided by the copied
// snapshot — its container may be gone from the live scene by now
const copiedElementsMap = arrayToMap(
(elementsCopied as unknown[]).filter(isExcalidrawElement),
);
const nextElements = relayoutStickyNotes(
// a restyled note and its label end up with one ink — the label's,
// when the copied styles carry two colors
syncStickyNoteInk(
elements.map((element) => {
if (selectedElementIds.includes(element.id)) {
let elementStylesToCopyFrom = pastedElement;
if (isTextElement(element) && element.containerId) {
elementStylesToCopyFrom = boundTextElement;
}
if (!elementStylesToCopyFrom) {
return element;
}
let newElement = newElementWith(element, {
backgroundColor: elementStylesToCopyFrom?.backgroundColor,
strokeWidth: elementStylesToCopyFrom?.strokeWidth,
strokeColor: elementStylesToCopyFrom?.strokeColor,
strokeStyle: elementStylesToCopyFrom?.strokeStyle,
fillStyle: elementStylesToCopyFrom?.fillStyle,
opacity: elementStylesToCopyFrom?.opacity,
roughness: elementStylesToCopyFrom?.roughness,
roundness: elementStylesToCopyFrom.roundness
? canApplyRoundnessTypeToElement(
elementStylesToCopyFrom.roundness.type,
element,
)
? elementStylesToCopyFrom.roundness
: getDefaultRoundnessTypeForElement(element)
: null,
});
newElement = newTextElement;
let container = null;
if (newTextElement.containerId) {
container =
selectedElements.find(
(element) => element.id === newTextElement.containerId,
) || null;
if (isTextElement(newElement)) {
const sourceText =
elementStylesToCopyFrom as ExcalidrawTextElement;
const fontSize =
(isTextElement(elementStylesToCopyFrom)
? getBaseFontSize(elementStylesToCopyFrom, copiedElementsMap)
: sourceText.fontSize) || DEFAULT_FONT_SIZE;
const fontFamily = sourceText.fontFamily || DEFAULT_FONT_FAMILY;
let container = null;
const containerId = newElement.containerId;
if (containerId) {
container =
selectedElements.find(
(element) => element.id === containerId,
) || null;
}
const newTextElement = newElementWith(newElement, {
...getBaseFontSizeUpdate(newElement, fontSize, elementsMap),
fontFamily,
textAlign: sourceText.textAlign || DEFAULT_TEXT_ALIGN,
lineHeight: sourceText.lineHeight || getLineHeight(fontFamily),
});
newElement = newTextElement;
if (isStickyNoteBoundText(newTextElement, elementsMap)) {
// the copied stroke may be transparent; a note's label never is
newElement = newElementWith(
newTextElement,
getColorUpdate(
newTextElement,
"strokeColor",
newTextElement.strokeColor,
elementsMap,
),
);
} else {
// sticky labels are laid out together with their (possibly
// also restyled) note in the post-pass below
redrawTextBoundingBox(newTextElement, container, app.scene);
}
}
redrawTextBoundingBox(newTextElement, container, app.scene);
}
if (
newElement.type === "arrow" &&
isArrowElement(elementStylesToCopyFrom)
) {
newElement = newElementWith(newElement, {
startArrowhead: elementStylesToCopyFrom.startArrowhead,
endArrowhead: elementStylesToCopyFrom.endArrowhead,
});
}
if (
newElement.type === "arrow" &&
isArrowElement(elementStylesToCopyFrom)
) {
newElement = newElementWith(newElement, {
startArrowhead: elementStylesToCopyFrom.startArrowhead,
endArrowhead: elementStylesToCopyFrom.endArrowhead,
});
}
if (isFrameLikeElement(element)) {
newElement = newElementWith(newElement, {
roundness: null,
backgroundColor: "transparent",
});
}
if (isFrameLikeElement(element)) {
newElement = newElementWith(newElement, {
roundness: null,
backgroundColor: "transparent",
});
}
if (isStickyNoteElement(newElement)) {
newElement = normalizeStickyNote(newElement);
}
return newElement;
}
return element;
}),
return newElement;
}
return element;
}),
elementsMap,
),
new Set(selectedElementIds),
{ prevElementsMap: elementsMap },
);
// a restyled note may have grown or shrunk — arrows bound to it follow
for (const element of nextElements) {
const prev = elementsMap.get(element.id);
if (
isStickyNoteElement(element) &&
isNonDeletedElement(element) &&
prev &&
(prev.height !== element.height ||
prev.x !== element.x ||
prev.y !== element.y)
) {
updateBoundElements(element, app.scene);
}
}
return {
elements: nextElements,
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
@@ -0,0 +1,28 @@
import { CaptureUpdateAction } from "@excalidraw/element";
import { messageCircleIcon } from "../components/icons";
import { register } from "./register";
export const actionToggleShowHints = register({
name: "showHints",
label: "labels.showHints",
icon: messageCircleIcon,
keywords: ["hint", "hints", "tip", "tips"],
// hints live in the toolbar, which view mode hides entirely
viewMode: false,
trackEvent: {
category: "canvas",
predicate: (appState) => !appState.showHints,
},
perform(elements, appState) {
return {
appState: {
...appState,
showHints: !this.checked!(appState),
},
captureUpdate: CaptureUpdateAction.NEVER,
};
},
checked: (appState) => appState.showHints,
});
@@ -0,0 +1,18 @@
import { KEYS, matchKey } from "@excalidraw/common";
import { register } from "./register";
export const actionToggleWrap = register({
name: "toggleWrap",
label: "labels.toggleWrap",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) =>
app.scene.getSelectedElements(appState).length > 0,
perform: (elements, appState, _, app) => app.wrap.toggle(elements, appState),
keyTest: (event, appState, elements, app) =>
!event[KEYS.CTRL_OR_CMD] &&
!event.altKey &&
!event.shiftKey &&
matchKey(event, KEYS.W) &&
app.scene.getSelectedElements(appState).length > 0,
});
+192
View File
@@ -0,0 +1,192 @@
import {
COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_PICKS,
DEFAULT_ELEMENT_STROKE_COLOR_PALETTE,
DEFAULT_ELEMENT_STROKE_PICKS,
STICKY_NOTE_BACKGROUND_PICKS,
STICKY_NOTE_STROKE_PICKS,
arrayToMap,
} from "@excalidraw/common";
import {
getColorTargetElement,
hasBackground,
hasStrokeColor,
isStickyNoteBoundText,
isStickyNoteElement,
isTextElement,
normalizeStickyNoteBackgroundColor,
normalizeStickyNoteStrokeColor,
} from "@excalidraw/element";
import type { ColorPaletteCustom, ColorTuple } from "@excalidraw/common";
import type { ElementsMap, ExcalidrawElement } from "@excalidraw/element/types";
import { getSelectedElements } from "../scene";
import type { AppState } from "../types";
export type ColorProperty = "strokeColor" | "backgroundColor";
/**
* Sticky notes are their own color domain: own defaults, own top picks, no
* transparent. A pick targets the regular domain, the sticky domain, or both
* ("mixed" selections write both defaults and use the regular picker).
*/
export type ColorTargetKind = "regular" | "sticky" | "mixed";
export type ColorDefaultKey =
| "currentItemStrokeColor"
| "currentItemBackgroundColor"
| "currentItemStickynoteStrokeColor"
| "currentItemStickynoteBackgroundColor";
export type ColorTargetAppState = Pick<
AppState,
"selectedElementIds" | "editingTextElement" | "activeTool" | ColorDefaultKey
>;
export type ColorTarget = {
kind: ColorTargetKind;
property: ColorProperty;
/** the current-item defaults a pick is written to (normalized per domain) */
appStateKeys: readonly ColorDefaultKey[];
/** the default shown when no element is targeted */
currentValue: string;
palette: ColorPaletteCustom;
topPicks: ColorTuple;
customizableTopPicks: keyof AppState["colorTopPicks"];
excludedColors: readonly string[] | undefined;
};
const DEFAULT_KEYS: Record<
ColorProperty,
Record<"regular" | "sticky", ColorDefaultKey>
> = {
strokeColor: {
regular: "currentItemStrokeColor",
sticky: "currentItemStickynoteStrokeColor",
},
backgroundColor: {
regular: "currentItemBackgroundColor",
sticky: "currentItemStickynoteBackgroundColor",
},
};
// transparent is hidden rather than removed from the palette so the remaining
// colors keep their usual hotkeys (same mechanism as the bucket fill picker);
// a module constant so the memoized picker's identity comparison holds
const STICKY_NOTE_EXCLUDED_COLORS: readonly string[] = [
COLOR_PALETTE.transparent,
];
const isStickyNoteColorTarget = (
element: ExcalidrawElement,
elementsMap: ElementsMap,
) =>
isStickyNoteElement(element) ||
(isTextElement(element) && isStickyNoteBoundText(element, elementsMap));
/**
* Who a stroke/background pick targets. Resolve it from the state an action
* runs against, at execution time — never capture it in a render closure:
* the memoized picker keeps a stale `onChange`, and the always-visible top
* picks fire it without a re-render.
*
* Targets are the selected color-capable elements (for stroke incl. bound
* labels, since a note's visible text is its label) plus the text being
* edited (`handleTextWysiwyg` deselects while editing) — or, for a
* background pick on a note's label, the note (see `getColorTargetElement`).
* With no target, the active tool decides the domain.
*/
export const resolveColorTarget = (
appState: ColorTargetAppState,
elements: readonly ExcalidrawElement[],
property: ColorProperty,
): ColorTarget => {
const elementsMap = arrayToMap(elements);
const supports = (element: ExcalidrawElement) =>
property === "strokeColor"
? hasStrokeColor(element.type)
: hasBackground(element.type);
const targets: ExcalidrawElement[] = getSelectedElements(elements, appState, {
includeBoundTextElement: property === "strokeColor",
}).filter(supports);
const editingText =
appState.editingTextElement &&
elementsMap.get(appState.editingTextElement.id);
const editing =
editingText && getColorTargetElement(editingText, property, elementsMap);
if (
editing &&
!editing.isDeleted &&
supports(editing) &&
!targets.some((element) => element.id === editing.id)
) {
targets.push(editing);
}
let kind: ColorTargetKind;
if (!targets.length) {
kind = appState.activeTool.type === "stickynote" ? "sticky" : "regular";
} else {
const stickyCount = targets.filter((element) =>
isStickyNoteColorTarget(element, elementsMap),
).length;
kind =
stickyCount === 0
? "regular"
: stickyCount === targets.length
? "sticky"
: "mixed";
}
const keys = DEFAULT_KEYS[property];
const isStroke = property === "strokeColor";
return {
kind,
property,
appStateKeys: kind === "mixed" ? [keys.regular, keys.sticky] : [keys[kind]],
currentValue: appState[kind === "sticky" ? keys.sticky : keys.regular],
palette: isStroke
? DEFAULT_ELEMENT_STROKE_COLOR_PALETTE
: DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE,
topPicks:
kind === "sticky"
? isStroke
? STICKY_NOTE_STROKE_PICKS
: STICKY_NOTE_BACKGROUND_PICKS
: isStroke
? DEFAULT_ELEMENT_STROKE_PICKS
: DEFAULT_ELEMENT_BACKGROUND_PICKS,
customizableTopPicks:
kind === "sticky"
? isStroke
? "stickyNoteStroke"
: "stickyNoteBackground"
: isStroke
? "elementStroke"
: "elementBackground",
excludedColors: kind === "sticky" ? STICKY_NOTE_EXCLUDED_COLORS : undefined,
};
};
/** the current-item default updates for a picked color */
export const getColorTargetAppStateUpdates = (
target: ColorTarget,
color: string,
): Partial<AppState> => {
const updates: Partial<AppState> = {};
for (const key of target.appStateKeys) {
updates[key] =
key === "currentItemStickynoteStrokeColor"
? normalizeStickyNoteStrokeColor(color)
: key === "currentItemStickynoteBackgroundColor"
? normalizeStickyNoteBackgroundColor(color)
: color;
}
return updates;
};
+2
View File
@@ -82,9 +82,11 @@ export { actionToggleZenMode } from "./actionToggleZenMode";
export { actionToggleObjectsSnapMode } from "./actionToggleObjectsSnapMode";
export { actionToggleArrowBinding } from "./actionToggleArrowBinding";
export { actionToggleMidpointSnapping } from "./actionToggleMidpointSnapping";
export { actionToggleShowHints } from "./actionToggleShowHints";
export { actionToggleStats } from "./actionToggleStats";
export { actionUnbindText, actionBindText } from "./actionBoundText";
export { actionToggleWrap } from "./actionToggleWrap";
export { actionLink } from "./actionLink";
export { actionToggleElementLock } from "./actionElementLock";
export { actionToggleLinearEditor } from "./actionLinearEditor";
+10 -3
View File
@@ -192,14 +192,21 @@ export class ActionManager {
const action = this.actions[name];
const PanelComponent = action.PanelComponent!;
PanelComponent.displayName = "PanelComponent";
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
const updateData = (formState?: any) => {
if (this.isActionBlockedByViewportTransition(action)) {
return;
}
trackAction(action, "ui", appState, elements, this.app, formState);
// read fresh state at call time — memoized panel children may invoke
// an `updateData` closure minted by an earlier render
trackAction(
action,
"ui",
this.getAppState(),
this.getElementsIncludingDeleted(),
this.app,
formState,
);
this.updater(
action.perform(
+2
View File
@@ -48,6 +48,7 @@ export type ShortcutName =
| "saveToActiveFile"
| "toggleShortcuts"
| "wrapSelectionInFrame"
| "toggleWrap"
>
| "saveScene"
| "imageExport"
@@ -112,6 +113,7 @@ const shortcutMap: Record<ShortcutName, string[]> = {
toggleShortcuts: [getShortcutKey("?")],
searchMenu: [getShortcutKey("CtrlOrCmd+F")],
wrapSelectionInFrame: [],
toggleWrap: [getShortcutKey("W")],
toolLock: [getShortcutKey("Q")],
};
+2
View File
@@ -61,6 +61,7 @@ export type ActionName =
| "objectsSnapMode"
| "arrowBinding"
| "midpointSnapping"
| "showHints"
| "stats"
| "changeStrokeColor"
| "changeBackgroundColor"
@@ -140,6 +141,7 @@ export type ActionName =
| "linkToElement"
| "cropEditor"
| "wrapSelectionInFrame"
| "toggleWrap"
| "toggleShapeSwitch"
| "togglePolygon";
+5 -1
View File
@@ -3,7 +3,11 @@
import { isDevEnv } from "@excalidraw/common";
// small subset of categories at a given time.
const ALLOWED_CATEGORIES_TO_TRACK = new Set(["command_palette", "export"]);
const ALLOWED_CATEGORIES_TO_TRACK = new Set([
"command_palette",
"export",
"ai",
]);
export const trackEvent = (
category: string,
+44 -3
View File
@@ -12,9 +12,10 @@ import {
THEME,
DEFAULT_GRID_STEP,
isTestEnv,
DEFAULT_STICKY_NOTE_BG,
} from "@excalidraw/common";
import type { AppState, NormalizedZoomValue } from "./types";
import type { AppState, InputDevice, NormalizedZoomValue } from "./types";
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
? devicePixelRatio
@@ -38,6 +39,8 @@ export const getDefaultAppState = (): Omit<
currentItemStrokeVariability: "constant",
currentItemStartArrowhead: null,
currentItemStrokeColor: DEFAULT_ELEMENT_PROPS.strokeColor,
currentItemStickynoteStrokeColor: DEFAULT_ELEMENT_PROPS.strokeColor,
currentItemStickynoteBackgroundColor: DEFAULT_STICKY_NOTE_BG,
currentItemRoundness: isTestEnv() ? "sharp" : "round",
currentItemArrowType: ARROW_TYPE.round,
currentItemStrokeStyle: DEFAULT_ELEMENT_PROPS.strokeStyle,
@@ -74,6 +77,8 @@ export const getDefaultAppState = (): Omit<
isBindingEnabled: true,
bindingPreference: "enabled",
isMidpointSnappingEnabled: true,
showHints: true,
inputDevice: "auto",
defaultSidebarDockedPreference: false,
isLoading: false,
isResizing: false,
@@ -103,7 +108,7 @@ export const getDefaultAppState = (): Omit<
panels: STATS_PANELS.generalStats | STATS_PANELS.elementProperties,
},
suggestedBinding: null,
hoveredArrowTextAnchor: null,
textToolHover: null,
frameRendering: { enabled: true, clip: true, name: true, outline: true },
frameToHighlight: null,
editingFrame: null,
@@ -130,6 +135,14 @@ export const getDefaultAppState = (): Omit<
activeLockedId: null,
bindMode: "orbit",
boxSelectionMode: "contain",
colorTopPicks: {
elementStroke: null,
elementBackground: null,
bucketFill: null,
stickyNoteStroke: null,
stickyNoteBackground: null,
},
fontTopPicks: null,
};
};
@@ -176,6 +189,16 @@ const APP_STATE_STORAGE_CONF = (<
},
currentItemStartArrowhead: { browser: true, export: false, server: false },
currentItemStrokeColor: { browser: true, export: false, server: false },
currentItemStickynoteStrokeColor: {
browser: true,
export: false,
server: false,
},
currentItemStickynoteBackgroundColor: {
browser: true,
export: false,
server: false,
},
currentItemStrokeStyle: { browser: true, export: false, server: false },
currentItemStrokeWidthKey: { browser: true, export: false, server: false },
currentItemTextAlign: { browser: true, export: false, server: false },
@@ -203,6 +226,8 @@ const APP_STATE_STORAGE_CONF = (<
boxSelectionMode: { browser: true, export: false, server: false },
bindingPreference: { browser: true, export: false, server: false },
isMidpointSnappingEnabled: { browser: true, export: false, server: false },
showHints: { browser: true, export: false, server: false },
inputDevice: { browser: true, export: false, server: false },
defaultSidebarDockedPreference: {
browser: true,
export: false,
@@ -239,7 +264,7 @@ const APP_STATE_STORAGE_CONF = (<
shouldCacheIgnoreZoom: { browser: true, export: false, server: false },
stats: { browser: true, export: false, server: false },
suggestedBinding: { browser: false, export: false, server: false },
hoveredArrowTextAnchor: { browser: false, export: false, server: false },
textToolHover: { browser: false, export: false, server: false },
frameRendering: { browser: false, export: false, server: false },
frameToHighlight: { browser: false, export: false, server: false },
editingFrame: { browser: false, export: false, server: false },
@@ -261,6 +286,8 @@ const APP_STATE_STORAGE_CONF = (<
lockedMultiSelections: { browser: true, export: true, server: true },
activeLockedId: { browser: false, export: false, server: false },
bindMode: { browser: true, export: false, server: false },
colorTopPicks: { browser: true, export: false, server: false },
fontTopPicks: { browser: true, export: false, server: false },
});
const _clearAppStateForStorage = <
@@ -312,3 +339,17 @@ export const isHandToolActive = ({
}) => {
return activeTool.type === "hand";
};
/**
* The device the wheel mappings follow for the given preference.
*
* `auto` is meant to detect the device from the wheel events themselves
* (line vs. pixel delta modes, whole vs. fractional deltas, one vs. two axes
* moving, event cadence and momentum tails). That is not implemented yet, so
* it resolves to `trackpad` — the mapping the editor has always had, and the
* default to keep until detection exists.
*/
export const resolveInputDevice = (
inputDevice: InputDevice,
): Exclude<InputDevice, "auto"> =>
inputDevice === "auto" ? "trackpad" : inputDevice;
+1 -4
View File
@@ -2,7 +2,6 @@ import {
COLOR_CHARCOAL_BLACK,
COLOR_VOICE_CALL,
COLOR_WHITE,
THEME,
UserIdleState,
} from "@excalidraw/common";
@@ -122,9 +121,7 @@ export const renderRemoteCursors = ({
context.closePath();
}
// TODO remove the dark theme color after we stop inverting canvas colors
const IS_SPEAKING_COLOR =
appState.theme === THEME.DARK ? "#2f6330" : COLOR_VOICE_CALL;
const IS_SPEAKING_COLOR = COLOR_VOICE_CALL;
const isSpeaking = collaborator?.isSpeaking;
+33 -2
View File
@@ -1,6 +1,6 @@
.zoom-actions,
.undo-redo-buttons {
background-color: var(--island-bg-color);
background-color: var(--color-surface-low);
border-radius: var(--border-radius-lg);
box-shadow: 0 0 0 1px var(--color-surface-lowest);
}
@@ -8,7 +8,6 @@
.zoom-button,
.undo-redo-buttons button {
border-radius: 0 !important;
background-color: var(--color-surface-low) !important;
font-size: 0.875rem !important;
width: var(--lg-button-size);
height: var(--lg-button-size);
@@ -31,6 +30,24 @@
width: 3.75rem !important;
justify-content: center;
color: var(--text-primary-color);
// unlike the other zoom buttons, has no .ToolIcon__icon to show the hover
.zoom-actions &:hover:not(:active) {
background-color: var(--button-hover-bg);
}
}
// shifted left in zen mode (the wrapper rather than the button, so that the
// tooltip, positioned off the wrapper, moves along)
.reset-zoom-button-wrapper {
transition: transform var(--zen-mode-transition-duration) ease-in-out;
}
// faded out in zen mode
.zoom-out-button-wrapper,
.zoom-in-button-wrapper {
transition: opacity var(--zen-mode-transition-duration) ease-in-out,
visibility var(--zen-mode-transition-duration);
}
.zoom-out-button {
@@ -92,6 +109,20 @@
}
}
// two separate rows (rather than a flex-wrap row break) so the panel's
// intrinsic width is that of a single row
.align-buttons {
display: flex;
flex-direction: column;
gap: 0.5rem;
&__row {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
}
.compact-shape-actions {
display: flex;
flex-direction: column;
+27 -28
View File
@@ -94,31 +94,24 @@ const AlignFieldset = ({
return (
<fieldset>
<legend>{t("labels.align")}</legend>
<div className="buttonList">
{isRTL ? (
<>
{renderAction("alignRight")}
{renderAction("alignHorizontallyCentered")}
{renderAction("alignLeft")}
</>
) : (
<>
{renderAction("alignLeft")}
{renderAction("alignHorizontallyCentered")}
{renderAction("alignRight")}
</>
)}
{showDistribute && renderAction("distributeHorizontally")}
{/* breaks the row ˇˇ */}
<div style={{ flexBasis: "100%", height: 0 }} />
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: ".5rem",
marginTop: "-0.5rem",
}}
>
<div className="buttonList align-buttons">
<div className="align-buttons__row">
{isRTL ? (
<>
{renderAction("alignRight")}
{renderAction("alignHorizontallyCentered")}
{renderAction("alignLeft")}
</>
) : (
<>
{renderAction("alignLeft")}
{renderAction("alignHorizontallyCentered")}
{renderAction("alignRight")}
</>
)}
{showDistribute && renderAction("distributeHorizontally")}
</div>
<div className="align-buttons__row">
{renderAction("alignTop")}
{renderAction("alignVerticallyCentered")}
{renderAction("alignBottom")}
@@ -420,7 +413,9 @@ const CombinedTextProperties = ({
predicates: ShapeActionPredicates;
container: HTMLDivElement | null;
}) => {
const { saveCaretPosition, restoreCaretPosition } = useTextEditorFocus();
const { saveCaretPosition, restoreCaretPosition } = useTextEditorFocus(
container?.ownerDocument,
);
const isOpen = appState.openPopup === "compactTextProperties";
return (
@@ -902,10 +897,14 @@ export const UndoRedoActions = ({
}) => (
<div className={`undo-redo-buttons ${className}`}>
<div className="undo-button-container">
<Tooltip label={t("buttons.undo")}>{renderAction("undo")}</Tooltip>
<Tooltip label={t("buttons.undo")} delay>
{renderAction("undo")}
</Tooltip>
</div>
<div className="redo-button-container">
<Tooltip label={t("buttons.redo")}> {renderAction("redo")}</Tooltip>
<Tooltip label={t("buttons.redo")} delay>
{renderAction("redo")}
</Tooltip>
</div>
</div>
);
+99 -102
View File
@@ -1,17 +1,20 @@
import { CURSOR_TYPE, DRAGGING_THRESHOLD } from "@excalidraw/common";
import {
bindBindingElementToFixedPoint,
dragNewTextElement,
getBoundTextElement,
getEndpointBoundTextDragAnchor,
getTextBindingForArrowEndpoint,
getUnboundArrowEndpointAtPoint,
hitElementBoundText,
isArrowElement,
isBindingEnabled,
isEndpointBoundText,
isTextElement,
LinearElementEditor,
} from "@excalidraw/element";
import { pointFrom } from "@excalidraw/math";
import { pointDistance, pointFrom } from "@excalidraw/math";
import type { ArrowEndpoint } from "@excalidraw/element";
import type {
@@ -19,64 +22,28 @@ import type {
ExcalidrawTextElement,
FixedPoint,
NonDeleted,
NonDeletedExcalidrawElement,
} from "@excalidraw/element/types";
import type App from "./App";
import type { AppState } from "../types";
import type { PointerDownState } from "../types";
/**
* The text tool's interaction with arrows: the hover affordance showing where
* a click would attach text to an arrow — a free endpoint (binds the arrow to
* a new text element positioned against that endpoint) or the arrow's midpoint
* (adds a label bound to the arrow) — and the endpoint-bound flavor of
* drag-sizing a new text.
* Text ↔ arrow interactions.
*
* The scene-level logic lives in `@excalidraw/element`'s `arrowEndpointText.ts`.
* With the text tool: the free endpoint a click would bind a new text to
* (`AppTextTool` resolves and shows it), the binding itself, and the
* endpoint-bound flavor of drag-sizing a new text.
*
* With the selection tool: dragging an arrow's existing label along the arrow
* — the grab affordance and the drag itself.
*
* The scene-level logic lives in `@excalidraw/element`'s
* `arrowEndpointText.ts` and `linearElementEditor.ts`.
*/
export class AppArrowText {
constructor(private app: App) {}
/**
* With the text tool active, an arrow under the cursor is a target for
* attaching text. Returns where the text would land (if anywhere), and keeps
* `appState.hoveredArrowTextAnchor` — which drives the highlight — in sync.
*/
updateHoveredAnchor = (scenePointer: {
x: number;
y: number;
}): AppState["hoveredArrowTextAnchor"] => {
const hovered =
this.app.state.activeTool.type === "text" &&
!this.app.state.editingTextElement &&
!this.app.state.newElement
? this.getAnchorAtPosition(scenePointer.x, scenePointer.y)
: null;
const previous = this.app.state.hoveredArrowTextAnchor;
if (
previous?.elementId !== hovered?.elementId ||
previous?.anchor !== hovered?.anchor
) {
this.app.setState({ hoveredArrowTextAnchor: hovered });
}
return hovered;
};
/**
* Re-evaluates the hovered anchor at the last known pointer position — for
* events that change what a click would do without the pointer moving,
* i.e. the ctrl/cmd binding toggle. (Events that invalidate the anchor
* wholesale — tool switches, finalize, deselect — clear it directly
* instead.)
*/
refresh = (): void => {
if (this.app.lastPointerMoveCoords) {
this.updateHoveredAnchor(this.app.lastPointerMoveCoords);
}
};
/**
* A free arrow endpoint a new text could be bound to. Binding an endpoint is
* an arrow binding, so it follows the binding toggle (ctrl/cmd) like every
@@ -98,17 +65,17 @@ export class AppArrowText {
return null;
}
// The text tool edits before it creates: when a text element is the
// top-most hit at this position, a click edits that text, so a nearby
// endpoint must not be offered over it.
if (this.app.getTextElementAtPosition(x, y)) {
return null;
}
// The endpoint scan only knows about arrows, so it happily reaches through
// whatever is drawn on top of them. An element stacked above the arrow that
// the pointer actually hits owns the click — the text tool should label
// that element rather than bind the endpoint hidden behind it.
// the pointer actually hits owns the click — the text tool should edit or
// label that element rather than bind the endpoint hidden behind it. This
// includes text: a text stacked above the arrow keeps its edit behavior.
//
// The preference is z-aware on purpose. When the arrow is the top-most hit
// (e.g. drawn over an existing text), its endpoint has full preference
// over the whole hit circle — a z-blind "any text under the cursor wins"
// rule would make the affordance flicker between the endpoint anchor and
// text editing wherever a text bbox edge cuts into the circle.
const hitElement = this.app.getElementAtPosition(x, y, {
includeLockedElements: true,
});
@@ -125,49 +92,6 @@ export class AppArrowText {
return endpoint;
}
/**
* Mirrors what `handleTextOnPointerDown` would do at this position, so the
* highlight can't promise something the click won't deliver.
*/
private getAnchorAtPosition(
x: number,
y: number,
): AppState["hoveredArrowTextAnchor"] {
const endpoint = this.getBindableEndpointAtPosition(x, y);
if (endpoint) {
return { elementId: endpoint.arrow.id, anchor: endpoint.startOrEnd };
}
const container = this.app.getTextBindableContainerAtPosition(x, y);
// Only arrows get a midpoint label anchor worth pointing at; other
// containers center the text in themselves, which needs no affordance.
// An arrow that already has a label is edited in place, not re-anchored.
if (
!isArrowElement(container) ||
getBoundTextElement(container, this.app.scene.getNonDeletedElementsMap())
) {
return null;
}
// `getTextBindableContainerAtPosition` resolves an arrow anywhere in its
// bounding box, but a click only becomes a *label* when it also snaps to
// the arrow's center — off-center clicks drop a free-floating text
// instead. Gate on the same check so the highlight can't promise a label
// the click won't deliver.
const snappedToCenter = this.app.getTextWysiwygSnappedToCenterPosition(
x,
y,
this.app.state,
container,
);
return snappedToCenter
? { elementId: container.id, anchor: "label" }
: null;
}
/**
* How a text should be created to read as a label for this endpoint — the
* side midpoint to bind, the alignment that pins it, and the scene position
@@ -234,4 +158,77 @@ export class AppArrowText {
return true;
}
/**
* Whether the arrow's label is what a grab at this position would pick up:
* the pointer is over the label, and no element stacked above the arrow
* owns the hit instead.
*/
isBoundTextGrabbable(
element: NonDeletedExcalidrawElement,
x: number,
y: number,
): boolean {
if (
!isArrowElement(element) ||
!hitElementBoundText(
pointFrom(x, y),
element,
this.app.scene.getNonDeletedElementsMap(),
)
) {
return false;
}
const hitElements = this.app.getElementsAtPosition(x, y);
const arrowIndex = hitElements.findIndex((el) => el.id === element.id);
return (
arrowIndex !== -1 &&
!hitElements
.slice(arrowIndex + 1)
.some((el) => this.app.hitElement(x, y, el, false))
);
}
/**
* The pointer-move half of dragging a label along its arrow. Owns the move
* whenever the gesture started on the label (`pointerDownState.hit.arrowLabel`),
* dragging only once past the threshold. Returns whether it owned it.
*/
maybeDragLabel(
linearElementEditor: LinearElementEditor,
pointerDownState: PointerDownState,
pointerCoords: { x: number; y: number },
): boolean {
if (!pointerDownState.hit.arrowLabel) {
return false;
}
this.app.cursor.set(CURSOR_TYPE.GRABBING);
if (
linearElementEditor.isDragging ||
pointDistance(
pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
pointFrom(pointerCoords.x, pointerCoords.y),
) >=
DRAGGING_THRESHOLD / this.app.state.zoom.value
) {
const updatedEditor = LinearElementEditor.handleBoundTextDragging(
linearElementEditor,
this.app.scene,
pointerCoords.x,
pointerCoords.y,
);
if (updatedEditor) {
pointerDownState.drag.hasOccurred = true;
this.app.setState({
selectedLinearElement: updatedEditor,
});
}
}
return true;
}
}
@@ -1,6 +1,11 @@
import {
getBucketFillBackgroundColor,
applyDarkModeFilter,
BUCKET_FILL_BACKGROUND_PICKS,
COLOR_PALETTE,
DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX,
getSizeFromPoints,
isTransparent,
THEME,
} from "@excalidraw/common";
import { pointFrom, type GlobalPoint, type LocalPoint } from "@excalidraw/math";
@@ -13,10 +18,17 @@ import {
ShapeCache,
} from "@excalidraw/element";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import type {
NonDeletedExcalidrawElement,
Theme,
} from "@excalidraw/element/types";
import { actionChangeBucketFillBackgroundColor } from "../actions";
import { editorJotaiStore } from "../editor-jotai";
import { t } from "../i18n";
import { activeEyeDropperAtom, type EyeDropperProperties } from "./EyeDropper";
import type App from "./App";
type ScenePoint = {
@@ -24,10 +36,16 @@ type ScenePoint = {
y: number;
};
const BUCKET_FILL_KEYBOARD_COLOR_PICKS = BUCKET_FILL_BACKGROUND_PICKS.filter(
(color) => color !== COLOR_PALETTE.white,
);
/** Owns bucket-fill interaction and App-bound scene mutations. */
export class AppBucketFill {
constructor(private app: App) {}
private temporaryEyeDropper: EyeDropperProperties | null = null;
/**
* The click armed on pointer down, committed on pointer up. Deferring the
* scene mutation to pointer up is what lets a pinch/pan second finger, a
@@ -59,12 +77,60 @@ export class AppBucketFill {
this.pending = null;
};
cycleBackgroundColor = () => {
const currentColor = this.getBucketFillBackgroundColor(
this.app.state.currentItemBackgroundColor,
);
const currentIndex = BUCKET_FILL_KEYBOARD_COLOR_PICKS.indexOf(currentColor);
const nextColor =
BUCKET_FILL_KEYBOARD_COLOR_PICKS[
(currentIndex + 1) % BUCKET_FILL_KEYBOARD_COLOR_PICKS.length
];
this.app.actionManager.executeAction(
actionChangeBucketFillBackgroundColor,
"keyboard",
{ currentItemBackgroundColor: nextColor },
);
};
openTemporaryEyeDropper = () => {
if (editorJotaiStore.get(activeEyeDropperAtom)) {
return;
}
const eyeDropper: EyeDropperProperties = {
colorPickerType: "elementBackground",
keepOpenOnAlt: true,
onSelect: (color) => {
this.app.actionManager.executeAction(
actionChangeBucketFillBackgroundColor,
"ui",
{ currentItemBackgroundColor: color },
);
},
};
this.temporaryEyeDropper = eyeDropper;
this.app.updateEditorAtom(activeEyeDropperAtom, eyeDropper);
};
closeTemporaryEyeDropper = () => {
const eyeDropper = this.temporaryEyeDropper;
this.temporaryEyeDropper = null;
if (
eyeDropper &&
editorJotaiStore.get(activeEyeDropperAtom) === eyeDropper
) {
this.app.updateEditorAtom(activeEyeDropperAtom, null);
}
};
/**
* Apply the current bucket fill settings to an existing fill-compatible
* element (no-op when nothing would change). One undoable step.
*/
private restyle = (element: NonDeletedExcalidrawElement) => {
const backgroundColor = getBucketFillBackgroundColor(
const backgroundColor = this.getBucketFillBackgroundColor(
this.app.state.currentItemBackgroundColor,
);
if (
@@ -89,7 +155,7 @@ export class AppBucketFill {
private fill = (scenePointer: ScenePoint) => {
// shared with the generic shape background, but a transparent fill would
// be invisible, so fall back to a real color (appState is not mutated)
const backgroundColor = getBucketFillBackgroundColor(
const backgroundColor = this.getBucketFillBackgroundColor(
this.app.state.currentItemBackgroundColor,
);
@@ -217,4 +283,19 @@ export class AppBucketFill {
// (even when the tool isn't locked).
this.app.scheduleCapture();
};
/**
* The color the bucket fill tool actually fills with: the shared
* `currentItemBackgroundColor`, falling back to green when that is
* transparent (the tool's picker doesn't offer transparent, but the shared
* state can hold it from the generic shape picker).
*/
public getBucketFillBackgroundColor = (
backgroundColor: string,
/** supply only for display purposes such as when applying to the cursor */
theme?: Theme,
) =>
isTransparent(backgroundColor)
? COLOR_PALETTE.green[DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX]
: applyDarkModeFilter(backgroundColor, theme === THEME.DARK);
}

Some files were not shown because too many files have changed in this diff Show More