@weasel-js/core 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/dist/{DrawCommand-Dl0bXNfS.d.ts → DrawCommand-CJtqqt8H.d.ts} +26 -2
  3. package/dist/{chunk-7V6JEOXE.js → chunk-2J6V527H.js} +10033 -10912
  4. package/dist/chunk-2J6V527H.js.map +1 -0
  5. package/dist/chunk-SYM6RAM4.js +232 -0
  6. package/dist/chunk-SYM6RAM4.js.map +1 -0
  7. package/dist/clone.d.ts +1 -1
  8. package/dist/geometry-D9BDMiQi.d.ts +114 -0
  9. package/dist/{grid-Cf87knjU.d.ts → grid-CaSK9bHV.d.ts} +1 -1
  10. package/dist/index-DOYRTfP0.d.ts +2986 -0
  11. package/dist/index.css +0 -35
  12. package/dist/index.css.map +1 -1
  13. package/dist/index.d.ts +1174 -2481
  14. package/dist/index.js +2 -2
  15. package/dist/insert.d.ts +2 -2
  16. package/dist/move.d.ts +3 -3
  17. package/dist/{options-BPPBWMa7.d.ts → options-DMWeTELe.d.ts} +1 -1
  18. package/dist/{pointSnapToGrid-D7s7QmOF.d.ts → pointSnapToGrid-C3EruUwt.d.ts} +3 -54
  19. package/dist/renderer.css +0 -35
  20. package/dist/renderer.css.map +1 -1
  21. package/dist/renderer.d.ts +30 -5
  22. package/dist/renderer.js +2 -2
  23. package/dist/resize.d.ts +3 -3
  24. package/dist/routing.d.ts +10 -8
  25. package/dist/routing.js +1 -1
  26. package/dist/{types-BjUi2vA-.d.ts → types-Dcaa0tPq.d.ts} +1 -25
  27. package/dist/{registerFont-CP-wCsrz.d.ts → viewToMat3-D4lrBigW.d.ts} +2 -44
  28. package/package.json +6 -5
  29. package/dist/chunk-7V6JEOXE.js.map +0 -1
  30. package/dist/chunk-AM6ARSPN.js +0 -517
  31. package/dist/chunk-AM6ARSPN.js.map +0 -1
  32. package/dist/fitViewToBounds-evGsnR8Q.d.ts +0 -62
  33. package/dist/index-DZBYMsHI.d.ts +0 -1555
  34. package/dist/routing.css +0 -35
  35. package/dist/routing.css.map +0 -1
@@ -0,0 +1,2986 @@
1
+ import { N as NodeId, S as Scene, P as PoseComposition } from './types-Cpb4hii1.js';
2
+ import { M as ModifierState, A as ActionBehavior, c as ResizeAnchor, R as ResizePose, B as BoundsConstraint, P as PointSnapBehavior } from './types-Dcaa0tPq.js';
3
+ import { V as View } from './view-DSQgxBJB.js';
4
+ import { CapabilityTag } from '@weasel-js/modes';
5
+ import * as React from 'react';
6
+ import { MutableRefObject, ReactNode, ReactElement } from 'react';
7
+ import { IngestItem, GestureSpec, InputEvent, ParsedModifiers, GestureName, ChannelRef, DescribeRouteOptions, GESTURE_DESCRIPTORS, GestureArgSpec, GestureDescriptor, ModRequirement, ModifierKey, ParsedRoute, PhaseAtom, RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, ROUTE_FIELD_DEFINITIONS, ROUTE_TERMS, RouteDescriptionPart, RouteFieldName, RouteTermLabel, canonicalModifiers, collapseShiftPairs, describeRoute, describeRouteParts, formatPhaseAtom, formatRoute, getGestureDescriptor, isKnownGestureName, parseRoute } from '@weasel-js/gestures';
8
+ import { F as FillStyle, a as Stroke, D as DrawCommand } from './DrawCommand-CJtqqt8H.js';
9
+ import * as react_jsx_runtime from 'react/jsx-runtime';
10
+ import { P as Path } from './types-B6MMiodD.js';
11
+ import { Op, History } from '@weasel-js/history';
12
+ import { L as LayoutStrategy, I as InsertAdapter } from './types-B_-khFM0.js';
13
+ import { B as Bounds, P as PoseProjection } from './geometry-D9BDMiQi.js';
14
+ import { Mat3 } from '@weasel-js/geom';
15
+ import { D as DebugSink } from './types-BJ8_cyT7.js';
16
+
17
+ /**
18
+ * Read-only state that affordances consult on every render and hit-test
19
+ * call. Built once per Canvas render via `buildChromeState`; affordances
20
+ * must not cache it across calls.
21
+ */
22
+ interface ChromeState {
23
+ /** Currently selected ids. Live; reflects useSelection's React state. */
24
+ readonly selection: readonly NodeId[];
25
+ /** True when the canvas is in multi-mode AND >= 2 ids are selected. */
26
+ readonly multiActive: boolean;
27
+ /** Bounds for any selection member id. Honors active-tool overlay state
28
+ * (move/resize/rotate ghosts → ghost bounds; otherwise → committed
29
+ * pose bounds). Returns null for unknown ids or ids whose bounds aren't
30
+ * computable. */
31
+ boundsOf(id: string): Bounds | null;
32
+ /** Multi-union AABB when `multiActive`. Computed lazily from `boundsOf`
33
+ * over every selected id; null otherwise. */
34
+ readonly unionBounds: Bounds | null;
35
+ /** Active modifier state at the moment of the call. */
36
+ readonly modifiers: ModifierState;
37
+ /** True iff the node's pose-descriptor declares it can carry a rotation.
38
+ * Affordances consult this to decide whether to expose rotate cursors /
39
+ * drag-bands. Defaults to `true` when the descriptor doesn't declare
40
+ * (back-compat) or when the id is unknown — the rotation gesture will
41
+ * no-op visually for poses without AABB fields, but the affordance
42
+ * doesn't lie about the cursor. Optional on the interface so unit-test
43
+ * call sites that construct `ChromeState` by hand keep compiling;
44
+ * affordances should treat an absent predicate as "true". */
45
+ canRotate?(id: string): boolean;
46
+ }
47
+
48
+ /**
49
+ * @experimental
50
+ * A single interactive piece of chrome. Pure functions; the kit composes
51
+ * multiple affordances into a single RenderLayer per tool via
52
+ * `composeAffordanceLayer`.
53
+ *
54
+ * Affordances declare interactive regions in a target's *local* frame.
55
+ * The framework (`composeAffordanceLayer`) composes the target's bounds
56
+ * transform (rotation around the AABB center, when present) for both paint
57
+ * and hit-test, so the affordance never touches rotation, view.scale, or
58
+ * world↔screen math.
59
+ */
60
+ interface Affordance {
61
+ /** Stable id for debug overlays + visibility maps. */
62
+ id: string;
63
+ /** Enumerate this affordance's interactive regions. Each region lives in
64
+ * some target id's local frame (or in the world frame when `targetId`
65
+ * is `null`). Returning `[]` means "no chrome for this state" (no
66
+ * selection, multi-mode disabled, etc.). */
67
+ regions(state: ChromeState): readonly AffordanceRegion[];
68
+ /** Optional non-interactive decoration (e.g., a leader line drawn from
69
+ * a bounds edge to a handle — visual only, not draggable). Receives
70
+ * raw state + view because the decoration may live outside any single
71
+ * target's local frame. Most affordances leave this undefined. */
72
+ decorate?(state: ChromeState, view: View): DrawCommand[];
73
+ }
74
+ /**
75
+ * @experimental
76
+ * One interactive region produced by an affordance. The framework owns
77
+ * the local↔world transform for `targetId` (when non-null), so `shape`,
78
+ * `paint.sizePx`, and `hitRadiusPx` are always specified in coordinates
79
+ * the affordance can reason about directly.
80
+ */
81
+ interface AffordanceRegion<TScratch = unknown> {
82
+ /** Stable id, e.g. `corner-min-min`. Used for debug overlays + a11y. */
83
+ id: string;
84
+ /** Target id whose `state.boundsOf(targetId)` defines this region's
85
+ * local frame. `bounds.rotation` (if present) is the only transform
86
+ * applied — translation is the AABB origin; scale is identity. Pass
87
+ * `null` for affordances anchored to the viewport / world frame
88
+ * (identity transform). */
89
+ targetId: string | null;
90
+ /** Region geometry, expressed in the target's local frame.
91
+ *
92
+ * - `point` — circular hit (`hitRadiusPx` is screen-space).
93
+ * - `rect` — axis-aligned rect (target rotation applies).
94
+ * - `annulus` — outer ellipse minus inner rect cutout. Used for
95
+ * invisible zones that sit *around* the AABB (e.g. rotate-on-
96
+ * hover band). The outer ellipse is defined by world-space
97
+ * semi-axes `rx` / `ry` around `(cx, cy)`; the inner rect is the
98
+ * same target-local rect that defines the AABB. Hit-test:
99
+ * inside outer ellipse AND outside inner rect. */
100
+ shape: {
101
+ kind: 'point';
102
+ x: number;
103
+ y: number;
104
+ hitRadiusPx: number;
105
+ } | {
106
+ kind: 'rect';
107
+ x: number;
108
+ y: number;
109
+ width: number;
110
+ height: number;
111
+ } | {
112
+ kind: 'annulus';
113
+ /** Outer-ellipse center (target-local). */
114
+ cx: number;
115
+ cy: number;
116
+ /** Outer-ellipse semi-axes (target-local). */
117
+ rx: number;
118
+ ry: number;
119
+ /** Inner rect (target-local) — the cutout. Typically the
120
+ * selection's AABB. */
121
+ innerX: number;
122
+ innerY: number;
123
+ innerWidth: number;
124
+ innerHeight: number;
125
+ /** Minimum band thickness outside the inner rect, in **screen**
126
+ * pixels. The framework widens `rx`/`ry` to at least
127
+ * `innerHalfExtent + minBandPx / meanScale(view.scale)` for both
128
+ * paint and hit-test.
129
+ *
130
+ * This exists because the clamp has to know the view and the
131
+ * affordance doesn't: `ChromeState` carries no scale. Expressing the
132
+ * floor in world units instead (which is what the rotate ring used
133
+ * to do) makes the band shrink on screen as you zoom in, until the
134
+ * ring around a small shape is too thin to hover. */
135
+ minBandPx?: number;
136
+ };
137
+ /** Optional paint. World position is derived from `shape` + target
138
+ * transform; visual size stays in screen pixels (so handles don't
139
+ * warp under zoom or non-uniform scale). Omit for hit-only regions.
140
+ *
141
+ * - `square` — small fixed-size square (only valid over `point` shapes).
142
+ * - `annulus` — fill + stroke the annulus ring (only valid over
143
+ * `annulus` shapes). Uses even-odd fill rule to punch the inner-rect
144
+ * cutout.
145
+ * - `custom` — emit arbitrary draw commands; receives a {@link CustomPaintContext}. */
146
+ paint?: {
147
+ kind: 'square';
148
+ sizePx: number;
149
+ fill?: FillStyle;
150
+ stroke?: Stroke;
151
+ } | {
152
+ kind: 'annulus';
153
+ fill?: FillStyle;
154
+ stroke?: Stroke;
155
+ insetPx?: number;
156
+ } | {
157
+ kind: 'custom';
158
+ draw: (ctx: CustomPaintContext) => DrawCommand[];
159
+ };
160
+ /** Discriminator a press on this region reports as `AffordanceHit.kind` —
161
+ * the string routing specs match on (`'handle:top-left'`,
162
+ * `'rotate-handle'`, `'anchor:3'`). Omit for regions that only exist
163
+ * inside a consumer-registered layer, where the layer id is the
164
+ * discriminator; `buildAffordanceAt` falls back to
165
+ * `<affordanceId>:<regionId>`. */
166
+ hitKind?: string;
167
+ /** CSS cursor to show while hovering this region. Read by the hover-cursor
168
+ * pump in `useGestureDispatcher` via `AffordanceHit.cursor`, which
169
+ * `buildAffordanceAt` fills in from the region the walk landed on. */
170
+ cursor?: string;
171
+ /** Drag binding produced when this region is hit. Lazily called so
172
+ * affordances don't pay binding-construction cost on every paint frame —
173
+ * state snapshots (e.g., capturing per-leaf poses at click time) belong
174
+ * inside `bind()`, not inside `regions()`. */
175
+ bind(): AffordanceBinding<TScratch>;
176
+ }
177
+ /** Context passed to a region's `paint.kind === 'custom'` draw callback.
178
+ * Provides both the world-space anchor (already transformed) and the
179
+ * original local shape, for affordances that want to do additional
180
+ * geometry themselves. */
181
+ interface CustomPaintContext {
182
+ /** World-space mapping of `shape`. For `point`, only `x`/`y` are set.
183
+ * For `rect`, all four fields are set. */
184
+ world: {
185
+ x: number;
186
+ y: number;
187
+ width?: number;
188
+ height?: number;
189
+ };
190
+ /** The original local shape (same object identity as `region.shape`). */
191
+ local: AffordanceRegion['shape'];
192
+ view: View;
193
+ state: ChromeState;
194
+ }
195
+ /**
196
+ * @experimental
197
+ * Result of an affordance hit — what the region computed about itself.
198
+ *
199
+ * `initialScratch` is the payload: what the region already knows (which
200
+ * corner, which target id) so the action that picks up the drag doesn't
201
+ * re-derive it. `<SceneCanvas>` reads it out of the layer hit-test and packs
202
+ * it into `AffordanceHit`, which flows to the matching action through
203
+ * `InvocationCtx.drag.affordance`.
204
+ *
205
+ * This used to also carry a `drag: DragChannel` naming the handlers the
206
+ * tool-routing dispatcher should wire up. Every implementation supplied a
207
+ * no-op stub that claimed, because the real routing had already moved to
208
+ * bindings; the field went with that dispatcher.
209
+ */
210
+ interface AffordanceBinding<TScratch = unknown> {
211
+ initialScratch?: TScratch;
212
+ }
213
+ /**
214
+ * The fields `buildAffordanceAt` lifts out of a region's `initialScratch`
215
+ * when it turns a region hit into an `AffordanceHit`.
216
+ *
217
+ * Scratch is otherwise opaque — whatever the affordance wants to hand the
218
+ * action that picks up the drag. These few names are the exception: they mean
219
+ * the same thing to every affordance, and the actions that consume them
220
+ * (`resizeAction`, `rotateAction`) read them off `AffordanceHit` rather than
221
+ * out of scratch. An affordance that doesn't set them simply produces a hit
222
+ * without those fields.
223
+ */
224
+ interface CommonAffordanceScratch {
225
+ /** The node (or `MULTI_RESIZE_TARGET_ID`) this chrome acts on. Becomes
226
+ * `AffordanceHit.targetIds`. */
227
+ targetId?: string;
228
+ /** For resize chrome: which corner stays pinned. Mirrors the kit's
229
+ * `ResizeAnchor`, spelled inline so `affordances/` doesn't take a type
230
+ * dependency on the gesture layer for one field. */
231
+ anchor?: {
232
+ x: 'min' | 'max' | 'free';
233
+ y: 'min' | 'max' | 'free';
234
+ };
235
+ /** World-space invariant point of the transform — the fixed corner for a
236
+ * resize, the pivot for a rotation. */
237
+ fixedPoint?: {
238
+ x: number;
239
+ y: number;
240
+ };
241
+ }
242
+
243
+ /**
244
+ * Canvas size in CSS pixels — passed to `draw` for layers that anchor to
245
+ * canvas edges (e.g. the debug overlay's layer-list panel). The GL backend
246
+ * supplies it explicitly so layers don't have to know about DPR.
247
+ */
248
+ interface Dims {
249
+ width: number;
250
+ height: number;
251
+ }
252
+ /**
253
+ * A single named render sub-layer within a canvas renderer.
254
+ *
255
+ * @template TData - The data object passed to each draw call.
256
+ */
257
+ interface RenderLayer<TData> {
258
+ /** Unique identifier used in visibility maps and ordering arrays. */
259
+ id: string;
260
+ /** Human-readable name for UI toggles. */
261
+ label: string;
262
+ /**
263
+ * Emit a DrawCommand tree for the GL backend to dispatch.
264
+ *
265
+ * For world-space layers (the default), emit commands in WORLD COORDS —
266
+ * `drawLayers` automatically wraps them in `{ kind: 'group', transform:
267
+ * viewToMat3(view), ... }` before handing them to the renderer. Do NOT
268
+ * apply the view transform yourself.
269
+ *
270
+ * For screen-space layers (`space: 'screen'`), emit commands in CSS-pixel
271
+ * coords directly; `drawLayers` passes them through unchanged. If part
272
+ * of a screen-space layer's output needs to track the view, wrap that
273
+ * subset manually with `viewToMat3(view)`.
274
+ */
275
+ draw: (data: TData, view: View, dims: Dims) => DrawCommand[];
276
+ /**
277
+ * Whether the layer is shown when no explicit visibility entry exists.
278
+ * Defaults to `true` when absent.
279
+ */
280
+ defaultVisible?: boolean;
281
+ /**
282
+ * When true, the layer is always drawn regardless of the visibility map.
283
+ * Useful for layers that must never be hidden (e.g. base grid).
284
+ */
285
+ alwaysOn?: boolean;
286
+ /**
287
+ * Coordinate space the layer draws in.
288
+ *
289
+ * - `'world'` (default): the layer's `draw` returns world-space commands;
290
+ * `drawLayers` wraps them in a `kind: 'group'` with `viewToMat3(view)`
291
+ * automatically.
292
+ * - `'screen'`: the layer's `draw` returns screen-space (CSS-pixel)
293
+ * commands; `drawLayers` passes them through unchanged. World-anchored
294
+ * chrome inside a screen-space layer must call `worldToScreen` or wrap
295
+ * the relevant subset with `viewToMat3(view)` manually.
296
+ */
297
+ space?: 'world' | 'screen';
298
+ /**
299
+ * Optional hit-test for **consumer-attached** layers.
300
+ *
301
+ * Only layers registered through `CanvasExtensionApi.registerLayer` are
302
+ * hit-tested: `hitTestExtras` walks them last-registered-first on
303
+ * pointerdown, and `<SceneCanvas>` folds the result into its `affordanceAt`
304
+ * thunk ahead of the kit's own selection chrome. First non-null result
305
+ * wins; null means "I don't claim this hit, try the next layer."
306
+ *
307
+ * Layers that reach the draw stack some other way — a `Tool.overlay`, an
308
+ * entry in the `layers` map — are painted but never hit-tested, so defining
309
+ * `hitTest` on one has no effect. (The kit's own chrome doesn't need it: it
310
+ * goes through `buildAffordanceAt`.)
311
+ *
312
+ * Coordinates are world-space. The `data` arg is the layer's
313
+ * configured data slot (same as `draw`); `view` and `dims` mirror
314
+ * `draw`'s arguments.
315
+ */
316
+ hitTest?: (worldX: number, worldY: number, data: TData, view: View, dims: Dims,
317
+ /** Chrome-caps visibility predicate. When supplied, the layer must
318
+ * not return a hit from any chrome element whose id reports
319
+ * `false`. Absent → every element is hittable. */
320
+ isVisible?: (id: string) => boolean) => AffordanceBinding | null;
321
+ /**
322
+ * Called on every pointermove when no gesture is currently captured.
323
+ * Lets layers (e.g. HUD widgets) track hover state without participating
324
+ * in the drag pipeline. Coords are world-space; the layer is responsible
325
+ * for any further conversion (e.g. world→screen for screen-space layers)
326
+ * and for its own throttling.
327
+ */
328
+ onUncapturedMove?: (worldX: number, worldY: number, evt: PointerEvent, view: View, dims: Dims) => void;
329
+ /**
330
+ * Called when the cursor leaves the canvas element. Lets layers clear
331
+ * any hover state they're holding.
332
+ */
333
+ onUncapturedLeave?: () => void;
334
+ }
335
+ /**
336
+ * Walk visible layers and concatenate their emitted DrawCommand arrays into
337
+ * one flat list, ready to feed to `WeaselRenderer.render(commands)`.
338
+ *
339
+ * Visibility resolution order:
340
+ * 1. `alwaysOn` — always drawn, ignores visibility map.
341
+ * 2. Explicit entry in `visibility` map — overrides default.
342
+ * 3. `layer.defaultVisible` — falls back to `true` when absent.
343
+ *
344
+ * Transform composition: world-space layers (the default; `space` unset or
345
+ * `'world'`) have their commands wrapped in a `kind: 'group'` with
346
+ * `viewToMat3(view)` before they reach the renderer. Screen-space layers
347
+ * (`space: 'screen'`) pass through unchanged.
348
+ */
349
+ declare function drawLayers<TData>(layers: RenderLayer<TData>[], data: TData, visibility: Record<string, boolean>, order: string[] | undefined, view: View | undefined, dims: Dims): DrawCommand[];
350
+
351
+ /**
352
+ * Live state read by rule evaluation. Built once per frame on the consuming
353
+ * surface — chrome-caps, the affordance pipeline, the dispatcher's
354
+ * eligibility filter — and discarded.
355
+ *
356
+ * Adding a new field is additive: existing rules don't change, new
357
+ * selector atoms can read it.
358
+ */
359
+ interface RuleCtx {
360
+ readonly focused: boolean;
361
+ readonly selection: readonly NodeId[];
362
+ readonly multiActive: boolean;
363
+ readonly modifiers: ModifierState;
364
+ readonly action: {
365
+ readonly kind: string | null;
366
+ readonly id: string | null;
367
+ };
368
+ readonly hover: NodeId | null;
369
+ readonly view: View;
370
+ /** Active mode id. `'normal'` when no non-default mode is engaged. */
371
+ readonly mode: string;
372
+ /** Capability tags allowed by the active mode (the union of
373
+ * `ModeDefinition.allows` plus implicit tags). The `capability:`
374
+ * selector reads this to determine whether a tag is permitted. */
375
+ readonly allowedCapabilities: ReadonlySet<CapabilityTag>;
376
+ /** Whether the current selection may be resized. `<SceneCanvas>` folds
377
+ * `selectTool.resize.resizable` over the selection (true only when every
378
+ * selected node is resizable). Read by the `resizable:` selector to gate
379
+ * `selection.resize-handles`. Absent (legacy ctx builders) is treated as
380
+ * resizable — back-compat: handles show unless a consumer opts a node out. */
381
+ readonly selectionResizable?: boolean;
382
+ /** Whether a path is currently in anchor-edit mode. Read by the
383
+ * `editingAnchors:` selector, which gates the path-edit chrome.
384
+ *
385
+ * This is deliberately a fact about state, not about permission: the
386
+ * anchor overlay and the anchor hit-test must agree, and the thing they
387
+ * must agree on is "is there an edited path right now", which no
388
+ * capability or mode id answers. A mode that allows `edits-anchors`
389
+ * with nothing being edited should draw no anchors. Absent is treated
390
+ * as false. */
391
+ readonly editingAnchors?: boolean;
392
+ }
393
+ interface BuildRuleCtxArgs {
394
+ focused: boolean;
395
+ selection: readonly NodeId[];
396
+ multiActive: boolean;
397
+ modifiers: ModifierState;
398
+ action: {
399
+ kind: string | null;
400
+ id: string | null;
401
+ };
402
+ hover: NodeId | null;
403
+ view: View;
404
+ mode: string;
405
+ allowedCapabilities: ReadonlySet<CapabilityTag>;
406
+ /** Optional — omitted means "resizable" (handles show). See {@link RuleCtx}. */
407
+ selectionResizable?: boolean;
408
+ /** Optional — omitted means "no path is being anchor-edited". */
409
+ editingAnchors?: boolean;
410
+ }
411
+ declare function buildRuleCtx(args: BuildRuleCtxArgs): RuleCtx;
412
+
413
+ /**
414
+ * A selector is a conjunction of key/value tests. Multiple keys at the same
415
+ * level AND together. Each key maps to a selector primitive in the evaluator.
416
+ */
417
+ interface Selector {
418
+ selection?: {
419
+ is?: number;
420
+ atLeast?: number;
421
+ empty?: boolean;
422
+ };
423
+ mode?: string | {
424
+ not: string;
425
+ } | {
426
+ in: readonly string[];
427
+ };
428
+ capability?: CapabilityTag | readonly CapabilityTag[] | {
429
+ in: readonly CapabilityTag[];
430
+ } | {
431
+ not: CapabilityTag;
432
+ };
433
+ gesturing?: boolean;
434
+ actionIs?: string;
435
+ modifierHeld?: keyof ModifierState;
436
+ focused?: boolean;
437
+ hovering?: boolean;
438
+ hoveringSelected?: boolean;
439
+ zoomAtLeast?: number;
440
+ /** Matches `ctx.editingAnchors` — true while a path is in anchor-edit
441
+ * mode. Absent flag is treated as `false`. */
442
+ editingAnchors?: boolean;
443
+ /** Matches `ctx.selectionResizable`. Absent flag is treated as `true`
444
+ * (resizable), so `{ resizable: true }` passes for legacy ctx builders
445
+ * that don't compute it. */
446
+ resizable?: boolean;
447
+ }
448
+ /**
449
+ * Composable visibility/eligibility rule. Trees of `all`/`any`/`not` nodes
450
+ * over `Selector` leaves. `when` is the escape hatch — its closure is
451
+ * opaque to introspection and should be avoided when a declarative form
452
+ * exists. Empty `all` is true; empty `any` is false.
453
+ */
454
+ type Rule = Selector | {
455
+ all: readonly Rule[];
456
+ } | {
457
+ any: readonly Rule[];
458
+ } | {
459
+ not: Rule;
460
+ } | {
461
+ when: (ctx: RuleCtx) => boolean;
462
+ };
463
+ /** Constant rules. Kept here so they have a single source. */
464
+ declare const ALWAYS: Rule;
465
+ declare const NEVER: Rule;
466
+ /**
467
+ * Render a {@link Rule} as a short human-readable string, for inspectors and
468
+ * diagnostics that need to say WHICH rule decided something.
469
+ *
470
+ * ```
471
+ * { capability: 'edits-page' } → capability:edits-page
472
+ * { all: [{ mode: 'normal' }, { focused: true }] } → all(mode:normal, focused:true)
473
+ * { not: { selection: { empty: true } } } → not(selection:empty=true)
474
+ * { when: function hasPath() { … } } → when(hasPath)
475
+ * ```
476
+ *
477
+ * Never throws and always terminates — unlike `JSON.stringify`, which throws
478
+ * on a cyclic value and renders the `when` arm as a useless `{}`.
479
+ */
480
+ declare function describeRule(rule: Rule): string;
481
+ declare function evaluate(rule: Rule, ctx: RuleCtx): boolean;
482
+
483
+ /**
484
+ * Live state read by chrome-visibility {@link Condition}s. Backward-compat
485
+ * alias for the legacy ChromeCtx shape — kept for consumers that still
486
+ * import `ChromeCtx`. Subset of `RuleCtx`: legacy ChromeCtx didn't carry
487
+ * mode/capability info. The resolver builds a `RuleCtx` for evaluation;
488
+ * surfaces that still operate in `ChromeCtx` shape supply defaults
489
+ * (mode='normal', empty allowedCapabilities) at the construction site.
490
+ */
491
+ interface ChromeCtx {
492
+ readonly focused: boolean;
493
+ readonly selection: readonly NodeId[];
494
+ readonly multiActive: boolean;
495
+ readonly modifiers: ModifierState;
496
+ readonly action: {
497
+ readonly kind: string | null;
498
+ readonly id: string | null;
499
+ };
500
+ readonly hover: NodeId | null;
501
+ readonly view: View;
502
+ }
503
+ /**
504
+ * Composable visibility predicate with fluent surface. Carries its underlying
505
+ * `Rule` tree at `.rule` so the resolver can introspect / share trees with
506
+ * the affordance pipeline and the dispatcher's eligibility filter.
507
+ *
508
+ * Callable form `cond(ctx)` evaluates the tree against ctx. The fluent
509
+ * methods return new Conditions wrapping new trees.
510
+ *
511
+ * **Chain semantics: strict left-to-right, no precedence.**
512
+ * `a.and(b).or(c)` is `(a && b) || c`; `a.or(b).and(c)` is
513
+ * `(a || b) && c`. Mix `.and` and `.or` only when you mean
514
+ * left-to-right evaluation. For grouped disjunction, name the
515
+ * subexpression or use the top-level `or(...)`.
516
+ */
517
+ interface Condition {
518
+ (ctx: RuleCtx): boolean;
519
+ readonly rule: Rule;
520
+ /** `this && other` */
521
+ and(other: Condition | Rule): Condition;
522
+ /** `this || other` */
523
+ or(other: Condition | Rule): Condition;
524
+ /** `this && !other` */
525
+ andNot(other: Condition | Rule): Condition;
526
+ /** `this || !other` */
527
+ orNot(other: Condition | Rule): Condition;
528
+ }
529
+ /**
530
+ * Stable identifier for one user-visible chrome element. The same id
531
+ * gates both paint and hit-test — there is no separate
532
+ * `affordance.X` / `selection.X` split — so toggling a rule cannot
533
+ * leave a visually-present but un-hittable handle (or vice versa).
534
+ *
535
+ * Naming convention by lifecycle:
536
+ *
537
+ * - `selection.*` — chrome reflecting committed selection state
538
+ * (persists between actions).
539
+ * - `action.*` — chrome that only exists during an in-flight
540
+ * action (vanishes on commit / cancel).
541
+ * - `snap.*` — snapping system chrome (guides, target highlights).
542
+ * - `grid`, `debug.*` — environment chrome.
543
+ *
544
+ * The intersection `(string & {})` keeps the union open so consumers
545
+ * can register their own ids; the kit's built-ins are listed
546
+ * explicitly for autocomplete.
547
+ */
548
+ type ChromeId = 'selection.outline' | 'selection.resize-handles' | 'selection.rotation-handle' | 'action.marquee' | 'action.lasso' | 'action.move-ghosts' | 'action.insert-preview' | 'action.commands' | 'snap.guides' | 'snap.targets' | 'grid' | (string & {});
549
+ /**
550
+ * Consumer override map. Merged on top of the kit's
551
+ * `defaultVisibilityRules`; absent keys fall through to defaults,
552
+ * absent ids fall through to `always`. Entries may be either fluent
553
+ * `Condition` instances OR raw `Rule` trees — the resolver normalizes.
554
+ */
555
+ type VisibilityRules = Partial<Record<ChromeId, Condition | Rule>>;
556
+
557
+ /** A 2D point in either world or screen coordinates. */
558
+ interface Point2 {
559
+ x: number;
560
+ y: number;
561
+ }
562
+ /**
563
+ * Information about which UI affordance was hit at pointerdown.
564
+ *
565
+ * Populated by the dispatcher when the `affordanceAt` thunk is provided to
566
+ * `useGestureDispatcher`. Tools / action invokers that only fire on a specific
567
+ * affordance (e.g. a resize handle) use this field as a guard — if the
568
+ * affordance is absent or is the wrong kind, they return `{}` and let other
569
+ * bindings handle the drag.
570
+ *
571
+ * `kind` is a discriminator string:
572
+ * - `'handle:top-left'` / `'handle:top-right'` / `'handle:bottom-left'` /
573
+ * `'handle:bottom-right'` — corner resize handles.
574
+ * - `'rotate-handle'` — the rotation affordance.
575
+ * - `'anchor:N'` — a path anchor at index N.
576
+ *
577
+ * `fixedPoint` is the world-space point that should remain stationary during
578
+ * the gesture. For resize handles this is the opposite (diagonally fixed)
579
+ * corner; for rotate it is the pivot.
580
+ *
581
+ * `targetIds` are the node ids this affordance belongs to.
582
+ */
583
+ interface AffordanceHit {
584
+ /** Discriminator string, e.g. `'handle:bottom-right'`. */
585
+ kind: string;
586
+ /** World-space fixed/pivot point. For resize: opposite corner. For rotate: pivot. */
587
+ fixedPoint?: {
588
+ x: number;
589
+ y: number;
590
+ };
591
+ /** Which nodes this affordance belongs to. */
592
+ targetIds?: string[];
593
+ /** Set when `kind` matches `'handle:*'`. Identifies which corner stays
594
+ * fixed during a resize so consumers (resizeAction) don't re-parse `kind`.
595
+ * Other affordance kinds (rotate-handle, anchor:N, controlIn:N, controlOut:N)
596
+ * leave this undefined. */
597
+ anchor?: ResizeAnchor;
598
+ /** CSS cursor to show while the pointer hovers this affordance (no
599
+ * gesture in flight). Consumed by the hover-cursor pump in
600
+ * `useGestureDispatcher`; unset = the pump falls through to
601
+ * action-cursor prediction, then to the active tool's cursor. */
602
+ cursor?: string;
603
+ /**
604
+ * Free-form payload from whatever produced the hit, carried through to the
605
+ * matching action untouched.
606
+ *
607
+ * Kit affordances describe themselves fully in the fields above and leave
608
+ * this unset. It exists for affordances the kit doesn't know the shape of —
609
+ * a registered layer's own chrome, where the hit-test already resolved
610
+ * *which* of its pieces was hit and the action would otherwise have to
611
+ * redo that work. `@weasel-js/hud` passes the hit widget here.
612
+ */
613
+ payload?: unknown;
614
+ }
615
+ /**
616
+ * One accumulated point on a drag trail: world-space position plus whatever
617
+ * stylus state the originating `PointerEvent` carried.
618
+ *
619
+ * The stylus fields are absent for mouse/touch on browsers that don't report
620
+ * them, and for synthetic events. Consumers that want pressure-driven output
621
+ * (e.g. `Stroke.vertexWidths` from a pencil stroke) read them off the samples
622
+ * their `insert` dep receives — see `apps/site/demos/VertexWidthsDemo.tsx`.
623
+ */
624
+ interface DragSample extends Point2 {
625
+ /** 0..1. Mouse/touch report 0.5 while a button is held, per the spec. */
626
+ pressure?: number;
627
+ /** Degrees, ±90. Zero for mouse/touch. */
628
+ tiltX?: number;
629
+ /** Degrees, ±90. Zero for mouse/touch. */
630
+ tiltY?: number;
631
+ }
632
+ /** Per-invocation runtime context the dispatcher hands to an Invoker.
633
+ * Gesture-kind-specific fields (`drag`, `wheel`, `multiTouch`, `key`) are
634
+ * populated only for matching gesture kinds. */
635
+ interface InvocationCtx {
636
+ world: Point2;
637
+ screen: Point2;
638
+ modifiers: ModifierState;
639
+ deps: ActionDeps;
640
+ drag?: {
641
+ start: Point2;
642
+ current: Point2;
643
+ delta: Point2;
644
+ /**
645
+ * Drag delta in client/screen coordinates (CSS pixels from the drag
646
+ * origin). Use this — never `delta` — for any action whose effect
647
+ * mutates the viewport itself (pan, view-zoom), because world-space
648
+ * deltas become self-referential as the view shifts mid-drag.
649
+ *
650
+ * Populated when the dispatcher received `clientX`/`clientY` on the
651
+ * underlying pointer events. Absent for legacy callers that don't
652
+ * provide them.
653
+ */
654
+ screenDelta?: Point2;
655
+ affordance?: AffordanceHit;
656
+ /**
657
+ * Full pointermove history for the current drag, in world space, with
658
+ * per-sample stylus state when the browser reported it.
659
+ * Accumulated by the dispatcher on every `pointermove` pump event.
660
+ * Available only during `onMove` and `onEnd` calls (not on `start`).
661
+ * Used by `lassoSelectAction` to build its polygon vertex list and by
662
+ * `insertAction`'s pencil kind to carry the freehand stroke.
663
+ */
664
+ points?: DragSample[];
665
+ };
666
+ wheel?: {
667
+ deltaX: number;
668
+ deltaY: number;
669
+ deltaZ: number;
670
+ };
671
+ multiTouch?: {
672
+ centroid: Point2;
673
+ spread: number;
674
+ rotation: number;
675
+ /**
676
+ * Pinch-zoom geometry. Populated by the dispatcher when a multitouch
677
+ * handle is in flight and a pointermove-pump fires.
678
+ * `startSpread` is the spread at the moment the gesture began.
679
+ * `currentSpread` is the spread at the current frame.
680
+ */
681
+ pinch?: {
682
+ startSpread: number;
683
+ currentSpread: number;
684
+ centroid: Point2;
685
+ };
686
+ };
687
+ key?: {
688
+ key: string;
689
+ repeat: boolean;
690
+ };
691
+ /**
692
+ * Per-invocation parameters. Populated by `ActionsRegistry.begin()` for
693
+ * UI-driven ongoing actions (color picker, opacity slider) so handles can
694
+ * read the current value on `start` and updated values on `onMove`. The
695
+ * gesture dispatcher does not populate this field; gesture-driven actions
696
+ * receive params via `BindingOpts.params` on `start` (the `opts` arg).
697
+ */
698
+ params?: Record<string, unknown>;
699
+ }
700
+ /** Per-invocation options the dispatcher reads from a `GestureBinding`'s
701
+ * `opts` field and passes to `OngoingInvoker.start`. Today carries
702
+ * behaviors; extensible. */
703
+ interface BindingOpts {
704
+ behaviors?: ActionBehavior<unknown, unknown, unknown>[];
705
+ /** Per-binding action parameters. The action's invoker reads
706
+ * these via the second arg to `run` (or via InvocationCtx for ongoing
707
+ * invokers, when needed). Loose typing (Record<string, unknown>) for
708
+ * now; consider per-action typing later via BindingOpts<A>.
709
+ *
710
+ * params may also be a thunk evaluated each time the
711
+ * dispatcher (or invoker) needs the value. Thunks let tools close over
712
+ * refs that mutate during a gesture (e.g. polygon `sides` adjusted
713
+ * mid-drag via ArrowUp). For ongoing invokers that want the latest
714
+ * values at commit, the invoker can re-call the thunk inside `onEnd`
715
+ * via `resolveParams(opts?.params)`. */
716
+ params?: Record<string, unknown> | (() => Record<string, unknown>);
717
+ }
718
+ /** Convention-shaped action dependencies bag. Actions declare which
719
+ * contexts they consume; the dispatcher composes them per call.
720
+ * Consumer-side contexts (e.g. ColorContext) plug in by extending. */
721
+ interface ActionDeps {
722
+ selection?: unknown;
723
+ view?: unknown;
724
+ scene?: unknown;
725
+ pointer?: unknown;
726
+ activeTool?: unknown;
727
+ [k: string]: unknown;
728
+ }
729
+ /**
730
+ * Discriminated overlay shape returned by `OngoingHandle.overlay()`.
731
+ * Dispatcher-side chrome surface for in-flight
732
+ * gestures that paint non-ghost visuals. The canvas's
733
+ * `useDispatcherOverlayLayer` walks every in-flight handle, calls
734
+ * `overlay()`, and dispatches on `kind` to draw the appropriate shape.
735
+ *
736
+ * `marquee` mirrors `AreaSelectOverlay`; `lasso` mirrors `LassoSelectOverlay`.
737
+ * `commands` is the generic escape hatch — actions emit arbitrary
738
+ * `DrawCommand[]` for previews the typed variants can't express (insert
739
+ * shape outlines, paste ghosts of synthetic nodes, custom chrome). World-
740
+ * space is the default; the layer wraps in `viewToMat3` so commands track
741
+ * the camera. Set `space: 'screen'` for projections you've already done
742
+ * yourself (rare).
743
+ */
744
+ type OngoingOverlay = {
745
+ kind: 'marquee';
746
+ start: {
747
+ x: number;
748
+ y: number;
749
+ };
750
+ current: {
751
+ x: number;
752
+ y: number;
753
+ };
754
+ shiftHeld: boolean;
755
+ } | {
756
+ kind: 'lasso';
757
+ vertices: ReadonlyArray<{
758
+ x: number;
759
+ y: number;
760
+ }>;
761
+ current: {
762
+ x: number;
763
+ y: number;
764
+ };
765
+ shiftHeld: boolean;
766
+ } | {
767
+ kind: 'commands';
768
+ commands: readonly DrawCommand[];
769
+ /** Coordinate space the commands are authored in. Default `'world'`
770
+ * — the layer wraps them in `viewToMat3(view)` so they track the
771
+ * camera. `'screen'` emits them as-is (CSS pixels). */
772
+ space?: 'world' | 'screen';
773
+ } | {
774
+ /**
775
+ * Live insert-drag preview — dispatched by `insertAction` while the
776
+ * user is dragging out a new shape. Pre-commit there is no scene node
777
+ * to ghost via `previewIds()`/`previewPose()`, so insert paints its
778
+ * preview through the dispatcher overlay layer instead.
779
+ *
780
+ * `shape` is the kit's built-in insert kind. `bounds` is the AABB of
781
+ * the current drag (start/current normalized). `extras` is the
782
+ * per-kind extras the action already collected — the overlay
783
+ * renderer rebuilds the shape using the same path builders the
784
+ * commit factory uses, so the preview matches the eventual node.
785
+ *
786
+ * `extras` is opaque (`unknown`) at the union level; the overlay
787
+ * renderer narrows on `shape` and casts the field shape it expects.
788
+ */
789
+ kind: 'insertPreview';
790
+ shape: 'rect' | 'ellipse' | 'line' | 'polygon' | 'star' | 'pencil';
791
+ bounds: {
792
+ x: number;
793
+ y: number;
794
+ width: number;
795
+ height: number;
796
+ };
797
+ extras: unknown;
798
+ /** World-space point to paint a small "anchor" dot at. Sells the
799
+ * click point as the drag's anchor — particularly useful for
800
+ * radial shapes (polygon/star) where no vertex sits on the
801
+ * click point, and for any shape in center mode where the dot
802
+ * marks the center the shape grows around. */
803
+ anchorPoint?: {
804
+ x: number;
805
+ y: number;
806
+ };
807
+ };
808
+ /** Handle returned from an `OngoingInvoker.start`. The dispatcher pumps
809
+ * `onMove` on subsequent input events of the same gesture and calls
810
+ * `onEnd` exactly once (with `'commit'` on natural completion or `'cancel'`
811
+ * on pointercancel / blur / escape). */
812
+ interface OngoingHandle {
813
+ /**
814
+ * Optional logical action kind — a stable, human-readable tag the
815
+ * dispatcher exposes via `getActiveAction()` for chrome-visibility
816
+ * rules and any other surface that wants to react to "what action
817
+ * is currently in flight" without inspecting handles directly.
818
+ *
819
+ * Examples: `'marquee'`, `'lasso'`, `'move'`, `'resize'`, `'rotate'`,
820
+ * `'pan'`, `'pinch'`.
821
+ *
822
+ * Distinct from the dispatcher's internal `gestureId` (`pointer-mouse`,
823
+ * `key-held-Space`, etc.) which keys per-pointer state and is not
824
+ * meaningful to consumers.
825
+ *
826
+ * When omitted, the action is "anonymous" — `getActiveAction().kind`
827
+ * reports `null` even though a handle is in flight. This is fine for
828
+ * actions that don't have visible chrome of their own.
829
+ */
830
+ kind?: string;
831
+ onMove?(ctx: InvocationCtx): void;
832
+ onEnd?(ctx: InvocationCtx, reason: 'commit' | 'cancel'): void;
833
+ /**
834
+ * Optional preview surface — dispatcher-side ghost overlay.
835
+ *
836
+ * An ongoing-action implementation may populate `previewIds()` +
837
+ * `previewPose(id)` to expose its in-flight preview state for the
838
+ * canvas's preview-ghost layer (`usePreviewGhostLayer`) to render on
839
+ * top of the committed scene during the gesture.
840
+ *
841
+ * Returning `null` (or omitting the method entirely) means "no preview
842
+ * this gesture" — the canvas will skip this handle as a source.
843
+ *
844
+ * Semantics mirror the tool-side `Tool.previewIds` / `Tool.previewPose`
845
+ * pair: `previewIds()` enumerates the displaced node ids; `previewPose(id)`
846
+ * returns the interim pose for one of those ids (shape opaque — the
847
+ * canvas casts to its `TPose` parameter). The preview-ghost layer
848
+ * merges all sources via first-non-null semantics, with tool-side
849
+ * previews taking precedence over dispatcher-side (preserves
850
+ * backwards-compat during the registry-unification migration).
851
+ */
852
+ previewIds?(): Iterable<string> | null;
853
+ previewPose?(id: string): unknown | null;
854
+ /**
855
+ * When `false`, the preview-ghost layer paints the ghost AND the
856
+ * source node stays visible at its committed pose. Defaults to
857
+ * `true` (move/resize/rotate semantics: ghost replaces the source
858
+ * during the gesture). Clone overrides to `false` so the original
859
+ * stays put and the ghost appears at the drag target.
860
+ */
861
+ previewHidesSource?: boolean;
862
+ /**
863
+ * Optional per-id preview *data*. Falls back to the committed
864
+ * `node.data` when null/absent. Use when the gesture mutates
865
+ * `node.data` (e.g. anchor-edit on nodes that store the polygon on
866
+ * `data.path`) rather than (or in addition to) the pose. The preview-
867
+ * ghost layer assembles a synthetic node from `{ ...node, pose:
868
+ * previewPose ?? node.pose, data: previewData ?? node.data }` before
869
+ * calling the scene slot's `drawOne`.
870
+ *
871
+ * Sources compose first-non-null per axis: an action can emit only
872
+ * `previewPose` (translation), only `previewData` (data-only edit),
873
+ * or both (pose + data both change, e.g. anchor drag on a data.path
874
+ * node where the bounds shift).
875
+ */
876
+ previewData?(id: string): unknown | null;
877
+ /**
878
+ * Optional chrome surface — dispatcher-side overlay layer.
879
+ *
880
+ * An ongoing-action implementation may populate `overlay()` to expose a
881
+ * non-ghost visual (marquee rectangle, lasso polyline) for the canvas's
882
+ * `useDispatcherOverlayLayer` to paint while the gesture is in flight.
883
+ * Returning `null` (or omitting the method) means "no overlay this
884
+ * gesture" — the canvas will skip this handle as a chrome source.
885
+ *
886
+ * Distinct from the `previewIds()`/`previewPose(id)` ghost surface,
887
+ * which paints displaced scene-node silhouettes. Marquee and lasso
888
+ * gestures don't displace any node, but still need on-screen feedback.
889
+ */
890
+ overlay?(): OngoingOverlay | null;
891
+ }
892
+ /** Fire-once invocation. Runs to completion synchronously (or fires off an
893
+ * async side-effect; the registry doesn't wait). */
894
+ interface ImmediateInvoker {
895
+ timing: 'immediate';
896
+ /** `params` carries the matched binding's opts.params. When
897
+ * invoked via the legacy `Action.run` bridge or from the command palette
898
+ * with no per-binding context, `params` is undefined; descriptors should
899
+ * default to a sensible variant. */
900
+ run(deps: ActionDeps, params?: Record<string, unknown>): void;
901
+ }
902
+ /** Phase-machine invocation. `start` opens the phase and returns the handle
903
+ * the dispatcher pumps. */
904
+ interface OngoingInvoker {
905
+ timing: 'ongoing';
906
+ start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle;
907
+ }
908
+ /** Pluggable invocation strategy for an Action. Future variants
909
+ * (`longPress`, `twoStage`, `modal`) extend this union without touching
910
+ * the `Action` type. */
911
+ type Invoker = ImmediateInvoker | OngoingInvoker;
912
+
913
+ /** Boolean op identifiers — five Pathfinder primaries plus Crop. */
914
+ type BooleanOp = 'union' | 'intersect' | 'subtract' | 'exclude' | 'divide' | 'crop';
915
+ /**
916
+ * z-position descriptor for a path node. `parentId` is the direct parent
917
+ * (or `null` for a top-level node); `index` is the position within that
918
+ * parent's child order. Used by the optional `getZOrder` hook below to
919
+ * reposition the result of a boolean op at the topmost source's slot.
920
+ */
921
+ /** @internal */
922
+ interface BooleanZOrder {
923
+ parentId: string | null;
924
+ index: number;
925
+ }
926
+ /** Adapter the hook and the pure core both consume. */
927
+ interface BooleansAdapter {
928
+ getSelection(): NodeId[];
929
+ getWorldPath(id: NodeId): Path | undefined;
930
+ compareZ(a: NodeId, b: NodeId): number;
931
+ /**
932
+ * Mint a new node from a boolean-op result `Path`. `producedBy` names the
933
+ * op that synthesized it — adapters that store provenance (e.g. for a
934
+ * layer-panel icon) record it; others ignore the arg.
935
+ */
936
+ createPathNode(path: Path, producedBy: BooleanOp): {
937
+ id: string;
938
+ };
939
+ /**
940
+ * Optional: return the full object for an id, used by the delete ops so
941
+ * their `invert` (an insert) can restore the complete object on undo.
942
+ * If omitted, a `{ id }` stub is captured — undo will reinstate the id
943
+ * but consumers reading other fields (path, fill, etc.) will see them as
944
+ * undefined. Mirrors `DeleteAdapter.getNode`; should be provided whenever
945
+ * undo over boolean ops is expected to be lossless.
946
+ */
947
+ getNode?(id: NodeId): {
948
+ id: string;
949
+ } | undefined | null;
950
+ /**
951
+ * Optional: return the parent + child-index of `id` so the result of a
952
+ * boolean op can be placed in the topmost source's z-slot. Adapters that
953
+ * also expose `getChildren`/`setChildOrder` (the `ReorderAdapter`
954
+ * contract) will have the kit emit a `createMoveToIndexOp` after the
955
+ * inserts. Adapters that omit this method get v1 behavior — the result
956
+ * lands wherever the adapter's plain `insertNode` defaults to.
957
+ */
958
+ getZOrder?(id: NodeId): BooleanZOrder | undefined;
959
+ applyOps?(ops: Op[], label?: string): void;
960
+ setSelection?(ids: NodeId[]): void;
961
+ insertNode?(node: {
962
+ id: string;
963
+ }): void;
964
+ removeNode?(id: string): void;
965
+ }
966
+ /** Outcome reported back to callers (lets the hook surface no-op signals). */
967
+ type BooleanOpResult = {
968
+ kind: 'applied';
969
+ resultIds: string[];
970
+ } | {
971
+ kind: 'noop';
972
+ reason: 'no-paths' | 'too-few-for-subtract' | 'empty-result';
973
+ };
974
+ declare function applyBooleanOp(adapter: BooleansAdapter, op: BooleanOp): BooleanOpResult;
975
+
976
+ /**
977
+ * Selection click policy. `single` always replaces; `multi` toggles when the
978
+ * configured extend key is held, otherwise replaces.
979
+ */
980
+ type SelectionMode = 'single' | 'multi';
981
+ /** Modifier key used to extend the selection in `multi` mode. */
982
+ type SelectionExtendKey = 'shift' | 'meta' | 'ctrl';
983
+ /** API returned by {@link useSelection}. */
984
+ interface SelectionApi {
985
+ /** Current selection. Re-renders trigger when this reference changes. */
986
+ current: readonly NodeId[];
987
+ /** Imperative read for use inside event callbacks (avoids stale closures). */
988
+ get(): NodeId[];
989
+ /** Replace selection. */
990
+ set(ids: NodeId[]): void;
991
+ /** Add id (multi-mode appends; single-mode replaces). */
992
+ add(id: NodeId): void;
993
+ /** Remove id from selection. */
994
+ remove(id: NodeId): void;
995
+ /** Toggle id in/out of selection. */
996
+ toggle(id: NodeId): void;
997
+ /** Clear selection. */
998
+ clear(): void;
999
+ /** True if id is selected. */
1000
+ contains(id: NodeId): boolean;
1001
+ /**
1002
+ * Apply a click to the selection per the configured mode/extend key.
1003
+ * - `single`: replaces selection with `[id]`, regardless of modifiers.
1004
+ * - `multi`: with the extend key held, toggles `id` in/out of the selection;
1005
+ * otherwise replaces with `[id]`.
1006
+ */
1007
+ applyClick(id: NodeId, modifiers: {
1008
+ shift: boolean;
1009
+ meta: boolean;
1010
+ ctrl: boolean;
1011
+ }): void;
1012
+ /** Pre-built methods for spreading into an adapter that needs them. */
1013
+ adapterMethods: {
1014
+ getSelection: () => NodeId[];
1015
+ setSelection: (ids: NodeId[]) => void;
1016
+ };
1017
+ }
1018
+ /** Options for {@link useSelection}. */
1019
+ interface UseSelectionOptions {
1020
+ /** Default `'single'`. */
1021
+ mode?: SelectionMode;
1022
+ /** Default `'shift'`. Ignored in single-mode. */
1023
+ extend?: SelectionExtendKey;
1024
+ /** Default `[]`. */
1025
+ initial?: readonly NodeId[];
1026
+ /** When `true`, every mutator (`set`/`add`/`remove`/`toggle`/`clear`/
1027
+ * `applyClick`) is a no-op — selection stays at whatever `initial`
1028
+ * pinned it to. Useful for demos that exist to showcase a single
1029
+ * pre-selected node (e.g. the bezier-edit curve) and don't want a
1030
+ * stray click to deselect. */
1031
+ lock?: boolean;
1032
+ }
1033
+ /**
1034
+ * Default implementation of the `getSelection` / `setSelection` adapter
1035
+ * contract every action hook (delete, duplicate, nudge, group, ...) requires.
1036
+ *
1037
+ * Owns selection state, exposes a click-policy helper (single vs multi with
1038
+ * an extend key), and pre-builds the two adapter methods consumers otherwise
1039
+ * hand-roll in every demo:
1040
+ *
1041
+ * ```tsx
1042
+ * const selection = useSelection({ mode: 'multi' });
1043
+ * const adapter = { ...arrayAdapter({...}), ...selection.adapterMethods };
1044
+ * ```
1045
+ */
1046
+ declare function useSelection(opts?: UseSelectionOptions): SelectionApi;
1047
+
1048
+ /** Context handed to every content handler for one ingest event. */
1049
+ interface IngestCtx {
1050
+ /** World-space arrival point (drop / pointed imperative ingest); `null`
1051
+ * for paste and point-less calls — handlers pick their own policy
1052
+ * (the kit image handler centers on the viewport). */
1053
+ point: {
1054
+ x: number;
1055
+ y: number;
1056
+ } | null;
1057
+ /** Visible canvas area in world coordinates. */
1058
+ viewportWorldRect(): {
1059
+ x: number;
1060
+ y: number;
1061
+ width: number;
1062
+ height: number;
1063
+ };
1064
+ /** The kit insert dep — id/layer/undoable-op supplied; the canonical way
1065
+ * for a handler to mint a node (`insert.commit(bounds, { kind, ... })`). */
1066
+ insert: InsertDep;
1067
+ /** Raw op commit for handlers that build their own ops. */
1068
+ applyOps(ops: Op[], label?: string): void;
1069
+ scene: Scene<unknown, string, unknown>;
1070
+ selection: SelectionApi;
1071
+ /** Consumer file→src resolver (SceneCanvas `ingestion.resolveSrc`).
1072
+ * When absent, the kit image handler embeds as a `data:` URI. */
1073
+ resolveSrc?: (file: File) => Promise<string>;
1074
+ /** Kit SVG-handler options (SceneCanvas `ingestion.svg`) — e.g.
1075
+ * `{ unpack: unpackSvgFiles }` (from `@weasel-js/svg`) to parse SVG files
1076
+ * into scene nodes. */
1077
+ svg?: SvgIngestOptions;
1078
+ /** Clipboard-paste seam — present when the hosting `SceneCanvas` supplied
1079
+ * an adapter with `commitPaste`. `reviver` comes from
1080
+ * `SceneCanvasProps.ingestion.clipboard`. Absent ⇒ the kit weasel-JSON
1081
+ * handler declines inert (dwarn, nothing ingested) — its matched items
1082
+ * were already consumed at match time, so they do NOT fall through;
1083
+ * only match-level misses flow on to other handlers. */
1084
+ clipboard?: ClipboardIngestCtx;
1085
+ /** Set to `true` by the kit weasel-JSON handler when it successfully
1086
+ * pastes a payload in this event. The `ctx` object is shared across all
1087
+ * handlers in one `runIngest` call, and higher-priority handlers' `handle`
1088
+ * bodies run (synchronously) before lower ones — so `kit:svg`'s
1089
+ * `text/plain` SVG fallback reads this to decline the SVG flavor of a copy
1090
+ * whose canonical weasel-JSON flavor already ingested (avoids a
1091
+ * double-paste when both flavors ride one clipboard event). */
1092
+ consumedWeaselPayload?: boolean;
1093
+ /** Full action-deps bag, for consumer handlers that need more. */
1094
+ deps: ActionDeps;
1095
+ }
1096
+ interface ContentHandlerEntry {
1097
+ /** Stable identifier — used for unregistration and debugging
1098
+ * (`'kit:image'`, `'app:csv'`). */
1099
+ id: string;
1100
+ /** MIME glob(s) (`'image/*'`, `'text/csv'`) or an item predicate. */
1101
+ match: string | string[] | ((item: IngestItem) => boolean);
1102
+ /** Higher runs earlier. Kit defaults register at -100 so any consumer
1103
+ * handler (default 0) beats them. */
1104
+ priority?: number;
1105
+ handle(items: IngestItem[], ctx: IngestCtx): void | Promise<void>;
1106
+ }
1107
+ /** Register a content handler. Returns a disposer that removes it. */
1108
+ declare function registerContentHandler(entry: ContentHandlerEntry): () => void;
1109
+
1110
+ /**
1111
+ * @experimental
1112
+ * PointerContext — a tiny ambient context that publishes the world-space
1113
+ * position of the canvas pointer, refreshed on every `pointermove` over
1114
+ * the canvas. Cleared (set to `null`) on `pointerleave`.
1115
+ *
1116
+ * Why ref-based and not state-based: cursor moves fire dozens of times per
1117
+ * second; routing those through React state would re-render every consumer
1118
+ * in the tree. The context exposes a stable `pointerRef` whose `.current`
1119
+ * is mutated directly by the publisher, plus a thunk `getDropPoint()` that
1120
+ * reads it on demand. Consumers (e.g. `useClipboard`) pull via the thunk
1121
+ * inside their callbacks — no subscription, no re-render.
1122
+ *
1123
+ * `<SceneCanvas>` publishes automatically. `useClipboardOps` consumes when
1124
+ * the caller didn't pass an explicit `getDropPoint` option. Other future
1125
+ * hit-on-cursor consumers (drop-zone hover, context-menu anchor) can reuse
1126
+ * the same context.
1127
+ */
1128
+
1129
+ /** @experimental World-space pointer position, or `null` when the pointer
1130
+ * isn't over the publishing canvas. */
1131
+ type PointerWorldPos = {
1132
+ worldX: number;
1133
+ worldY: number;
1134
+ } | null;
1135
+ /** @experimental */
1136
+ interface PointerContextValue {
1137
+ /** Live ref — mutate to publish, read for the latest snapshot. The
1138
+ * identity is stable for the lifetime of the provider. */
1139
+ readonly pointerRef: MutableRefObject<PointerWorldPos>;
1140
+ /** Convenience thunk equivalent to `() => pointerRef.current`. Stable
1141
+ * identity for the lifetime of the provider; safe to pass to hooks. */
1142
+ readonly getDropPoint: () => PointerWorldPos;
1143
+ }
1144
+ /**
1145
+ * @experimental
1146
+ * Wrap the part of the React tree that should share a pointer-position
1147
+ * context. Usually placed at the demo / app root, alongside
1148
+ * `<ActionsProvider>` and `<SelectionContextProvider>`.
1149
+ *
1150
+ * Most consumers don't need to mount this directly — `<SceneCanvas>` mounts
1151
+ * an internal provider when no parent provider is in scope, so child hooks
1152
+ * (`useClipboard` without an explicit `getDropPoint`) read the canvas's
1153
+ * tracked pointer for free.
1154
+ */
1155
+ declare function PointerContextProvider({ children }: {
1156
+ children: ReactNode;
1157
+ }): ReactNode;
1158
+ /** @experimental Read the surrounding pointer-context value, or `null` when
1159
+ * no provider is in scope. */
1160
+ declare function usePointerContext(): PointerContextValue | null;
1161
+
1162
+ interface ActiveToolContextValue {
1163
+ active: string;
1164
+ hotkeyStack: string[];
1165
+ setActive(id: string): void;
1166
+ pushHotkey(id: string): void;
1167
+ popHotkey(): void;
1168
+ }
1169
+ interface ActiveToolContextProviderProps {
1170
+ children: ReactNode;
1171
+ initialActive?: string;
1172
+ }
1173
+ declare function ActiveToolContextProvider({ children, initialActive, }: ActiveToolContextProviderProps): react_jsx_runtime.JSX.Element;
1174
+ declare function useActiveToolContext(): ActiveToolContextValue;
1175
+ /**
1176
+ * Like `useActiveToolContext`, but returns `null` when no
1177
+ * `<ActiveToolContextProvider>` is in scope instead of throwing. Used by
1178
+ * `useStandardActions` to preserve its silent-no-op contract when no provider
1179
+ * is present.
1180
+ */
1181
+ declare function useOptionalActiveToolContext(): ActiveToolContextValue | null;
1182
+ /**
1183
+ * Conditional `<ActiveToolContextProvider>` wrapper. Mounts a provider only
1184
+ * when no parent provider is in scope — otherwise renders children unwrapped
1185
+ * so callers (e.g. `<WeaselProvider>`, `<SceneCanvas>`) defer to the host's
1186
+ * existing scope. Mirrors `ActionsProviderIfRoot` / `DepRegistryProviderIfRoot`.
1187
+ */
1188
+ declare function ActiveToolContextProviderIfRoot({ children, }: {
1189
+ children: ReactNode;
1190
+ }): react_jsx_runtime.JSX.Element;
1191
+
1192
+ /**
1193
+ * `enterTextEditAction` — immediate Action descriptor for entering in-place
1194
+ * text editing on a selected text node.
1195
+ *
1196
+ * ## Status: REAL
1197
+ *
1198
+ * Fires via `useTextTool.bindings` when the user clicks on a
1199
+ * selected text node. Calls `deps.textEdit.startEdit(id)` to activate the
1200
+ * contenteditable overlay managed by `useTextEdit` / `useSceneTextEdit`.
1201
+ *
1202
+ * ## No defaultBinding / defaultBinding
1203
+ *
1204
+ * This action has no ambient key or gesture binding — it fires ONLY via
1205
+ * `useTextTool`'s `Tool.bindings` entry:
1206
+ *
1207
+ * ```ts
1208
+ * bindings: [
1209
+ * { spec: { kind: 'click', target: 'selected-body' }, actionId: 'enterTextEdit' },
1210
+ * ]
1211
+ * ```
1212
+ *
1213
+ * Keeping it binding-free avoids ambient double-fire and scopes the action to
1214
+ * the text tool context where `classifyTarget` is already wired.
1215
+ *
1216
+ * ## Self-guard: only act on text nodes
1217
+ *
1218
+ * The `'selected-body'` target yields a match for any selected node kind. To
1219
+ * avoid entering text-edit mode when the text tool happens to have a non-text
1220
+ * node selected, the action self-guards via an optional `isTextNode` predicate
1221
+ * on `TextEditDep`:
1222
+ *
1223
+ * - When `isTextNode` is absent: action fires unconditionally (the binding
1224
+ * spec is the real gate — consumers should only bind this action from the
1225
+ * text tool).
1226
+ * - When `isTextNode(id)` returns `false`: action is a no-op for that node.
1227
+ *
1228
+ * ### Pre-filtering at dispatch time
1229
+ *
1230
+ * `classifyTarget` now surfaces node kind, so a binding can pre-filter instead
1231
+ * of relying on the self-guard:
1232
+ *
1233
+ * ```ts
1234
+ * { spec: { kind: 'click', target: 'kind:text:selected' }, actionId: 'enterTextEdit' }
1235
+ * ```
1236
+ *
1237
+ * That reads the *routing trait's* kind, so it matches whatever names the
1238
+ * consumer registered in `<SceneCanvas routing>` — `'text'` under the kit's
1239
+ * inferred default. `isTextNode` stays on `TextEditDep` because it also covers
1240
+ * consumers who bind the broader `'selected-body'` target, and because it is
1241
+ * the only guard for a consumer who opted out of routing entirely.
1242
+ *
1243
+ * ## Migration plan for useTextTool
1244
+ *
1245
+ * When wiring `useTextTool` to `Tool.bindings`:
1246
+ *
1247
+ * 1. Add to `useTextTool`'s `bindings`:
1248
+ * ```ts
1249
+ * { spec: { kind: 'click', target: 'selected-body' }, actionId: 'enterTextEdit' }
1250
+ * ```
1251
+ * 2. Register a `textEdit` dep sourced from the `useTextEdit` / `useSceneTextEdit`
1252
+ * return value, plus an `isTextNode` predicate that checks `data.kind === 'text'`
1253
+ * (or however the consumer identifies text nodes).
1254
+ * 3. The existing `hitExisting` gate in `useTextTool`'s click route becomes
1255
+ * redundant — remove it in the same pass.
1256
+ */
1257
+
1258
+ /**
1259
+ * Dep for `enterTextEditAction`.
1260
+ *
1261
+ * Wrap the return value of `useTextEdit` / `useSceneTextEdit` to source this
1262
+ * dep. The `isTextNode` predicate is optional — when absent the action fires
1263
+ * unconditionally (the binding spec acts as the gate).
1264
+ *
1265
+ * @example
1266
+ * ```ts
1267
+ * const textEdit = useSceneTextEdit({ scene, container });
1268
+ * useDepSource('textEdit', () => ({
1269
+ * startEdit: textEdit.startEdit,
1270
+ * isTextNode: (id) => scene.get(id as NodeId)?.data?.kind === 'text',
1271
+ * }));
1272
+ * ```
1273
+ */
1274
+ interface TextEditDep {
1275
+ /**
1276
+ * Begin editing the node with `id`. Activates the contenteditable overlay
1277
+ * managed by `useTextEdit` / `useSceneTextEdit`.
1278
+ */
1279
+ startEdit(id: string, opts?: {
1280
+ caret?: number | 'all';
1281
+ }): void;
1282
+ /**
1283
+ * Optional predicate: returns `true` when the node with `id` is a text node.
1284
+ * When absent the action fires on any selected node (binding spec is the gate).
1285
+ * When present and returning `false`, the invocation is a no-op.
1286
+ */
1287
+ isTextNode?(id: string): boolean;
1288
+ }
1289
+ /**
1290
+ * @experimental
1291
+ * Static descriptor for the `enterTextEdit` Action.
1292
+ *
1293
+ * Requires dep-schema entries: `textEdit`, `selection`.
1294
+ *
1295
+ * No `defaultBinding` / `defaultBinding` — fires only via `Tool.bindings`.
1296
+ * Self-guards via `TextEditDep.isTextNode` when provided.
1297
+ */
1298
+ declare const enterTextEditAction: Action & {
1299
+ requires: string[];
1300
+ };
1301
+
1302
+ /**
1303
+ * Consumer-supplied commit for the Slice action. `commit` receives the finite
1304
+ * slice segment (world coords); the consumer scans the scene, splits crossed
1305
+ * paths via `splitPathByLine`, and applies the result as one undoable batch.
1306
+ */
1307
+ interface SliceDep {
1308
+ commit(a: Point2, b: Point2): void;
1309
+ }
1310
+ /**
1311
+ * @experimental
1312
+ * Static descriptor for the `slice` Action.
1313
+ *
1314
+ * Ongoing drag invoker: tracks a slice line from drag start to current
1315
+ * pointer, renders a live line overlay while the gesture is in flight,
1316
+ * and on commit calls `SliceDep.commit(a, b)`. No-ops gracefully when
1317
+ * the `slice` dep is absent.
1318
+ */
1319
+ declare const sliceAction: Action & {
1320
+ requires: string[];
1321
+ };
1322
+
1323
+ /** Optional consumer seam: given a node and the affine `m` that a pose-transform
1324
+ * action applied to the node's POSE, return updated `data` with the node's
1325
+ * data-held geometry transformed by `m`, or `null` if this node has no
1326
+ * data-held geometry (the kit leaves `data` alone). */
1327
+ interface GeometryProjection {
1328
+ transform(node: {
1329
+ id?: string;
1330
+ data: unknown;
1331
+ pose: unknown;
1332
+ }, m: Mat3): unknown | null;
1333
+ }
1334
+
1335
+ /** Minimal view API the action layer consumes. May be refined later. */
1336
+ interface ViewApi {
1337
+ get(): View;
1338
+ set(v: View): void;
1339
+ /** Optional recenter callback. When wired, `viewportZoomAction`'s
1340
+ * `reset` branch (Cmd-0) calls this instead of resetting to identity —
1341
+ * letting consumers re-fit the page (or other reference bounds) into
1342
+ * the workspace. Receives no args; the consumer reads its own bounds
1343
+ * + host dims and dispatches `setView(...)`. */
1344
+ recenter?(): void;
1345
+ /** Optional canvas-local host dimensions (CSS px). When wired,
1346
+ * `viewportZoomAction`'s keyboard branches (Cmd+= / Cmd+-) anchor at the
1347
+ * host center instead of the top-left origin. Null when the host isn't
1348
+ * measurable (unmounted). */
1349
+ hostSize?(): {
1350
+ width: number;
1351
+ height: number;
1352
+ } | null;
1353
+ }
1354
+ /**
1355
+ * Adapter dep for `areaSelectAction`.
1356
+ *
1357
+ * Provided by `<SceneCanvas>` / `<StandardActionsRegistrar>` via AABB
1358
+ * overlap over scene nodes. Consumers with custom hit-testing override this
1359
+ * dep entry in their own registrar.
1360
+ */
1361
+ /**
1362
+ * Topmost-node-at-world-point dep, consumed by `moveAction` for
1363
+ * reparent-on-drop and available to any action that needs a single-best
1364
+ * pick. Mirrors the same hit-test plumbing `<SceneCanvas>` feeds to the
1365
+ * tool dispatcher; consumers with custom hit-testing override here.
1366
+ *
1367
+ * `exclude` is iterated once per call and treated as a set membership
1368
+ * test — the dep walks hits front-to-back and returns the first id not
1369
+ * in the exclude set. Pass moving-node roots + their descendants when
1370
+ * the caller wants to ignore the nodes it's manipulating.
1371
+ */
1372
+ type NodeAtPointDep = (point: {
1373
+ x: number;
1374
+ y: number;
1375
+ }, exclude?: Iterable<NodeId>) => NodeId | null;
1376
+ interface AreaSelectDep {
1377
+ /** Return ids of all scene nodes whose AABB overlaps `bounds`. */
1378
+ hitTestArea(bounds: {
1379
+ x: number;
1380
+ y: number;
1381
+ width: number;
1382
+ height: number;
1383
+ }): NodeId[];
1384
+ /** Return the current selection id list. */
1385
+ getSelection(): NodeId[];
1386
+ /** Replace the current selection. */
1387
+ setSelection(ids: NodeId[]): void;
1388
+ }
1389
+ /**
1390
+ * Adapter dep for `editAnchorsAction`.
1391
+ *
1392
+ * Provides narrow read/write access to the editable polygon for a single
1393
+ * node. Consumers register this dep so anchor-edit actions can read/write
1394
+ * the polygon WITHOUT knowing whether it lives directly on the node's
1395
+ * pose (`pose.kind === 'polygon'`) or on `node.data.path` (the kit's
1396
+ * built-in pen-tool default, also WeaselDraw's shape).
1397
+ *
1398
+ * Note on live previews: in-flight edit state is surfaced through the
1399
+ * dispatcher's standard `OngoingHandle.previewIds/previewPose/previewData`
1400
+ * triple (not this dep), so chrome and preview-ghost stay in lock-step
1401
+ * via one source of truth.
1402
+ */
1403
+ interface EditAnchorsDep {
1404
+ /** Id of the node currently being edited. Empty string means no node is
1405
+ * currently in edit mode — the chrome and gesture both opt out. */
1406
+ editingId: string;
1407
+ /** Enter/exit edit mode for a specific node. Pass `null` (or an empty
1408
+ * string) to exit. `enterPathEditAction` and `exitPathEditAction` call
1409
+ * this; consumers can call it directly to drive edit mode programmatically. */
1410
+ setEditingId(id: string | null): void;
1411
+ /** Returns the COMMITTED editable polygon in world coordinates, or
1412
+ * null if this node has no editable polygon. Does NOT consult in-
1413
+ * flight previews — callers that need live state read the dispatcher's
1414
+ * in-flight handles. */
1415
+ getEditablePath(id: string): unknown;
1416
+ /** Returns where the polygon is stored — `'pose'` when `node.pose`
1417
+ * IS the polygon, `'data'` when it lives on `node.data.path` with a
1418
+ * rect pose, or `null` when the node has no editable polygon. The
1419
+ * action uses this to know which preview-ghost axis to populate
1420
+ * (`previewPose` only / `previewData` + `previewPose` for data.path). */
1421
+ getStorageKind(id: string): 'pose' | 'data' | null;
1422
+ /** Returns the node's raw `pose` and `data` so storage-aware actions
1423
+ * can capture origin state at gesture-start and synthesize a matching
1424
+ * `previewPose` / `previewData` during `onMove`. Used by
1425
+ * `editAnchorsAction` for the data.path branch (rect pose + data
1426
+ * carrying extra fields like fill / stroke that must be preserved
1427
+ * through the preview). Returns null when the node is gone. */
1428
+ getNodeShape(id: string): {
1429
+ pose: unknown;
1430
+ data: unknown;
1431
+ } | null;
1432
+ /** Commit `worldPath` as the new value for `id`. Implementation routes
1433
+ * to setPose (when pose IS the polygon) or batched setPose+update
1434
+ * (when the polygon lives on data.path). Records one history entry
1435
+ * labelled `label`. */
1436
+ applyEdit(id: string, worldPath: unknown, label: string): void;
1437
+ /**
1438
+ * Anchors currently selected within the edited path, as **flat anchor
1439
+ * indices** — the same numbering `enumerateAnchors` produces and the
1440
+ * `anchor:N` affordance kinds carry.
1441
+ *
1442
+ * Selection is transient UI state, deliberately not part of the scene:
1443
+ * it is cleared whenever `editingId` changes, and any edit that
1444
+ * renumbers anchors (insert, delete) is responsible for leaving it
1445
+ * coherent. Empty means "no anchor selected" — the keyboard actions
1446
+ * (nudge, delete) no-op rather than acting on all anchors, matching
1447
+ * Illustrator.
1448
+ */
1449
+ selectedAnchors: ReadonlySet<number>;
1450
+ /** Replace the anchor selection. Pass an empty iterable to clear. */
1451
+ setSelectedAnchors(next: Iterable<number>): void;
1452
+ /**
1453
+ * In-flight anchor-marquee rect in world coords, or null when no
1454
+ * marquee drag is active. Written by `marqueeAnchorsAction` and read by
1455
+ * the path-editing overlay — the same "ongoing action owns the preview,
1456
+ * chrome just draws it" split the move/resize ghosts use.
1457
+ */
1458
+ marquee: {
1459
+ x: number;
1460
+ y: number;
1461
+ width: number;
1462
+ height: number;
1463
+ } | null;
1464
+ /** Set or clear the in-flight marquee rect. */
1465
+ setMarquee(rect: {
1466
+ x: number;
1467
+ y: number;
1468
+ width: number;
1469
+ height: number;
1470
+ } | null): void;
1471
+ }
1472
+ /**
1473
+ * Adapter dep for `lassoSelectAction`.
1474
+ *
1475
+ * Provides polygon-lasso hit-testing + selection read/write.
1476
+ * Consumers that don't implement `hitTestLasso` can omit it; the action
1477
+ * falls back to a bounding-box AABB test via `hitTestArea`.
1478
+ */
1479
+ interface LassoSelectDep {
1480
+ /**
1481
+ * Hit-test against a closed polygon (vertex order CW or CCW; last→first
1482
+ * closing edge is implicit). Returns matching node ids.
1483
+ * Optional — when absent, `lassoSelectAction` falls back to AABB via
1484
+ * `hitTestArea`.
1485
+ */
1486
+ hitTestLasso?(polygon: ReadonlyArray<{
1487
+ x: number;
1488
+ y: number;
1489
+ }>, mode: 'centers' | 'intersect' | 'enclosed'): string[];
1490
+ /** Return ids of nodes whose AABB overlaps the given rect (fallback). */
1491
+ hitTestArea(bounds: {
1492
+ x: number;
1493
+ y: number;
1494
+ width: number;
1495
+ height: number;
1496
+ }): string[];
1497
+ /** Return the current selection id list. */
1498
+ getSelection(): string[];
1499
+ /** Replace the current selection. */
1500
+ setSelection(ids: string[]): void;
1501
+ }
1502
+ /**
1503
+ * Options for the kit `image/svg+xml` content handler, threaded from
1504
+ * SceneCanvas's `ingestion={{ svg }}` prop.
1505
+ */
1506
+ interface SvgIngestOptions {
1507
+ /** Parse dropped/pasted/picked SVG files into native scene nodes (path /
1508
+ * text leaves under containers mirroring the source `<g>` structure)
1509
+ * instead of the default single embedded-image node.
1510
+ *
1511
+ * Pass `unpackSvgFiles` from `@weasel-js/svg`:
1512
+ *
1513
+ * ```ts
1514
+ * import { unpackSvgFiles } from '@weasel-js/svg';
1515
+ * <SceneCanvas ingestion={{ svg: { unpack: unpackSvgFiles } }} />
1516
+ * ```
1517
+ *
1518
+ * It is injected rather than flagged on with `true` because the SVG parser
1519
+ * lives in `@weasel-js/svg`, which depends on this package — core importing
1520
+ * it back would make the two mutually dependent and unpublishable
1521
+ * separately. Passing the function keeps the parser out of core's bundle
1522
+ * for consumers who never unpack. */
1523
+ unpack?: SvgUnpacker;
1524
+ }
1525
+ /** Parses SVG files and inserts the resulting nodes into `ctx.scene`, as one
1526
+ * `applyOps` batch per file. Implemented by `unpackSvgFiles` in
1527
+ * `@weasel-js/svg`; see {@link SvgIngestOptions.unpack}. */
1528
+ type SvgUnpacker = (files: File[], ctx: IngestCtx) => Promise<void>;
1529
+ /**
1530
+ * Clipboard-paste seam consumed by the kit weasel-JSON content handler
1531
+ * (`IngestCtx.clipboard`). Built by `<SceneCanvas>` from its own synthesized
1532
+ * adapter + the `ingestion.clipboard` prop; absent when the consumer set
1533
+ * `ingestion.clipboard.enabled === false` or the adapter lacks `commitPaste`.
1534
+ * Absence makes the handler decline inert (dwarn, nothing ingested) — its
1535
+ * matched items were already consumed at match time and do not fall through
1536
+ * to other handlers.
1537
+ */
1538
+ interface ClipboardIngestCtx {
1539
+ /** The hosting canvas's adapter — `commitPaste` materializes the pasted
1540
+ * nodes (fresh ids, offset applied); insertion still goes through ops. */
1541
+ adapter: InsertAdapter<{
1542
+ id: string;
1543
+ }>;
1544
+ /** JSON reviver for the weasel wire payload (typed arrays etc.) — from
1545
+ * `SceneCanvasProps.ingestion.clipboard.reviver`. */
1546
+ reviver?: (key: string, value: unknown) => unknown;
1547
+ }
1548
+ /**
1549
+ * Dep for the `ingest` action (external-content ingestion).
1550
+ * Sourced from `<SceneCanvas>` / `<StandardActionsRegistrar>` via
1551
+ * `useIngestionDepSource` — canvas rect + current view.
1552
+ */
1553
+ interface IngestionDep {
1554
+ /** Visible canvas area in world coordinates. */
1555
+ viewportWorldRect(): {
1556
+ x: number;
1557
+ y: number;
1558
+ width: number;
1559
+ height: number;
1560
+ };
1561
+ /** Consumer file→src resolver (from SceneCanvas's `ingestion` prop).
1562
+ * Live accessor — read it at use time. Destructuring (or copying the
1563
+ * property early) snapshots the current value and won't track later
1564
+ * prop changes across an `await`. */
1565
+ resolveSrc?: (file: File) => Promise<string>;
1566
+ /** Kit SVG-handler options (from SceneCanvas's `ingestion` prop).
1567
+ * Live accessor, same caveat as `resolveSrc`. */
1568
+ svg?: SvgIngestOptions;
1569
+ /** Clipboard-paste seam for the kit weasel-JSON handler.
1570
+ * Live accessor, same caveat as `resolveSrc`. */
1571
+ clipboard?: ClipboardIngestCtx;
1572
+ }
1573
+ /**
1574
+ * Per-kind extra geometry passed to `InsertDep.commit`.
1575
+ *
1576
+ * Built-in tools populate a typed variant so the kit's default factory can
1577
+ * render the true tool params (line endpoints, polygon side count, star
1578
+ * geometry, pencil sample list). Consumer-defined tools may pass any
1579
+ * `{ kind: string; ... }` payload; the kit's factory falls back to AABB
1580
+ * inscription for unknown kinds.
1581
+ *
1582
+ * `bounds` is still passed alongside as a useful AABB pose hint — factories
1583
+ * may use it as the node's pose even when richer geometry is available.
1584
+ */
1585
+ type InsertExtras = {
1586
+ kind: 'rect';
1587
+ } | {
1588
+ kind: 'ellipse';
1589
+ } | {
1590
+ kind: 'line';
1591
+ a: {
1592
+ x: number;
1593
+ y: number;
1594
+ };
1595
+ b: {
1596
+ x: number;
1597
+ y: number;
1598
+ };
1599
+ } | {
1600
+ kind: 'polygon';
1601
+ sides: number;
1602
+ rotation: number;
1603
+ center?: {
1604
+ x: number;
1605
+ y: number;
1606
+ };
1607
+ radius?: number;
1608
+ } | {
1609
+ kind: 'star';
1610
+ points: number;
1611
+ innerRadiusRatio: number;
1612
+ rotation: number;
1613
+ center?: {
1614
+ x: number;
1615
+ y: number;
1616
+ };
1617
+ outerRadius?: number;
1618
+ } | {
1619
+ kind: 'pencil';
1620
+ samples: ReadonlyArray<DragSample>;
1621
+ } | {
1622
+ kind: 'text';
1623
+ text?: string;
1624
+ } | {
1625
+ kind: string;
1626
+ [extra: string]: unknown;
1627
+ };
1628
+ /**
1629
+ * World-space point snapping — grid, guides, or any consumer rule.
1630
+ *
1631
+ * Sourced by `<SceneCanvas>` from its `toolOptions.snapPoint`. Actions apply
1632
+ * it to the coords they ingest so the live preview and the committed
1633
+ * geometry agree; `insertAction` snaps the drag's start and current point.
1634
+ *
1635
+ * Optional: when the dep is absent, actions treat it as identity.
1636
+ */
1637
+ interface SnapDep {
1638
+ /** Snap a world-space point. Return `p` unchanged to opt out. */
1639
+ point(p: {
1640
+ x: number;
1641
+ y: number;
1642
+ }): {
1643
+ x: number;
1644
+ y: number;
1645
+ };
1646
+ }
1647
+ /**
1648
+ * Adapter dep for `insertAction`.
1649
+ *
1650
+ * Provided by `<SceneCanvas>` / `<StandardActionsRegistrar>`. The `extras`
1651
+ * carry the active tool's kind + per-kind geometry. Callers
1652
+ * that need typed data must supply a richer `insert` dep.
1653
+ */
1654
+ interface InsertDep {
1655
+ /**
1656
+ * Materialise a new node from the given drag-rect bounds and typed
1657
+ * per-kind extras. Returns the new node's id, or `null` if the consumer
1658
+ * rejected the insert (e.g. sub-threshold bounds, unknown kind).
1659
+ */
1660
+ commit(bounds: {
1661
+ x: number;
1662
+ y: number;
1663
+ width: number;
1664
+ height: number;
1665
+ }, extras: InsertExtras): NodeId | null;
1666
+ }
1667
+ /**
1668
+ * Adapter dep for `resizeAction`.
1669
+ *
1670
+ * Carries the four behavior-shaping options the legacy `useResize` hook
1671
+ * exposed through `UseResizeOptions`: bounds-frame behaviors (e.g.
1672
+ * `lockAspectWithModifier`), world-space anchor-point snap behaviors (e.g.
1673
+ * `pointSnapToGrid`), group-expansion (`expandIds`), and pose↔bounds
1674
+ * projection (`geometry`).
1675
+ *
1676
+ * Optional in `DepSchema`: when absent, `resizeAction` falls back to
1677
+ * identity defaults (no behaviors, identity expandIds, `RECT_POSE_DESCRIPTOR`
1678
+ * geometry). Consumers wire the dep via `useDepSource('resizePolicy', ...)`
1679
+ * from any descendant of `<DepRegistryProvider>` / `<SceneCanvas>`.
1680
+ *
1681
+ * The generic is erased to `unknown` at the schema entry; consumers cast at
1682
+ * the call site (mirrors the `scene` entry's convention).
1683
+ */
1684
+ interface ResizePolicy<TPose> {
1685
+ /** Bounds-frame constraints. Constrained to `TPose extends ResizePose` since
1686
+ * constraints read/write `{x,y,width,height}`. For non-rect TPose pass `[]`. */
1687
+ constraints: TPose extends ResizePose ? BoundsConstraint<TPose>[] : never[];
1688
+ /** World-space anchor-point snap behaviors. Same TPose constraint as
1689
+ * `constraints`. */
1690
+ pointSnap: TPose extends ResizePose ? PointSnapBehavior<TPose>[] : never[];
1691
+ /** Group-expansion at gesture start. Identity (`ids => ids`) when group
1692
+ * resize isn't wanted. */
1693
+ expandIds: (ids: string[]) => string[];
1694
+ /** Projection from `TPose` to bounds and back. Use `RECT_POSE_DESCRIPTOR`
1695
+ * for plain rect poses. */
1696
+ projection: PoseProjection<TPose>;
1697
+ }
1698
+ /**
1699
+ * Layout-strategy lookup by container id, consumed by `moveAction` to run
1700
+ * the drag-time reflow pass. Sourced by `<SceneCanvas>` from its `layouts`
1701
+ * prop. Optional: `getLayout` returns null for any container when no layout
1702
+ * is configured, so the reflow pass is a no-op then.
1703
+ */
1704
+ interface LayoutDep {
1705
+ getLayout(containerId: string): LayoutStrategy<unknown> | null;
1706
+ }
1707
+ interface DepSchema {
1708
+ /** Kit selection state — ids of currently selected nodes. */
1709
+ selection: SelectionApi;
1710
+ /** Current viewport — camera position + scale. */
1711
+ view: ViewApi;
1712
+ /**
1713
+ * Scene tree — structural reads + undoable mutations.
1714
+ *
1715
+ * The entry uses the fully-erased form `Scene<unknown, string, unknown>`
1716
+ * because `DepSchema` must be concrete. Actions that need a typed scene
1717
+ * should cast: `deps.scene as Scene<MyData, MyLayer, MyPose>`.
1718
+ */
1719
+ scene: Scene<unknown, string, unknown>;
1720
+ /** Undo/redo history bound to the current scene. */
1721
+ history: History;
1722
+ /**
1723
+ * Canvas pointer position in world space.
1724
+ *
1725
+ * Exposes `pointerRef` (mutable live ref) and `getDropPoint()` thunk.
1726
+ * Marked `@experimental` in the source.
1727
+ */
1728
+ pointer: PointerContextValue;
1729
+ /** Currently active tool id + hotkey-hold stack. */
1730
+ activeTool: ActiveToolContextValue;
1731
+ /**
1732
+ * Area-select dep — AABB hit-test + selection read/write.
1733
+ *
1734
+ * Sourced from `<SceneCanvas>` via AABB overlap over all scene
1735
+ * nodes. Override per-consumer for custom hit-testing (e.g. contain-mode,
1736
+ * lock-aware filtering).
1737
+ */
1738
+ areaSelect: AreaSelectDep;
1739
+ /**
1740
+ * Topmost node at a world-space point. Sourced by `<SceneCanvas>` from
1741
+ * the same picker that feeds the tool dispatcher's `getNodeAtPoint`.
1742
+ * Optional: actions that read this (e.g. `moveAction` reparent-on-drop)
1743
+ * fall back to a no-op when the dep isn't registered.
1744
+ */
1745
+ nodeAtPoint?: NodeAtPointDep;
1746
+ /**
1747
+ * Insert dep — node factory for drag-to-insert.
1748
+ *
1749
+ * Sourced from `<SceneCanvas>`. The `kind` param comes from
1750
+ * the active binding's `opts.params.kind`. Override per-consumer to
1751
+ * provide a typed node factory (e.g. with custom data payloads).
1752
+ */
1753
+ insert: InsertDep;
1754
+ /**
1755
+ * Snap dep — world-space point snapping (grid / guides).
1756
+ *
1757
+ * Sourced by `<SceneCanvas>` from `toolOptions.snapPoint`. Optional:
1758
+ * absent means no snapping (identity).
1759
+ */
1760
+ snap?: SnapDep;
1761
+ /**
1762
+ * Lasso-select dep — polygon hit-test + selection read/write.
1763
+ *
1764
+ * Sourced from `<SceneCanvas>` / `<StandardActionsRegistrar>`.
1765
+ * Falls back to AABB hit-test when `hitTestLasso` is absent.
1766
+ */
1767
+ lassoSelect: LassoSelectDep;
1768
+ /**
1769
+ * Edit-anchors dep — narrow read/write of one polygon's path pose.
1770
+ *
1771
+ * Sourced from consumer. Wraps `getPose`/`setPose`/`applyOps`
1772
+ * for the currently-being-edited polygon node.
1773
+ *
1774
+ * The `editAnchorsAction` requires this dep to be registered when anchor
1775
+ * editing is active. If absent, `start` returns an empty handle (no-op).
1776
+ */
1777
+ editAnchors: EditAnchorsDep;
1778
+ /**
1779
+ * Text-edit dep — activates the in-place text editing overlay.
1780
+ *
1781
+ * Sourced from consumer via `useTextEdit` / `useSceneTextEdit`.
1782
+ * The `enterTextEditAction` requires this dep to be registered by the text
1783
+ * tool when text editing is available.
1784
+ *
1785
+ * The optional `isTextNode` predicate guards against entering edit mode on
1786
+ * non-text nodes. A binding can pre-filter instead with a
1787
+ * `target: 'kind:text:selected'` spec; the guard remains for consumers who
1788
+ * bind the broader `'selected-body'` target or opted out of routing.
1789
+ */
1790
+ textEdit: TextEditDep;
1791
+ /**
1792
+ * Resize-policy dep — bounds constraints, point-snap behaviors,
1793
+ * group expansion, and pose↔bounds projection for `resizeAction`.
1794
+ *
1795
+ * Optional: when omitted, `resizeAction` falls back to identity defaults
1796
+ * (no constraints, no snap, identity expandIds, `RECT_POSE_DESCRIPTOR`).
1797
+ * Consumers wire via `useDepSource('resizePolicy', ...)` or the
1798
+ * `useResizePolicy` helper.
1799
+ */
1800
+ resizePolicy?: ResizePolicy<unknown>;
1801
+ /**
1802
+ * Booleans adapter — read selection ids, fetch world-space `Path`s,
1803
+ * compare z-order, and mint result nodes for Pathfinder ops.
1804
+ *
1805
+ * Consumers wire via `useBooleansAdapter(adapter)` (a thin wrapper
1806
+ * around `useDepSource('booleansAdapter', ...)`). The descriptor's
1807
+ * `enabled` predicate reads `deps.selection` for the count check; the
1808
+ * invoker reads `deps.booleansAdapter` to execute the op.
1809
+ */
1810
+ booleansAdapter?: BooleansAdapter;
1811
+ /**
1812
+ * Gesture dispatcher control surface — exposes `cancelAll(reason)` so
1813
+ * actions that need to abort an in-flight handle (Escape cancels a
1814
+ * drag, etc.) can do so. Sourced by `<SceneCanvas>` from the
1815
+ * dispatcher instance it already owns.
1816
+ */
1817
+ dispatcher?: {
1818
+ cancelAll(reason: 'commit' | 'cancel'): void;
1819
+ };
1820
+ /**
1821
+ * Layout-strategy lookup. Sourced by `<SceneCanvas>` from `layouts`.
1822
+ * Optional: absent (or all-null) → `moveAction` skips reflow.
1823
+ */
1824
+ layout?: LayoutDep;
1825
+ /**
1826
+ * Slice dep — consumer-supplied commit for the Slice action.
1827
+ *
1828
+ * Receives the finite slice segment in world coordinates; the consumer
1829
+ * scans the scene, splits crossed paths via `splitPathByLine`, and
1830
+ * applies the result as one undoable batch.
1831
+ *
1832
+ * Optional: when absent, `sliceAction` is a no-op.
1833
+ */
1834
+ slice?: SliceDep;
1835
+ /**
1836
+ * Optional consumer commit hook. When present, `moveAction` (and other
1837
+ * default actions) submit their committed ops through it instead of
1838
+ * `scene.applyBatch`, so apps with their own history integration
1839
+ * (checkpoint + push entry) capture the gesture as one undo entry.
1840
+ * When absent, commits fall back to `scene.applyBatch`.
1841
+ */
1842
+ applyOps?: (ops: Op[], label: string) => void;
1843
+ /** Optional pose-composition strategy for hierarchical (local-pose) scenes.
1844
+ * When absent, defaults to IDENTITY (absolute-pose: nodes store world
1845
+ * coords). Local-pose consumers supply { compose: composeRectPose,
1846
+ * decompose: decomposeRectPose } (or their pose shape's equivalent). */
1847
+ poseComposition?: PoseComposition<unknown>;
1848
+ /**
1849
+ * Ingestion dep — canvas viewport rect + consumer file→src resolver.
1850
+ *
1851
+ * Sourced from `<SceneCanvas>` / `<StandardActionsRegistrar>` via
1852
+ * `useIngestionDepSource`. Feeds `ingestAction` with the world-space
1853
+ * viewport rect for paste-placement and image fit-clamping, and forwards
1854
+ * the consumer's optional `resolveSrc` seam.
1855
+ *
1856
+ * Optional: when absent, the `ingest` action no-ops (there is no
1857
+ * placement geometry to work with).
1858
+ */
1859
+ ingestion?: IngestionDep;
1860
+ /**
1861
+ * Optional consumer seam for the eager-sync layer: lets pose-transform
1862
+ * actions (resize/move/nudge/flip — NOT rotate) ALSO rewrite a node's
1863
+ * data-held geometry. Given a node and the affine `m` applied to its pose,
1864
+ * `transform(node, m)` returns updated `data` (geometry mapped by `m`) or
1865
+ * `null` for nodes with no data-held geometry.
1866
+ *
1867
+ * Strictly opt-in: when absent (or when `transform` returns null), the kit
1868
+ * emits only the pose op and leaves `data` untouched. apps/draw wires this
1869
+ * to mirror `data.path` through `transformPath`. Rotate intentionally never
1870
+ * consults this seam (rotation lives on the pose, baked at render).
1871
+ */
1872
+ geometryProjection?: GeometryProjection;
1873
+ }
1874
+ /**
1875
+ * Every dep name the registry knows about — derived from {@link DepSchema} so
1876
+ * the two can't drift.
1877
+ *
1878
+ * Declared here rather than beside the registry so that this `keyof` reference
1879
+ * resolves to the exported `DepSchema` declaration; from another module it
1880
+ * resolves to that module's import alias, which the API docs can't link.
1881
+ */
1882
+ type DepName = keyof DepSchema;
1883
+
1884
+ interface DepRegistry {
1885
+ register<K extends DepName>(name: K, source: () => DepSchema[K]): () => void;
1886
+ get<K extends DepName>(name: K): DepSchema[K] | undefined;
1887
+ }
1888
+ declare function DepRegistryProvider({ children }: {
1889
+ children: ReactNode;
1890
+ }): react_jsx_runtime.JSX.Element;
1891
+ declare function useDepRegistry(): DepRegistry;
1892
+ /**
1893
+ * Like `useDepRegistry`, but returns `null` when no `<DepRegistryProvider>` is
1894
+ * in scope instead of throwing. Used by `useStandardActions` to preserve its
1895
+ * silent-no-op contract when neither provider is present.
1896
+ */
1897
+ declare function useOptionalDepRegistry(): DepRegistry | null;
1898
+ /** Register a live source for `name` for the lifetime of the calling
1899
+ * component. The `source` thunk is called at dispatch time and should
1900
+ * return the latest value. */
1901
+ declare function useDepSource<K extends DepName>(name: K, source: () => DepSchema[K]): void;
1902
+
1903
+ /**
1904
+ * GestureBinding — connects a GestureSpec to an Action id (with per-binding
1905
+ * options). Tools own arrays of these on their `bindings` field; ambient
1906
+ * gesture-bindings are registered globally.
1907
+ *
1908
+ * See `docs/superpowers/specs/2026-05-16-registry-unification-design.md`.
1909
+ */
1910
+
1911
+ interface GestureBinding {
1912
+ spec: GestureSpec;
1913
+ actionId: string;
1914
+ opts?: BindingOpts;
1915
+ }
1916
+
1917
+ /** Modifier-key snapshot at event dispatch time. `space` is included
1918
+ * because tools commonly use space as a hotkey-slot trigger and may
1919
+ * also want to read it as a flag mid-gesture. */
1920
+ interface ToolModifiers {
1921
+ alt: boolean;
1922
+ shift: boolean;
1923
+ meta: boolean;
1924
+ ctrl: boolean;
1925
+ space: boolean;
1926
+ }
1927
+ /** Per-event context passed to every channel handler. `scratch` is typed
1928
+ * via the tool's `TScratch` parameter; it survives across a single
1929
+ * gesture (pointer-down through end/cancel) and is replaced on next
1930
+ * gesture start by `initScratch()`. */
1931
+ interface ToolCtx<TScratch = unknown> {
1932
+ worldX: number;
1933
+ worldY: number;
1934
+ modifiers: ToolModifiers;
1935
+ selection: SelectionApi;
1936
+ /** Adapter/scene access — opaque at this layer; tools that need it
1937
+ * cast to a known shape. This layer doesn't constrain it. */
1938
+ adapter: unknown;
1939
+ applyOps: (ops: Op[], label: string) => void;
1940
+ /** Current viewport. Reflects camera-position semantics — see
1941
+ * `View` JSDoc. */
1942
+ view: View;
1943
+ /** Mutate the viewport. In controlled mode this calls the consumer's
1944
+ * `onViewChange`; in uncontrolled mode it updates Canvas's internal
1945
+ * state. View changes are not undoable. */
1946
+ setView: (next: View) => void;
1947
+ /** Bounding rect of the canvas element in viewport coords. Used by
1948
+ * zoom/pan tools to convert event clientX/clientY to canvas-relative
1949
+ * anchors. */
1950
+ canvasRect: DOMRect;
1951
+ /** Screen-space pointer coords relative to `canvasRect`. Useful for
1952
+ * viewport tools that pan/zoom in screen space (e.g. hand-pan
1953
+ * computes deltas in pixels, not world units). Optional — populated
1954
+ * by the dispatcher on pointer events; absent on keyboard events. */
1955
+ screenPoint?: {
1956
+ x: number;
1957
+ y: number;
1958
+ };
1959
+ /** Optional debug sink. When `<Canvas debug={...}>` is enabled, Canvas
1960
+ * threads its sink here so tool-internal hit math (handle hitboxes,
1961
+ * rotation handle, etc.) lands in the same overlay as Canvas's own
1962
+ * bounds/origin records. Tools should call this conditionally with `?.`. */
1963
+ debug?: DebugSink;
1964
+ scratch: TScratch;
1965
+ }
1966
+ /** Hotkey-slot trigger key. The slot is engaged while this key is held —
1967
+ * hence "hotkey": active as long as the key is hot. `null` (or omitted)
1968
+ * means the tool is not eligible for the hotkey slot. */
1969
+ type HotkeyTrigger = 'space' | 'alt' | 'ctrl' | 'meta' | 'shift';
1970
+ /** World-space AABB shape used by `previewBounds`. Alias of the kit-wide
1971
+ * `Bounds` type — the optional `rotation` field carries through so a tool
1972
+ * can report an oriented preview rect (e.g. mid-rotate). */
1973
+ type ToolBounds = Bounds;
1974
+ /** Presentation metadata for tool palettes / menus. Optional on every
1975
+ * tool — consumers that render a palette (`<ToolPalette>`) read these
1976
+ * fields to display the tool; consumers that don't can ignore them.
1977
+ *
1978
+ * Note: cursor is NOT here. The top-level `Tool.cursor` field below is
1979
+ * already plumbed through `<Canvas>` to `style.cursor` on the host. */
1980
+ interface ToolPresentation<TScratch = unknown> {
1981
+ /** Human-readable label, distinct from the `id`. Falls back to `id`. */
1982
+ label?: string;
1983
+ /** Inline-SVG icon component output. May be a static `ReactNode` or a
1984
+ * function of scratch state (rare; useful for shape-aware affordances). */
1985
+ icon?: React.ReactNode | ((scratch?: TScratch) => React.ReactNode);
1986
+ /** Palette grouping key. Tools sharing a group render contiguously
1987
+ * with separators between groups. Free-form string; the kit
1988
+ * recommends 'select' | 'shape' | 'draw' | 'type' | 'view'. */
1989
+ group?: string;
1990
+ /** Display override for the keyboard shortcut. When omitted the palette
1991
+ * derives one from `Tool.keybinding` via its own formatter. */
1992
+ shortcut?: string;
1993
+ }
1994
+ /** Full Tool record. */
1995
+ interface Tool<TScratch = unknown> {
1996
+ id: string;
1997
+ /**
1998
+ * App-level capability tags for modality. The `weasel-modes` package's
1999
+ * `eligibleForMode(mode, capabilities)` predicate consumes these to decide
2000
+ * whether the tool is usable in the active mode. Tags are extensible
2001
+ * strings — apps can define their own. Untagged tools are treated as
2002
+ * ineligible by all modes except those whose `allows` list includes
2003
+ * every implicit-or-declared tag (i.e. `normal` in the default preset).
2004
+ */
2005
+ capabilities?: CapabilityTag[];
2006
+ /**
2007
+ * Actions this tool owns and needs registered while it is in the tools
2008
+ * registry — e.g. polygon's `polygon.adjustSides`, which its own bindings
2009
+ * reference by id.
2010
+ *
2011
+ * Declared here rather than registered by the hook with `useAction`,
2012
+ * because tool hooks run wherever the consumer calls them — for
2013
+ * `<SceneCanvas>` that is ABOVE `<ActionsProviderIfRoot>`, where
2014
+ * `useActionsRegistry()` returns null and `useAction` silently no-ops. The
2015
+ * result was a binding pointing at an action id nothing had registered, so
2016
+ * the gesture fell through to whatever matched next (polygon's
2017
+ * wheel/arrow-key side adjustment did nothing and `nudge.*` moved the
2018
+ * selection instead). `<ToolActionsMounter>` registers these from inside
2019
+ * the provider.
2020
+ */
2021
+ actions?: Action[];
2022
+ /** Optional caller-supplied key. Most built-in tools have their activation
2023
+ * key declared in `BUILTIN_SELECT_KEYS` in `useKeybindings.ts`; this field
2024
+ * is for tools that want their activation key to be configurable by the
2025
+ * host (currently Lasso and Eyedropper). The dynamic loop in
2026
+ * `useKeybindings.ts` picks this up and appends a binding entry to the
2027
+ * consolidated `tool.activate` action (with `opts.params.toolId` set so
2028
+ * the invoker knows which tool to switch to). */
2029
+ keybinding?: ToolKeybinding;
2030
+ initScratch?: () => TScratch;
2031
+ onActivate?: (ctx: ToolCtx<TScratch>) => void;
2032
+ onDeactivate?: (ctx: ToolCtx<TScratch>) => void;
2033
+ cursor?: string | ((ctx: ToolCtx<TScratch>) => string);
2034
+ /** Presentation metadata for tool palettes. See `ToolPresentation`. */
2035
+ presentation?: ToolPresentation<TScratch>;
2036
+ /** Returns the in-flight preview pose for `id` if this tool is mid-gesture
2037
+ * on it; otherwise `null`. Lets `Canvas.helpersRef.getEffectivePose`
2038
+ * reflect live gesture state without reaching into hook internals. The
2039
+ * return type is `unknown` here because the Tool interface is pose-agnostic;
2040
+ * callers that know the pose shape (e.g. Canvas typed by `TPose`) cast at
2041
+ * the use site. */
2042
+ previewPose?: (id: string) => unknown;
2043
+ /** Returns the in-flight preview bounds for `id` if this tool is mid-gesture
2044
+ * on it; otherwise `null`. Optional companion to `previewPose` for tools that
2045
+ * can compute bounds without round-tripping through a geometry adapter. */
2046
+ previewBounds?: (id: string) => ToolBounds | null;
2047
+ /** Returns ids whose committed scene-render should be suppressed while this
2048
+ * tool is mid-gesture (e.g. cascade move's dragged + descendant ids whose
2049
+ * preview ghosts replace the committed pose). The standard scene slot
2050
+ * consults this alongside `previewPose` to avoid double-rendering. Returns
2051
+ * `null` when no gesture is in flight. */
2052
+ previewIds?: () => Iterable<string> | null;
2053
+ /** Optional overlay layer rendered on top of the scene/chrome whenever
2054
+ * this tool is in any active slot (active, hotkey, or ambient).
2055
+ * The layer's `draw` function reads from this tool's scratch via React
2056
+ * closure (re-evaluated each render). Return early from `draw` to render
2057
+ * nothing — typically gated on a scratch field like
2058
+ * `if (!scratch.overlay) return`. */
2059
+ overlay?: RenderLayer<unknown>;
2060
+ /** Declarative gesture bindings — the tool's entire input surface. The
2061
+ * gesture dispatcher consults these at active scope while this tool is
2062
+ * active, and at hotkey scope while it is held. See
2063
+ * `docs/superpowers/specs/2026-05-16-registry-unification-design.md`. */
2064
+ bindings?: GestureBinding[];
2065
+ /** Reflection escape hatch: when this `Tool` was produced by `defineTool`,
2066
+ * the source `ToolDef` is attached here so introspection consumers
2067
+ * (`buildRouteRegistry`, `findConflicts`, the toolkit-builder UI, the
2068
+ * reflection demo) can read the authored form — `hookName` in particular,
2069
+ * which the runtime `Tool` doesn't carry. Tools constructed without
2070
+ * `defineTool` may leave this undefined. Typed as `unknown` to keep this
2071
+ * file from importing the routing types — consumers cast at the use site. */
2072
+ def?: unknown;
2073
+ }
2074
+ /** Internal — which slot a tool occupies in the dispatch order. */
2075
+ type ToolSlot = 'hotkey' | 'active' | 'ambient';
2076
+ /** Internal alias for "a Tool of any scratch type" — used in registries and
2077
+ * dispatchers that hold tools of heterogeneous scratch shapes. `any` is
2078
+ * intentional: `Tool<TScratch>` is invariant in TScratch, so `Tool<unknown>`
2079
+ * is too strict for containers that accept any concrete `Tool<T>`. */
2080
+ type AnyTool = Tool<any>;
2081
+
2082
+ /**
2083
+ * Pure matcher primitives live in `@weasel-js/gestures`. This file
2084
+ * re-exports them for kit-internal consumers and layers the actions-layer
2085
+ * binding-scope / matchBest logic on top.
2086
+ */
2087
+
2088
+ type BindingScope = 'ambient' | 'active' | 'hotkey';
2089
+ interface ScopedBinding {
2090
+ binding: GestureBinding;
2091
+ scope: BindingScope;
2092
+ /** Tool id that owns this binding — `'&'`-channel phase atoms resolve
2093
+ * to this. `null` for ambient bindings that came from a registered
2094
+ * Action with no owning tool. */
2095
+ ownerToolId: string | null;
2096
+ }
2097
+ interface MatchResult {
2098
+ binding: GestureBinding;
2099
+ scope: BindingScope;
2100
+ /** Tool id that owns the binding — propagated from `ScopedBinding`
2101
+ * so the dispatcher can record it as the handle owner. */
2102
+ ownerToolId: string | null;
2103
+ }
2104
+ /** CSS-style specificity tuple for a GestureSpec. Higher tuple wins under
2105
+ * lexicographic compare. Dimensions, in order of precedence:
2106
+ *
2107
+ * [0] target — how much the spec's target narrows; see `targetRank`.
2108
+ * [1] mods — count of required modifier keys (shift/alt/ctrl/meta/mod).
2109
+ * `'optional'` does NOT count.
2110
+ * [2] phase — 1 if the spec declares a `phase` field, else 0.
2111
+ * [3] exact — per-kind tiebreak: 2 for a drop/paste spec with a
2112
+ * non-empty `types` MIME filter, else 1.
2113
+ *
2114
+ * Identical tuples fall back to registration order in the matcher's
2115
+ * stable sort, preserving the pre-specificity tiebreaker. */
2116
+ declare function specificity(spec: GestureSpec): readonly [number, number, number, number];
2117
+
2118
+ /**
2119
+ * Dispatcher orchestrator — pure module, no React, no DOM.
2120
+ *
2121
+ * Assembles `ScopedBinding[]` from the actions registry, active tool, and
2122
+ * hotkey stack; matches input events via `matchSorted`; gates each candidate
2123
+ * on `enabled()`; then invokes `immediate` or `ongoing` invokers and tracks
2124
+ * in-flight handles.
2125
+ *
2126
+ * ## Specificity-ordered fall-through
2127
+ * `matchSorted` returns every matching binding in precedence order
2128
+ * (hotkey > active > ambient, first-declared within scope). The dispatcher
2129
+ * walks that list and fires the first action whose `enabled()` returns
2130
+ * `true`. If every candidate's `enabled()` returns a disabled reason, the
2131
+ * event is unhandled. This mirrors CSS-style specificity matching with a
2132
+ * `:not(:disabled)` filter, and lets a tool declare a high-specificity
2133
+ * binding (e.g. drag-on-empty → areaSelect) that gracefully falls through
2134
+ * to a lower-specificity ambient binding (e.g. drag → viewport.dragPan)
2135
+ * when its required deps aren't wired.
2136
+ *
2137
+ * ## gestureId scheme
2138
+ * - `key-held` ongoing actions: `key-held-<key>` (e.g. `key-held- ` for Space).
2139
+ * Chosen because key-held gestures are identified by the held key alone.
2140
+ * - `pointerdown` / drag ongoing actions: `pointer-<pointerId>`, taken from
2141
+ * the originating DOM `PointerEvent`. Each physical pointer — mouse, each
2142
+ * touch, the stylus — gets its own handle slot. Events with no
2143
+ * `pointerId` (synthesized probes, programmatic drags, most tests) key to
2144
+ * `pointer-mouse`, so a single synthetic pointer behaves as it always has.
2145
+ * - `multitouch` ongoing actions: `multitouch-<fingers>`.
2146
+ * - Fallback for any other kind that triggers an ongoing invoker: `ongoing-<kind>`.
2147
+ *
2148
+ * ## Action-lookup miss behavior
2149
+ * When `matchBest` resolves a binding whose `actionId` has no entry in
2150
+ * `ctx.actions.list()`, the dispatcher emits `console.warn` and returns
2151
+ * `'unhandled'`. The user's input gesture falls through as if unmatched.
2152
+ * This preserves input flow (nothing is swallowed silently) while flagging
2153
+ * the misconfiguration at dev time.
2154
+ */
2155
+
2156
+ interface DispatcherContext {
2157
+ /** All registered actions; the dispatcher walks `.defaultBinding` for ambient bindings. */
2158
+ actions: ActionsRegistry;
2159
+ /** Dep sources keyed by name. */
2160
+ depRegistry: DepRegistry;
2161
+ /** Active tool's id (from ActiveToolContext). */
2162
+ activeToolId: string;
2163
+ /** Held-hotkey stack, top of stack last. */
2164
+ hotkeyStack: readonly string[];
2165
+ /**
2166
+ * Ids of always-on tools. Their bindings are assembled at AMBIENT scope, so
2167
+ * they lose to the active tool on a tie — which is what "always listening,
2168
+ * never in the way" needs. Chrome that floats over the scene lives here:
2169
+ * `@weasel-js/hud`'s tool is the worked example.
2170
+ *
2171
+ * Without this an ambient tool's `bindings` were assembled nowhere at all:
2172
+ * the walk covered hotkey and active tools plus actions' `defaultBinding`,
2173
+ * and an ambient tool is in neither set.
2174
+ */
2175
+ ambientToolIds?: readonly string[];
2176
+ /** Lookup for tool definitions. */
2177
+ toolsById: ReadonlyMap<string, Tool>;
2178
+ /** Platform flag for `mod` shorthand resolution. */
2179
+ isMac: boolean;
2180
+ /**
2181
+ * Thunk returning a fresh `RuleCtx` for the current frame. When
2182
+ * supplied, the dispatcher filters matched candidates by their
2183
+ * declared `Action.eligible` rule (omitted => always eligible).
2184
+ * When omitted, no eligibility filtering is applied — preserves
2185
+ * backward compatibility for callers (tests, legacy harnesses) that
2186
+ * don't wire up chrome-caps state.
2187
+ */
2188
+ getRuleCtx?: () => RuleCtx;
2189
+ }
2190
+ /**
2191
+ * Handle returned by `Dispatcher.beginUiOngoing()` for driving an
2192
+ * ongoing invoker from a UI control (color picker, slider).
2193
+ *
2194
+ * - `update(params)` rebuilds an `InvocationCtx` with the new params and
2195
+ * calls the handle's `onMove`. Safe to call many times.
2196
+ * - `end(reason)` calls `onEnd(ctx, reason)` once and removes the handle
2197
+ * from the in-flight map. Idempotent — further calls are no-ops.
2198
+ */
2199
+ interface UiOngoingControl {
2200
+ readonly gestureId: string;
2201
+ update(params?: Record<string, unknown>): void;
2202
+ end(reason: 'commit' | 'cancel'): void;
2203
+ }
2204
+ /**
2205
+ * Successful `Dispatcher.resolveOnly` prediction: the binding + action that
2206
+ * would fire if `event` were dispatched for real. `action` is the resolved
2207
+ * descriptor so callers (the hover-cursor pump) can read metadata like
2208
+ * `Action.cursor` without a second registry lookup.
2209
+ */
2210
+ interface ResolveOnlyResult {
2211
+ actionId: string;
2212
+ action: Action;
2213
+ scope: BindingScope;
2214
+ /** Tool id owning the winning binding; `null` for ambient action bindings. */
2215
+ ownerToolId: string | null;
2216
+ }
2217
+ /**
2218
+ * One candidate from `Dispatcher.resolveAll` — a binding that matched the
2219
+ * event, with why it did or didn't get to fire.
2220
+ *
2221
+ * Verdicts:
2222
+ * - `would-fire` — eligible, `enabled()` passed, and nothing above it fired.
2223
+ * At most one candidate per call carries this.
2224
+ * - `ineligible` — the action's `eligible` rule evaluated false against the
2225
+ * live `RuleCtx`. `reason` is the rule, serialized.
2226
+ * - `disabled` — `enabled()` returned a disabled reason, carried verbatim.
2227
+ * - `shadowed` — never asked, for one of two reasons: something above it
2228
+ * already fired, or it is a repeat binding of the action that itself won
2229
+ * higher in the list (several bindings may point at one action, and the
2230
+ * dispatcher runs each action at most once). A repeat of an action that was
2231
+ * already judged `ineligible` or `disabled` is NOT shadowed — it inherits
2232
+ * that action's verdict, since that is the reason it doesn't fire.
2233
+ */
2234
+ interface ResolvedCandidate {
2235
+ actionId: string;
2236
+ action: Action;
2237
+ binding: GestureBinding;
2238
+ scope: BindingScope;
2239
+ ownerToolId: string | null;
2240
+ /** The tuple from `specificity(binding.spec)`, surfaced so a reader can see
2241
+ * why one candidate outranks another rather than inferring it. */
2242
+ specificity: readonly [number, number, number, number];
2243
+ verdict: {
2244
+ kind: 'would-fire';
2245
+ } | {
2246
+ kind: 'ineligible';
2247
+ reason: string;
2248
+ } | {
2249
+ kind: 'disabled';
2250
+ reason: string;
2251
+ } | {
2252
+ kind: 'shadowed';
2253
+ };
2254
+ }
2255
+ /** Options for {@link Dispatcher.resolveAll}. */
2256
+ interface ResolveAllOptions {
2257
+ /**
2258
+ * Evaluate eligibility and `enabled()` for candidates below the winner
2259
+ * instead of short-circuiting them to `shadowed`.
2260
+ *
2261
+ * Off by default, and deliberately so: the default walk's early exit is what
2262
+ * keeps `resolveOnly`'s `enabled()` call count identical to a real dispatch,
2263
+ * and `enabled()` predicates are only contractually pure — not free.
2264
+ *
2265
+ * Turn it on for diagnostics, where "this one was outranked" is a less
2266
+ * useful answer than "this one was outranked AND would have been disabled
2267
+ * anyway". With it on, `shadowed` narrows to its precise meaning: this
2268
+ * candidate would have fired, but something above it did.
2269
+ */
2270
+ evaluateShadowed?: boolean;
2271
+ }
2272
+ interface Dispatcher {
2273
+ /**
2274
+ * Route an input event through the binding pipeline. Returns `'handled'`
2275
+ * when a binding matched and the action invoked successfully (whether it
2276
+ * returned ops or not). Returns `'unhandled'` when no binding matched or
2277
+ * the matched action's `enabled()` returned a disabled reason.
2278
+ */
2279
+ handleInput(event: InputEvent, ctx: DispatcherContext): 'handled' | 'unhandled';
2280
+ /**
2281
+ * Predict which action `event` would route to WITHOUT invoking it. Replays
2282
+ * the same walk as `handleInput` — scope assembly, specificity-sorted
2283
+ * match, eligibility filter, per-candidate `enabled()` gate — and returns
2284
+ * the first candidate that would fire, or `null` when the event would go
2285
+ * unhandled. Pure query: no invoker runs, no in-flight state changes, no
2286
+ * trace-log entry.
2287
+ *
2288
+ * Known divergence from a real dispatch: an ongoing invoker that matches
2289
+ * but returns an empty handle at `start()` (runtime bail) makes the real
2290
+ * dispatch fall through to the next candidate; prediction cannot see that
2291
+ * and reports the bailing action. Keep `enabled()` accurate on actions
2292
+ * that rely on prediction (hover cursors).
2293
+ */
2294
+ resolveOnly(event: InputEvent, ctx: DispatcherContext): ResolveOnlyResult | null;
2295
+ /**
2296
+ * Every binding that matches `event`, in dispatch precedence order, each
2297
+ * with a verdict explaining whether it would fire. Same walk as
2298
+ * `resolveOnly` — scope assembly, specificity-sorted match, eligibility
2299
+ * check, per-candidate `enabled()` gate — without stopping at the winner
2300
+ * and without invoking anything. Nothing is dropped: candidates that
2301
+ * `resolveOnly`'s walk would filter out are kept here and labelled
2302
+ * `ineligible` instead. Pure query: no invoker runs, no in-flight state
2303
+ * changes, no trace-log entry.
2304
+ *
2305
+ * `resolveOnly` is the first `would-fire` entry of this list.
2306
+ *
2307
+ * Shares `resolveOnly`'s known divergence from a real dispatch: an ongoing
2308
+ * invoker that matches but returns an empty handle at `start()` makes the
2309
+ * real dispatch fall through, and this cannot see that.
2310
+ *
2311
+ * By default everything below the winner is `shadowed` without being asked,
2312
+ * which is what keeps this walk as cheap as the dispatch it replays. Pass
2313
+ * `{ evaluateShadowed: true }` to keep evaluating past the winner, so a
2314
+ * lower candidate that is ALSO ineligible or disabled says so — see
2315
+ * {@link ResolveAllOptions.evaluateShadowed}.
2316
+ */
2317
+ resolveAll(event: InputEvent, ctx: DispatcherContext, opts?: ResolveAllOptions): ResolvedCandidate[];
2318
+ /**
2319
+ * Synthesize an end-of-gesture for every in-flight ongoing handle.
2320
+ * Used by tool-switch cancellation (Q2 decision).
2321
+ */
2322
+ cancelAll(reason: 'commit' | 'cancel'): void;
2323
+ /**
2324
+ * Read-only view of currently in-flight ongoing handles, keyed by gestureId.
2325
+ * For debug/testing.
2326
+ */
2327
+ inFlight(): ReadonlyMap<string, OngoingHandle>;
2328
+ /**
2329
+ * CSS cursor for the gesture currently in flight, or `null` when nothing
2330
+ * is. Reads `Action.activeCursor` (falling back to `Action.cursor`) off the
2331
+ * action whose handle is open — the hover pump applies this instead of its
2332
+ * prediction once a gesture starts, which is how `grab` becomes `grabbing`.
2333
+ */
2334
+ inFlightCursor(): string | null;
2335
+ /**
2336
+ * Read-only iterator over currently in-flight `OngoingHandle` instances.
2337
+ *
2338
+ * Surface for the canvas's preview-ghost layer (`usePreviewGhostLayer`)
2339
+ * to walk each handle's `previewIds()` / `previewPose(id)` and render
2340
+ * dispatcher-driven gesture previews. Read-only by design:
2341
+ * external consumers must not mutate the in-flight map.
2342
+ */
2343
+ getInFlightHandles(): Iterable<OngoingHandle>;
2344
+ /**
2345
+ * Subscribe to in-flight state changes. The callback fires after every
2346
+ * mutation that affects what the preview-ghost / dispatcher-overlay
2347
+ * layers read — handle start, every `onMove` pump, end, cancel,
2348
+ * cancel-all. Consumers re-read `getInFlightHandles()` and re-render.
2349
+ *
2350
+ * Returns an unsubscribe function.
2351
+ */
2352
+ subscribe(fn: () => void): () => void;
2353
+ /**
2354
+ * Monotonic counter bumped on exactly the events {@link subscribe} fires
2355
+ * on. The snapshot half of the `useSyncExternalStore` contract: pair it
2356
+ * with `subscribe` to drive a render off in-flight gesture state without
2357
+ * a `useReducer` force-rerender.
2358
+ *
2359
+ * Starts at 0 and only ever increases. Two reads returning the same number
2360
+ * mean nothing pumped in between; it does **not** guarantee that a bump
2361
+ * changed anything observable (a pump that matched no binding still
2362
+ * counts — see `subscribe`).
2363
+ */
2364
+ getVersion(): number;
2365
+ /**
2366
+ * Snapshot of the currently active action, for surfaces (chrome-caps
2367
+ * visibility rules, debug HUDs) that need to react to "what action
2368
+ * is in flight right now."
2369
+ *
2370
+ * - `kind` — the `OngoingHandle.kind` reported by the in-flight
2371
+ * handle (e.g. `'marquee'`, `'move'`). `null` when no action is
2372
+ * in flight OR the handle didn't declare a kind.
2373
+ * - `id` — the dispatcher's internal `gestureId` (`pointer-1`,
2374
+ * `key-held-Space`, …) — the pointer/key channel the action rode
2375
+ * in on. `null` when no action is in flight.
2376
+ *
2377
+ * When multiple handles are in flight simultaneously (e.g. a key-held
2378
+ * action overlapping a pointer action), the most-recently-started
2379
+ * handle wins. This matches user intent: the latest interaction is
2380
+ * the one consumers care about.
2381
+ *
2382
+ * That rule used to be near-vacuous on the pointer side, because every
2383
+ * pointer shared one handle slot and two pointer drags could not coexist.
2384
+ * With per-pointer keying they can — but only via paths that bypass the
2385
+ * multi-pointer policy in `useGestureDispatcher` (which stops a second
2386
+ * finger from opening a drag while a pinch is live), such as a mouse and
2387
+ * a pen used together. Latest-start remains the right answer there.
2388
+ */
2389
+ getActiveAction(): {
2390
+ kind: string | null;
2391
+ id: string | null;
2392
+ };
2393
+ /**
2394
+ * Start an ongoing action driven by UI (not a gesture). Builds an
2395
+ * `InvocationCtx` with the given `deps` and `params`, calls
2396
+ * `action.invoker.start(ctx, { params })`, and registers the returned
2397
+ * handle in the in-flight map so `getInFlightHandles()` reports it —
2398
+ * enabling preview rendering via `SceneCanvas`.
2399
+ *
2400
+ * Returns `null` if `actionId` is unknown, the action's invoker is not
2401
+ * ongoing, or `start` returned an empty handle.
2402
+ *
2403
+ * If a UI-driven handle for the same `actionId` is already in flight,
2404
+ * it is committed (`end('commit')`) before the new one starts.
2405
+ */
2406
+ beginUiOngoing(actionId: string, deps: ActionDeps, params?: Record<string, unknown>): UiOngoingControl | null;
2407
+ }
2408
+ declare function createDispatcher(opts?: {
2409
+ getAction?: (id: string) => Action | undefined;
2410
+ }): Dispatcher;
2411
+
2412
+ /**
2413
+ * @experimental
2414
+ * A single entry in `Action.defaultBinding[]`. Either a bare `GestureSpec`
2415
+ * (no per-binding opts) or an object form that pairs a spec with
2416
+ * `BindingOpts` for parametric actions (e.g. `{ params: { axis: 'x' } }`).
2417
+ * Use the object form when two bindings for the same action differ only in
2418
+ * a runtime parameter — the dispatcher extracts `opts.params` and passes
2419
+ * them to `ImmediateInvoker.run` as its second argument.
2420
+ */
2421
+ type BoundGesture = GestureSpec | {
2422
+ spec: GestureSpec;
2423
+ opts: BindingOpts;
2424
+ };
2425
+ /**
2426
+ * @experimental
2427
+ * Single registered action. v1: one binding per action.
2428
+ */
2429
+ interface Action {
2430
+ id: string;
2431
+ label: string;
2432
+ /** The gesture-spec form of the binding, read by the gesture dispatcher.
2433
+ * May be a single `GestureSpec`, a bare `GestureSpec[]` (any-of semantics),
2434
+ * or a `BoundGesture[]` where each entry is either a bare `GestureSpec` or
2435
+ * `{ spec, opts }` — use the object form for parametric actions where two
2436
+ * bindings for the same action differ only by `opts.params` (e.g. `flip`
2437
+ * with `axis: 'x'` vs `'y'`). The dispatcher extracts `opts.params` and
2438
+ * passes them to `ImmediateInvoker.run` as its second argument. */
2439
+ defaultBinding?: GestureSpec | BoundGesture[];
2440
+ /** Names of the deps this action's invoker reads (keys of `DepSchema`).
2441
+ * The dispatcher (and `trigger`, when `requires` is present) resolves
2442
+ * each name against the `DepRegistry` at invocation time and passes the
2443
+ * resulting bag to the invoker. Dev builds warn when the invoker reads a
2444
+ * dep it didn't declare here — see `buildDepsFromRequires`. */
2445
+ requires?: readonly DepName[];
2446
+ /** Inline-SVG icon for palette / toolbar surfaces. Mirrors
2447
+ * `ToolPresentation.icon` so a generic `<ActionBar>` can render from
2448
+ * action metadata the same way `<ToolPalette>` renders from tool
2449
+ * metadata. May be a static `ReactNode` or a function (rare; useful
2450
+ * for state-aware icons like a "lock" toggle). */
2451
+ icon?: ReactNode | (() => ReactNode);
2452
+ /** Grouping key for palette/menu surfaces. Free-form string; the kit
2453
+ * ships defaults for `'align'` (six edges/centers), `'distribute'`
2454
+ * (two axes), and recommends `'pathfinder'` for boolean ops. */
2455
+ group?: string;
2456
+ /** Display override for the keyboard shortcut. When omitted, palette
2457
+ * surfaces derive a label from `defaultBinding` via their own
2458
+ * formatter. */
2459
+ shortcut?: string;
2460
+ /** Pluggable invocation strategy. The gesture dispatcher routes matched
2461
+ * bindings through `invoker.start` / `invoker.run` depending on timing.
2462
+ * All kit-standard descriptors ship one; consumer-supplied actions
2463
+ * without an invoker can still register but won't be triggered. */
2464
+ invoker?: Invoker;
2465
+ /** When set to `'hotkey'`, this action's `defaultBinding` rides the hotkey
2466
+ * `BindingScope` instead of the ambient scope — meaning it beats any
2467
+ * active-tool binding on the same input shape. Use for tool-switch
2468
+ * shortcuts and global held-key triggers. Default: ambient. */
2469
+ scope?: 'hotkey';
2470
+ /**
2471
+ * @experimental
2472
+ * Optional predicate the command palette consults when rendering. Return
2473
+ * `true` when the action is currently triggerable. Return a reason string
2474
+ * (e.g. `'Selection required'`) when disabled — the palette greys out
2475
+ * the row, skips it in keyboard nav, ignores clicks, and shows the
2476
+ * reason next to the label. Keystroke dispatch (the registered binding)
2477
+ * is unaffected; the action's own `run` should self-guard.
2478
+ *
2479
+ * **Contract:** must be pure (no side effects), fast (< 4ms in dev), and
2480
+ * must not throw. If a call throws or exceeds the budget in dev mode,
2481
+ * `evaluateEnabled` logs a one-time warning per action id; throws are
2482
+ * caught and treated as disabled with reason `'(predicate threw)'`.
2483
+ *
2484
+ * Snapshot-on-open semantics: the palette evaluates `enabled` once when
2485
+ * opened and does NOT re-evaluate on selection changes while open. Live
2486
+ * reactive updates are deferred — palette is short-lived.
2487
+ *
2488
+ * The reason set is a closed enum — to add a new reason, edit
2489
+ * `ActionDisabledReason` and the consumer's display map.
2490
+ *
2491
+ * The optional `deps` argument is the same bag passed to
2492
+ * `ImmediateInvoker.run`; callers (`evaluateEnabled` / the ActionBar) may
2493
+ * synthesize it from the surrounding `DepRegistry` so predicates can
2494
+ * inspect selection / scene / etc. Predicates that don't need deps just
2495
+ * ignore the arg.
2496
+ */
2497
+ enabled?: (deps?: ActionDeps) => true | ActionDisabledReason;
2498
+ /**
2499
+ * Declarative eligibility rule, evaluated against the current
2500
+ * `RuleCtx` by the dispatcher before invoking `start()`. Omitted =
2501
+ * always eligible.
2502
+ *
2503
+ * Accepts either a fluent `Condition` (callable with `.rule`) or a
2504
+ * raw `Rule` tree; the dispatcher normalizes via `.rule` unwrap.
2505
+ *
2506
+ * Prefer `capability:`-based rules (e.g. `{ capability: 'transforms-selection' }`)
2507
+ * over `mode:` rules — capability rules survive new modes being added
2508
+ * that allow the same capability.
2509
+ */
2510
+ eligible?: Rule | Condition;
2511
+ /**
2512
+ * CSS cursor shown while the pointer hovers a spot where this action
2513
+ * would win the drag. The hover-cursor pump (in `useGestureDispatcher`)
2514
+ * runs `Dispatcher.resolveOnly` on each idle pointermove — the same
2515
+ * match walk a real pointerdown takes — and applies the winning
2516
+ * action's `cursor`, so the hint and the actual click target stay in
2517
+ * sync by construction. Omitted = no override (the active tool's
2518
+ * `Tool.cursor` shows). Affordance hits are resolved earlier in the
2519
+ * pump via `AffordanceRegion.cursor` and never reach this field.
2520
+ *
2521
+ * Static string only. Prediction runs `enabled()` but cannot run the
2522
+ * invoker, so an action that matches yet bails at `start()` (empty
2523
+ * handle) may still show its cursor — keep `enabled` accurate for
2524
+ * actions that declare one.
2525
+ */
2526
+ cursor?: string;
2527
+ /**
2528
+ * CSS cursor shown while THIS action's ongoing handle is in flight —
2529
+ * grabbing while panning, `move` while dragging a selection, `crosshair`
2530
+ * while pulling a marquee.
2531
+ *
2532
+ * Separate from `cursor` because the two answer different questions:
2533
+ * `cursor` is a prediction ("a drag from here would pan"), this is a state
2534
+ * ("you are panning"). An action can declare either, both, or neither;
2535
+ * with only `cursor` set, the hover hint holds for the duration of the
2536
+ * gesture.
2537
+ *
2538
+ * This is where mid-gesture cursors live now. They used to come from the
2539
+ * tool side — `ViewportToolDef.engaged.cursor` for a phase-gated string,
2540
+ * or a function-form `Tool.cursor` reading the gesture scratch out of the
2541
+ * tool-routing dispatcher. Both belonged to a pipeline whose whole job was
2542
+ * being taken over by bindings, and neither could describe a cursor for an
2543
+ * action a tool doesn't own.
2544
+ */
2545
+ activeCursor?: string;
2546
+ }
2547
+ /**
2548
+ * @experimental
2549
+ * Closed enum of reasons an action might report itself as disabled. The
2550
+ * consumer (palette, menu, etc.) maps these symbolic values to display
2551
+ * strings via its own label map — see `demo/CommandPalette.tsx` for the
2552
+ * canonical mapping.
2553
+ */
2554
+ declare const ActionDisabledReason: {
2555
+ readonly SelectionRequired: "selection-required";
2556
+ readonly SceneEmpty: "scene-empty";
2557
+ readonly NotApplicable: "not-applicable";
2558
+ /** Sentinel: the predicate threw. Surfaced by `evaluateEnabled`'s catch. */
2559
+ readonly PredicateThrew: "predicate-threw";
2560
+ };
2561
+ type ActionDisabledReason = (typeof ActionDisabledReason)[keyof typeof ActionDisabledReason];
2562
+ /**
2563
+ * @experimental
2564
+ * Result of evaluating an Action's `enabled` predicate.
2565
+ */
2566
+ interface ActionEnabledResult {
2567
+ enabled: boolean;
2568
+ reason?: ActionDisabledReason;
2569
+ }
2570
+ declare function evaluateEnabled(action: Action, deps?: ActionDeps): ActionEnabledResult;
2571
+ /**
2572
+ * @experimental
2573
+ * Partial override or full descriptor passed via `<SceneCanvas actions={...}>`.
2574
+ * `null` disables a default at this id.
2575
+ */
2576
+ type ActionEntry = null | Partial<Action> | Action;
2577
+ /**
2578
+ * @experimental
2579
+ * Shape of the `actions` prop on `<SceneCanvas>`. `null` disables all defaults.
2580
+ */
2581
+ type ActionsProp = null | Record<string, ActionEntry>;
2582
+ /**
2583
+ * @experimental
2584
+ * Imperative API exposed by `useActionsRegistry()`.
2585
+ */
2586
+ interface ActionsRegistry {
2587
+ register(action: Action): () => void;
2588
+ unregister(id: string): void;
2589
+ list(): readonly Action[];
2590
+ /** Fire an immediate-invoker action by id. The optional `params` arg is
2591
+ * forwarded to `ImmediateInvoker.run` as its second argument — use it for
2592
+ * parametric actions (e.g. `trigger('tool.activate', { toolId: 'rect' })`).
2593
+ * Ongoing-invoker actions are not reachable from `trigger`. */
2594
+ trigger(id: string, params?: Record<string, unknown>): boolean;
2595
+ /**
2596
+ * Subscribe to registry mutations. The callback fires after any
2597
+ * `register`/`unregister` that changes the version. Returns an
2598
+ * unsubscribe function. Designed for `useSyncExternalStore`-driven
2599
+ * surfaces (e.g. `<ActionBar>` in `@weasel-js/ui`) that need to
2600
+ * re-render when the action set changes.
2601
+ */
2602
+ subscribe(listener: () => void): () => void;
2603
+ /**
2604
+ * Start an ongoing action driven by UI (color picker, opacity slider).
2605
+ * Returns a control object with `update(params)` and `end(reason)`.
2606
+ *
2607
+ * Returns `null` if no dispatcher is wired into this registry, the
2608
+ * action is unknown, or its invoker is not ongoing.
2609
+ *
2610
+ * See `Dispatcher.beginUiOngoing` for full semantics including
2611
+ * auto-commit when a prior UI handle for the same action is in flight.
2612
+ */
2613
+ begin(id: string, params?: Record<string, unknown>): UiOngoingControl | null;
2614
+ /** Wire a dispatcher into the registry so `begin()` can delegate to it.
2615
+ * Call with `null` to detach. Idempotent. */
2616
+ setDispatcher(d: Dispatcher | null): void;
2617
+ /** Wire a `DepRegistry` into the registry so `trigger()` / `begin()` can
2618
+ * resolve action deps even when this provider is mounted ABOVE the dep
2619
+ * registry (e.g. a consumer's root `<ActionsProvider>` reused by
2620
+ * SceneCanvas's `ActionsProviderIfRoot`). Takes precedence over the dep
2621
+ * registry read from context at the provider's own level. Call with
2622
+ * `null` to detach. */
2623
+ setDepRegistry(r: DepRegistry | null): void;
2624
+ }
2625
+ /**
2626
+ * @experimental
2627
+ * Mounts an `ActionsRegistry` for its lifetime. Children call
2628
+ * `useActionsRegistry()` or `useAction()` to participate. Mounts no input
2629
+ * listener of its own — the gesture dispatcher owns input.
2630
+ */
2631
+ declare function ActionsProvider({ children }: {
2632
+ children: ReactNode;
2633
+ }): ReactElement;
2634
+ /**
2635
+ * @experimental
2636
+ * Returns the parent `ActionsRegistry`, or `null` when no provider is in scope.
2637
+ */
2638
+ declare function useActionsRegistry(): ActionsRegistry | null;
2639
+ /**
2640
+ * @experimental
2641
+ * Register an `Action` for the lifetime of the calling component. No-op when
2642
+ * no `ActionsProvider` is in scope. Re-registers on `action` reference change
2643
+ * (consumers should memoize stable identities to avoid churn).
2644
+ */
2645
+ declare function useAction(action: Action): void;
2646
+
2647
+ /**
2648
+ * Configurable activation-key descriptor for tools that expose their
2649
+ * keybinding to the host (currently Lasso and Eyedropper). Captures
2650
+ * only the fields meaningful to a caller-supplied tool-select key —
2651
+ * dispatcher-internal fields (`skipInEditable`, `enabled`,
2652
+ * `preventDefault`) live on `KeyBinding` in keyHelpers.ts and are
2653
+ * not part of the configurable surface.
2654
+ */
2655
+ interface ToolKeybinding {
2656
+ /** Key or list of keys to match (case-insensitive against `event.key`). */
2657
+ key: string | readonly string[];
2658
+ /** Require Cmd (mac) / Ctrl (others). Default `false`. */
2659
+ mod?: boolean;
2660
+ /** Require Alt. Default `false`. */
2661
+ alt?: boolean;
2662
+ /**
2663
+ * Shift policy. `undefined`/`false` forbids shift, `true` requires
2664
+ * shift, `'optional'` allows either.
2665
+ */
2666
+ shift?: boolean | 'optional';
2667
+ }
2668
+ interface ToolDef<TScratch = void> {
2669
+ id: string;
2670
+ /** Capability tags for modality eligibility. Forwarded onto `Tool.capabilities`. */
2671
+ capabilities?: CapabilityTag[];
2672
+ /**
2673
+ * Actions this tool owns and needs registered while it is in the tools
2674
+ * registry — e.g. polygon's `polygon.adjustSides`, which its own bindings
2675
+ * reference by id.
2676
+ *
2677
+ * Declared here rather than registered by the hook with `useAction`,
2678
+ * because tool hooks run wherever the consumer calls them — for
2679
+ * `<SceneCanvas>` that is ABOVE `<ActionsProviderIfRoot>`, where
2680
+ * `useActionsRegistry()` returns null and `useAction` silently no-ops. The
2681
+ * result was a binding pointing at an action id nothing had registered, so
2682
+ * the gesture fell through to whatever matched next (polygon's
2683
+ * wheel/arrow-key side adjustment did nothing and `nudge.*` moved the
2684
+ * selection instead). `<ToolActionsMounter>` registers these from inside
2685
+ * the provider.
2686
+ */
2687
+ actions?: Action[];
2688
+ /** Hook name as exported from the kit barrel (e.g. `'useHandTool'`).
2689
+ * Set by built-in hooks for inspector / debugging. Consumer-authored
2690
+ * tools may set this to surface their hook name; omitted is fine.
2691
+ * Introspection-only — do not make this load-bearing in production.
2692
+ * Read off the def via `Tool.def` (the reflection escape hatch). */
2693
+ hookName?: string;
2694
+ presentation?: ToolPresentation<TScratch>;
2695
+ /** Optional caller-supplied activation key. Most built-in tools have their
2696
+ * activation key declared in `BUILTIN_SELECT_KEYS` in `useKeybindings.ts`;
2697
+ * this field is for tools that want their activation key to be
2698
+ * configurable by the host (currently Lasso and Eyedropper). The dynamic
2699
+ * loop in `useKeybindings.ts` picks this up and appends a binding entry
2700
+ * to the consolidated `tool.activate` action (with `opts.params.toolId`
2701
+ * set so the invoker knows which tool to switch to). */
2702
+ keybinding?: ToolKeybinding;
2703
+ /** Declarative held-key trigger (reflection / inspector only). When set,
2704
+ * signals to the host that this tool can engage via a held key; the host
2705
+ * must register the activation via the consolidated `tool.offhand` action
2706
+ * (`makeToolOffhandAction` + `buildToolOffhandBindings`). Built-in tools
2707
+ * declare held keys in `BUILTIN_OFFHAND_ACTIONS`; configurable-hotkey
2708
+ * tools rely on the host to wire the binding. Setting this field does NOT
2709
+ * automatically engage the held-key behavior. */
2710
+ hotkey?: HotkeyTrigger;
2711
+ onActivate?: (ctx: ToolCtx<TScratch>) => void;
2712
+ onDeactivate?: (ctx: ToolCtx<TScratch>) => void;
2713
+ cursor?: string | ((ctx: ToolCtx<TScratch>) => string);
2714
+ /** Override the default scratch initializer. Default is `() => null`
2715
+ * cast to `TScratch`, which works for tools whose scratch is fresh
2716
+ * every gesture. Tools that need scratch identity to survive across
2717
+ * gesture boundaries (e.g. the pen tool's multi-click subpath state)
2718
+ * pass a stable-ref-returning thunk here. The factory forwards this
2719
+ * onto the returned `Tool.initScratch`. */
2720
+ initScratch?: () => TScratch;
2721
+ /** Declarative gesture bindings, forwarded onto `Tool.bindings`. The
2722
+ * gesture dispatcher consults these at active scope while this tool is the
2723
+ * active one, and at hotkey scope while it is held. This is the tool's
2724
+ * entire input surface — the `initial` / `engaged` phase tables that used
2725
+ * to sit beside it are gone, along with the second dispatcher that read
2726
+ * them. */
2727
+ bindings?: GestureBinding[];
2728
+ /** Optional overlay layer rendered while the tool occupies any slot
2729
+ * (active, hotkey, or ambient), surfaced on `Tool.overlay`.
2730
+ *
2731
+ * The layer's `draw` closure should read dynamic state through refs or
2732
+ * closures captured in the enclosing render scope, and gate on it there —
2733
+ * `if (!scratch.something) return []` — rather than expecting the kit to
2734
+ * swap layers as the gesture progresses. */
2735
+ overlay?: RenderLayer<unknown>;
2736
+ }
2737
+ /** Viewport-tool spec. Once phase tables went away this stopped differing
2738
+ * from `ToolDef` in any structural way; `defineViewportTool` survives as the
2739
+ * authoring signal that a tool pans/zooms the view rather than the scene. */
2740
+ type ViewportToolDef<TScratch = void> = ToolDef<TScratch>;
2741
+
2742
+ /**
2743
+ * Build a `Tool<TScratch>` from a declarative `ToolDef<TScratch>`.
2744
+ *
2745
+ * This used to be a translator: `ToolDef` carried `initial` / `engaged` phase
2746
+ * tables of hit-keyed route handlers, and `defineTool` compiled them into the
2747
+ * imperative `pointer` / `drag` / `keyboard` / `wheel` handlers the
2748
+ * tool-routing dispatcher called. Both ends of that are gone — tools declare
2749
+ * `bindings` and the gesture dispatcher routes them — so what remains is
2750
+ * identity plumbing plus the id check and the cursor resolver.
2751
+ *
2752
+ * It stays a function rather than becoming a spread because the id validation
2753
+ * and the `initScratch` / `cursor` defaults are worth applying uniformly, and
2754
+ * because `Tool.def` gives reflection a handle on the authored form.
2755
+ */
2756
+ declare function defineTool<TScratch = void>(def: ToolDef<TScratch>): Tool<TScratch>;
2757
+
2758
+ /**
2759
+ * Define a tool that acts on the viewport rather than the scene.
2760
+ *
2761
+ * This used to do real work: `ViewportPhaseDef` was a narrowed `PhaseDef`
2762
+ * (no click routes, drag restricted to the function form), and the factory
2763
+ * lifted it back to the permissive shape before handing it to `defineTool`.
2764
+ * With phase tables gone there is no shape left to narrow — a viewport tool
2765
+ * declares `bindings` like any other, pointing at `viewport.*` actions.
2766
+ *
2767
+ * It survives as an authoring signal. `defineViewportTool` at the top of a
2768
+ * hook says "this tool moves the camera, not the drawing", which is worth
2769
+ * more than the type gymnastics it replaced.
2770
+ */
2771
+ declare function defineViewportTool<TScratch = void>(def: ViewportToolDef<TScratch>): Tool<TScratch>;
2772
+
2773
+ /**
2774
+ * One row in the route registry — a single `GestureBinding` on one tool,
2775
+ * flattened into the route grammar's vocabulary so the inspector, the
2776
+ * conflict checker, and `describeRoute` can all read the same shape.
2777
+ *
2778
+ * Multiple rows can share (gesture, arg, target, modifiers) if different tools
2779
+ * declare them; consumers walk the list and group client-side.
2780
+ */
2781
+ interface RegistryEntry {
2782
+ toolId: string;
2783
+ /** Which phase the binding's `phase` spec restricts it to. `'any'` when it
2784
+ * declares none, declares `'*'`, or declares an atom list whose atoms
2785
+ * don't agree on one phase — such a binding fires in either phase, and
2786
+ * reporting it as `'initial'` made it collide with genuinely-initial
2787
+ * bindings in `findConflicts`' bucket key. */
2788
+ phase: 'initial' | 'engaged' | 'any';
2789
+ /** Structured v3 modifier requirements. Empty object = "no modifiers
2790
+ * held" (the strict default). */
2791
+ modifiers: ParsedModifiers;
2792
+ gesture: GestureName;
2793
+ /** Resolved arg value for arg-bearing gestures (wheel direction,
2794
+ * key name, multiTouchTap fingers). Undefined for gestures whose
2795
+ * descriptor has no `arg`. */
2796
+ arg: string | undefined;
2797
+ /** Target class for hit-testing gestures. `undefined` when the descriptor
2798
+ * has `hasTarget: false` or the spec declares no target;
2799
+ * {@link PREDICATE_TARGET} when the spec uses a `kindOf` predicate, which
2800
+ * the route grammar has no notation for. */
2801
+ target: string | undefined;
2802
+ /** The action this binding fires. */
2803
+ actionId: string;
2804
+ /** The `GestureSpec` this row was flattened from, by reference. Reflection
2805
+ * consumers that need something the grammar doesn't capture — the
2806
+ * specificity tuple, a `kindOf` predicate identity — read it here rather
2807
+ * than re-walking `Tool.bindings`. */
2808
+ spec: GestureSpec;
2809
+ }
2810
+ /**
2811
+ * Stand-in target for a `{ kindOf }` predicate spec.
2812
+ *
2813
+ * The route grammar can name target *classes* (`empty`, `selected-body`,
2814
+ * `kind:rect`) but not arbitrary predicates, so three distinct select-tool
2815
+ * bindings all render as this one token. Narrowing it would mean giving the
2816
+ * grammar a way to describe a function, which is a real design question and
2817
+ * not one this reflection layer should answer by inventing syntax.
2818
+ */
2819
+ declare const PREDICATE_TARGET = "predicate";
2820
+ /**
2821
+ * Flatten every tool's `bindings` into route-registry rows.
2822
+ *
2823
+ * This was `buildActionRegistry`, and it walked `ToolDef.initial` /
2824
+ * `.engaged` phase tables — the grammar that no longer exists. It was also
2825
+ * blind to `Tool.bindings` the entire time the two lived side by side, which
2826
+ * is why the inspector under-reported select by more than half. The rename
2827
+ * fixes a second thing: it never had anything to do with the Actions
2828
+ * Registry, and reading `buildActionRegistry` next to `ActionsRegistry`
2829
+ * suggested otherwise.
2830
+ */
2831
+ declare function buildRouteRegistry(tools: readonly Tool<unknown>[]): RegistryEntry[];
2832
+
2833
+ /** Two or more tools declare the same exact (phase, gesture, arg, target,
2834
+ * modifiers) tuple — the dispatcher's slot precedence picks one
2835
+ * arbitrarily (well, deterministically by slot order, but the author
2836
+ * probably didn't intend the duplication). */
2837
+ interface Conflict {
2838
+ phase: 'initial' | 'engaged' | 'any';
2839
+ gesture: GestureName;
2840
+ arg: string | undefined;
2841
+ target: string | undefined;
2842
+ modifiers: ParsedModifiers;
2843
+ /** All tool ids that registered the same tuple. At least 2 by
2844
+ * construction. Order matches the input tools[] order. */
2845
+ toolIds: string[];
2846
+ }
2847
+ /** Detect exact-tuple overlaps across a tool registration set.
2848
+ *
2849
+ * Intentionally NOT flagged:
2850
+ * - Broad vs. narrow targets (e.g. an untargeted `click` alongside
2851
+ * `click` on `empty`) — the dispatcher's specificity ordering resolves
2852
+ * those cleanly, and the broad one is usually the intended fallback.
2853
+ * - Different modifier requirements on the same target — they fire on
2854
+ * different inputs.
2855
+ * - A binding whose action declines via `enabled()` so a lower-priority
2856
+ * one can take the gesture. Detecting that intent would mean evaluating
2857
+ * the action; consumers can suppress known-intentional compositions in
2858
+ * their UI layer.
2859
+ *
2860
+ * - Two `{ kindOf }` predicate targets. The route grammar renders every
2861
+ * predicate as the single token {@link PREDICATE_TARGET}, so bucketing on
2862
+ * the rendered target alone reported select's `resize` / `rotate` / `move`
2863
+ * drags — three genuinely different predicates — as a three-way conflict.
2864
+ * Predicate entries bucket by function identity instead, which means two
2865
+ * *separately written but equivalent* predicates go unflagged. That's the
2866
+ * right way to be wrong here: this check has to be silent when nothing is
2867
+ * wrong or nobody will keep it on.
2868
+ *
2869
+ * Note that two bindings sharing a tuple on the SAME tool are now possible
2870
+ * (bindings are an array, where phase tables were objects with unique
2871
+ * keys) — so a conflict may name one tool twice.
2872
+ *
2873
+ * This is the raw same-tuple detector. Feeding it a whole tool *registry*
2874
+ * over-reports, because registry tools take turns in the active slot and
2875
+ * can't collide with each other — see {@link findScopedConflicts}.
2876
+ */
2877
+ declare function findConflicts(tools: readonly Tool<unknown>[]): Conflict[];
2878
+ /**
2879
+ * The tool scopes as the dispatcher sees them — which is what decides whether
2880
+ * two same-tuple bindings can actually collide.
2881
+ */
2882
+ interface ToolScopes {
2883
+ /** Tools eligible for the active slot, keyed by id or as a flat list. */
2884
+ registry: readonly Tool<unknown>[] | Readonly<Record<string, Tool<unknown>>>;
2885
+ /** Always-on tools. Every one of these is live at once. */
2886
+ ambient?: readonly Tool<unknown>[];
2887
+ }
2888
+ /**
2889
+ * Detect the same-tuple overlaps that are *reachable* — the ones where the
2890
+ * dispatcher really does fall back on declaration order.
2891
+ *
2892
+ * `matchSorted` walks scopes in strict priority (hotkey > active > ambient)
2893
+ * and only sorts by specificity *within* a scope. So a cross-scope tie isn't
2894
+ * a tie at all: an ambient tool losing a tuple to the active tool is the
2895
+ * documented design, not an accident. Likewise two registry tools sharing a
2896
+ * tuple — `rect` and `ellipse` both binding a bare `drag` — can never both be
2897
+ * in the active slot, so they never compete.
2898
+ *
2899
+ * What's left, and what this reports:
2900
+ * - a single tool colliding with **itself** (possible since bindings became
2901
+ * an array), which is ambiguous in whichever slot it occupies;
2902
+ * - two **ambient** tools, all of which are live simultaneously and are
2903
+ * ordered only by registration;
2904
+ * - two **hotkey-capable** tools, which can stack.
2905
+ *
2906
+ * Not covered: the actions registry's `defaultBinding`s, which the dispatcher
2907
+ * also folds into ambient/hotkey scope. They're assembled somewhere else
2908
+ * entirely (`ActionsRegistry`, not `useTools`), so catching tool-vs-action
2909
+ * collisions means giving this function a second input it doesn't have yet.
2910
+ */
2911
+ declare function findScopedConflicts(scopes: ToolScopes): Conflict[];
2912
+ /**
2913
+ * Render a conflict as one line of human-readable text.
2914
+ *
2915
+ * The tuple is printed through {@link formatRoute}, so the message names the
2916
+ * collision in the same grammar the author wrote the binding in — modulo the
2917
+ * phase slot, which prints as a bare `'&'`-channel atom because the bucket key
2918
+ * collapses channel-bearing phase specs (`sel:engaged` and `&:engaged` collide
2919
+ * with each other, and the collapse is what made them collide).
2920
+ */
2921
+ declare function formatConflict(conflict: Conflict): string;
2922
+ /**
2923
+ * Detect reachable route conflicts in an assembled tool set and report each one.
2924
+ *
2925
+ * This is the wiring `findConflicts` spent its first life without: the kit
2926
+ * could detect the one class of genuine routing ambiguity it has and never
2927
+ * looked. Call it once wherever a tool set is assembled (`useTools` does),
2928
+ * behind a `process.env.NODE_ENV !== 'production'` guard.
2929
+ *
2930
+ * **Warn, never throw.** A conflict between a consumer's tool and a kit tool
2931
+ * is a design question — sometimes deliberate, since the loser can still take
2932
+ * the gesture by declining through `enabled()` — and exploding in a running
2933
+ * app is the wrong way to raise it. A conflict between two *kit* tools is
2934
+ * always a bug, but the place to fail on that is the kit's own test suite
2935
+ * (`canvas/SceneCanvas.routeConflicts.test.tsx`), not a consumer's console.
2936
+ *
2937
+ * @returns The conflicts found, so callers can dedupe repeat reports.
2938
+ */
2939
+ declare function reportRouteConflicts(scopes: ToolScopes, warn?: (message: string) => void): Conflict[];
2940
+
2941
+ declare const index_ChannelRef: typeof ChannelRef;
2942
+ type index_Conflict = Conflict;
2943
+ declare const index_DescribeRouteOptions: typeof DescribeRouteOptions;
2944
+ declare const index_GESTURE_DESCRIPTORS: typeof GESTURE_DESCRIPTORS;
2945
+ declare const index_GestureArgSpec: typeof GestureArgSpec;
2946
+ declare const index_GestureDescriptor: typeof GestureDescriptor;
2947
+ declare const index_GestureName: typeof GestureName;
2948
+ declare const index_ModRequirement: typeof ModRequirement;
2949
+ declare const index_ModifierKey: typeof ModifierKey;
2950
+ declare const index_PREDICATE_TARGET: typeof PREDICATE_TARGET;
2951
+ declare const index_ParsedModifiers: typeof ParsedModifiers;
2952
+ declare const index_ParsedRoute: typeof ParsedRoute;
2953
+ declare const index_PhaseAtom: typeof PhaseAtom;
2954
+ declare const index_RESERVED_ID_NAMES: typeof RESERVED_ID_NAMES;
2955
+ declare const index_RESERVED_ID_PREFIXES: typeof RESERVED_ID_PREFIXES;
2956
+ declare const index_ROUTE_FIELD_DEFINITIONS: typeof ROUTE_FIELD_DEFINITIONS;
2957
+ declare const index_ROUTE_TERMS: typeof ROUTE_TERMS;
2958
+ type index_RegistryEntry = RegistryEntry;
2959
+ declare const index_RouteDescriptionPart: typeof RouteDescriptionPart;
2960
+ declare const index_RouteFieldName: typeof RouteFieldName;
2961
+ declare const index_RouteTermLabel: typeof RouteTermLabel;
2962
+ type index_ToolDef<TScratch = void> = ToolDef<TScratch>;
2963
+ type index_ToolKeybinding = ToolKeybinding;
2964
+ type index_ToolScopes = ToolScopes;
2965
+ type index_ViewportToolDef<TScratch = void> = ViewportToolDef<TScratch>;
2966
+ declare const index_buildRouteRegistry: typeof buildRouteRegistry;
2967
+ declare const index_canonicalModifiers: typeof canonicalModifiers;
2968
+ declare const index_collapseShiftPairs: typeof collapseShiftPairs;
2969
+ declare const index_defineTool: typeof defineTool;
2970
+ declare const index_defineViewportTool: typeof defineViewportTool;
2971
+ declare const index_describeRoute: typeof describeRoute;
2972
+ declare const index_describeRouteParts: typeof describeRouteParts;
2973
+ declare const index_findConflicts: typeof findConflicts;
2974
+ declare const index_findScopedConflicts: typeof findScopedConflicts;
2975
+ declare const index_formatConflict: typeof formatConflict;
2976
+ declare const index_formatPhaseAtom: typeof formatPhaseAtom;
2977
+ declare const index_formatRoute: typeof formatRoute;
2978
+ declare const index_getGestureDescriptor: typeof getGestureDescriptor;
2979
+ declare const index_isKnownGestureName: typeof isKnownGestureName;
2980
+ declare const index_parseRoute: typeof parseRoute;
2981
+ declare const index_reportRouteConflicts: typeof reportRouteConflicts;
2982
+ declare namespace index {
2983
+ export { index_ChannelRef as ChannelRef, type index_Conflict as Conflict, index_DescribeRouteOptions as DescribeRouteOptions, index_GESTURE_DESCRIPTORS as GESTURE_DESCRIPTORS, index_GestureArgSpec as GestureArgSpec, index_GestureDescriptor as GestureDescriptor, index_GestureName as GestureName, index_ModRequirement as ModRequirement, index_ModifierKey as ModifierKey, index_PREDICATE_TARGET as PREDICATE_TARGET, index_ParsedModifiers as ParsedModifiers, index_ParsedRoute as ParsedRoute, index_PhaseAtom as PhaseAtom, index_RESERVED_ID_NAMES as RESERVED_ID_NAMES, index_RESERVED_ID_PREFIXES as RESERVED_ID_PREFIXES, index_ROUTE_FIELD_DEFINITIONS as ROUTE_FIELD_DEFINITIONS, index_ROUTE_TERMS as ROUTE_TERMS, type index_RegistryEntry as RegistryEntry, index_RouteDescriptionPart as RouteDescriptionPart, index_RouteFieldName as RouteFieldName, index_RouteTermLabel as RouteTermLabel, type index_ToolDef as ToolDef, type index_ToolKeybinding as ToolKeybinding, type index_ToolScopes as ToolScopes, type index_ViewportToolDef as ViewportToolDef, index_buildRouteRegistry as buildRouteRegistry, index_canonicalModifiers as canonicalModifiers, index_collapseShiftPairs as collapseShiftPairs, index_defineTool as defineTool, index_defineViewportTool as defineViewportTool, index_describeRoute as describeRoute, index_describeRouteParts as describeRouteParts, index_findConflicts as findConflicts, index_findScopedConflicts as findScopedConflicts, index_formatConflict as formatConflict, index_formatPhaseAtom as formatPhaseAtom, index_formatRoute as formatRoute, index_getGestureDescriptor as getGestureDescriptor, index_isKnownGestureName as isKnownGestureName, index_parseRoute as parseRoute, index_reportRouteConflicts as reportRouteConflicts };
2984
+ }
2985
+
2986
+ export { DepRegistryProvider as $, type Action as A, type BooleansAdapter as B, type Condition as C, type Dims as D, ActiveToolContextProvider as E, ActiveToolContextProviderIfRoot as F, type GeometryProjection as G, type HotkeyTrigger as H, type InsertExtras as I, type ActiveToolContextProviderProps as J, type ActiveToolContextValue as K, type AreaSelectDep as L, type BindingOpts as M, type BindingScope as N, type BooleanOp as O, type BooleanOpResult as P, type BoundGesture as Q, type RenderLayer as R, type SliceDep as S, type Tool as T, type UseSelectionOptions as U, type VisibilityRules as V, type BuildRuleCtxArgs as W, type ClipboardIngestCtx as X, type CustomPaintContext as Y, type DepName as Z, type DepRegistry as _, type Rule as a, type ToolScopes as a$, type DispatcherContext as a0, type DragSample as a1, type EditAnchorsDep as a2, type GestureBinding as a3, type ImmediateInvoker as a4, type IngestCtx as a5, type IngestionDep as a6, type InsertDep as a7, type InvocationCtx as a8, type Invoker as a9, type UiOngoingControl as aA, type ViewApi as aB, applyBooleanOp as aC, buildRuleCtx as aD, createDispatcher as aE, describeRule as aF, drawLayers as aG, enterTextEditAction as aH, evaluate as aI, evaluateEnabled as aJ, registerContentHandler as aK, index as aL, sliceAction as aM, specificity as aN, useAction as aO, useActionsRegistry as aP, useActiveToolContext as aQ, useDepRegistry as aR, useDepSource as aS, useOptionalActiveToolContext as aT, useOptionalDepRegistry as aU, usePointerContext as aV, useSelection as aW, type Conflict as aX, PREDICATE_TARGET as aY, type RegistryEntry as aZ, type ToolDef as a_, type LassoSelectDep as aa, type LayoutDep as ab, type MatchResult as ac, NEVER as ad, type NodeAtPointDep as ae, type OngoingHandle as af, type OngoingInvoker as ag, type OngoingOverlay as ah, type Point2 as ai, PointerContextProvider as aj, type PointerContextValue as ak, type PointerWorldPos as al, type ResizePolicy as am, type ResolveAllOptions as an, type ResolveOnlyResult as ao, type ResolvedCandidate as ap, type ScopedBinding as aq, type SelectionExtendKey as ar, type SelectionMode as as, type Selector as at, type SnapDep as au, type SvgUnpacker as av, type TextEditDep as aw, type ToolModifiers as ax, type ToolPresentation as ay, type ToolSlot as az, type RuleCtx as b, type ViewportToolDef as b0, buildRouteRegistry as b1, defineTool as b2, defineViewportTool as b3, findConflicts as b4, findScopedConflicts as b5, formatConflict as b6, reportRouteConflicts as b7, type ChromeCtx as c, type ChromeId as d, type DepSchema as e, type ActionsRegistry as f, type AffordanceHit as g, type Dispatcher as h, type AnyTool as i, type ToolCtx as j, type ToolKeybinding as k, type AffordanceBinding as l, type ChromeState as m, type SelectionApi as n, type ContentHandlerEntry as o, type SvgIngestOptions as p, type ActionsProp as q, type Affordance as r, type AffordanceRegion as s, type CommonAffordanceScratch as t, ALWAYS as u, type ActionDeps as v, ActionDisabledReason as w, type ActionEnabledResult as x, type ActionEntry as y, ActionsProvider as z };