Files
excalidraw/packages/element/tests/linearElementEditor.test.tsx
T
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

2027 lines
62 KiB
TypeScript

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