@weasel-js/routing 1.5.0 → 1.5.2

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.
@@ -493,7 +493,7 @@ interface AffordanceHit {
493
493
  * The stylus fields are absent for mouse/touch on browsers that don't report
494
494
  * them, and for synthetic events. Consumers that want pressure-driven output
495
495
  * (e.g. `Stroke.vertexWidths` from a pencil stroke) read them off the samples
496
- * their `insert` dep receives — see `apps/site/demos/VertexWidthsDemo.tsx`.
496
+ * their `insert` dep receives — see `apps/site/demos/StrokeAndFillDemo.tsx`.
497
497
  */
498
498
  interface DragSample extends Point2 {
499
499
  /** 0..1. Mouse/touch report 0.5 while a button is held, per the spec. */
@@ -542,6 +542,10 @@ interface InvocationCtx {
542
542
  * per-sample stylus state when the browser reported it.
543
543
  * Accumulated by the dispatcher on every `pointermove` pump event.
544
544
  * Available only during `onMove` and `onEnd` calls (not on `start`).
545
+ *
546
+ * During `onMove` this is the dispatcher's live accumulator, and it grows
547
+ * under you — read it, don't retain it. On `onEnd` it is a snapshot, so
548
+ * that is where an action that keeps the trail should take it.
545
549
  * Used by `lassoSelectAction` to build its polygon vertex list and by
546
550
  * `insertAction`'s pencil kind to carry the freehand stroke.
547
551
  */
@@ -553,7 +557,11 @@ interface InvocationCtx {
553
557
  deltaZ: number;
554
558
  };
555
559
  multiTouch?: {
560
+ /** Canvas-local CSS pixels — see `MultitouchEvent.centroid`. Neither
561
+ * `world` nor `screen`: it is the space `zoomAt` anchors in, so passing
562
+ * it through `clientToWorld` removes the canvas origin twice. */
556
563
  centroid: Point2;
564
+ /** Distance between the two primary pointers, in CSS pixels. */
557
565
  spread: number;
558
566
  rotation: number;
559
567
  /**
@@ -565,6 +573,7 @@ interface InvocationCtx {
565
573
  pinch?: {
566
574
  startSpread: number;
567
575
  currentSpread: number;
576
+ /** Canvas-local, same as the enclosing `centroid`. */
568
577
  centroid: Point2;
569
578
  };
570
579
  };
@@ -972,8 +981,18 @@ interface ActionDispatch extends BindingSource {
972
981
  * synthesize it from the surrounding `DepRegistry` so predicates can
973
982
  * inspect selection / scene / etc. Predicates that don't need deps just
974
983
  * ignore the arg.
984
+ *
985
+ * `at` is the world point of the event being routed, when it has one — a
986
+ * click, a press, a long-press. An action that only applies somewhere
987
+ * (on a path segment, say) refuses other points here, so the dispatcher
988
+ * falls through to the next binding and hover prediction shows the
989
+ * action's `cursor` only where it would act. Palettes and keystrokes
990
+ * pass no point; treat absent as "anywhere".
975
991
  */
976
- enabled?: (deps?: ActionDeps) => true | ActionDisabledReason;
992
+ enabled?: (deps?: ActionDeps, at?: {
993
+ x: number;
994
+ y: number;
995
+ }) => true | ActionDisabledReason;
977
996
  /**
978
997
  * Declarative eligibility rule, evaluated against the current
979
998
  * `RuleCtx` by the dispatcher before invoking `start()`. Omitted =
@@ -989,11 +1008,11 @@ interface ActionDispatch extends BindingSource {
989
1008
  eligible?: Rule | Condition;
990
1009
  /**
991
1010
  * CSS cursor shown while the pointer hovers a spot where this action
992
- * would win the drag. The hover-cursor pump (in `useGestureDispatcher`)
993
- * runs `Dispatcher.resolveOnly` on each idle pointermove — the same
994
- * match walk a real pointerdown takes — and applies the winning
995
- * action's `cursor`, so the hint and the actual click target stay in
996
- * sync by construction. Omitted = no override (the active tool's
1011
+ * would win the drag — or, when the drag's winner declares no cursor,
1012
+ * the click. The hover-cursor pump (in `useGestureDispatcher`) runs
1013
+ * `Dispatcher.resolveOnly` on each idle pointermove — the same match
1014
+ * walk a real press takes — and applies the winning action's `cursor`,
1015
+ * so the hint and the actual target stay in sync by construction. Omitted = no override (the active tool's
997
1016
  * `Tool.cursor` shows). Affordance hits are resolved earlier in the
998
1017
  * pump via `AffordanceRegion.cursor` and never reach this field.
999
1018
  *
@@ -1231,14 +1250,6 @@ interface ToolCtx<TScratch = unknown> {
1231
1250
  * zoom/pan tools to convert event clientX/clientY to canvas-relative
1232
1251
  * anchors. */
1233
1252
  canvasRect: DOMRect;
1234
- /** Screen-space pointer coords relative to `canvasRect`. Useful for
1235
- * viewport tools that pan/zoom in screen space (e.g. hand-pan
1236
- * computes deltas in pixels, not world units). Optional — populated
1237
- * by the dispatcher on pointer events; absent on keyboard events. */
1238
- screenPoint?: {
1239
- x: number;
1240
- y: number;
1241
- };
1242
1253
  /** Optional debug sink. When `<Canvas debug={...}>` is enabled, Canvas
1243
1254
  * threads its sink here so tool-internal hit math (handle hitboxes,
1244
1255
  * rotation handle, etc.) lands in the same overlay as Canvas's own
@@ -1938,10 +1949,9 @@ declare function openPointerSession(origin: Element, down: PointerEvent | React.
1938
1949
  /** What the registry knows at dispatch time. */
1939
1950
  interface EligibilityState {
1940
1951
  focusedId: string | null;
1941
- heldTriggers: ReadonlySet<string>;
1942
- /** Ids the host reports as hotkey-engaged. A declared `offhand` registers
1943
- * the binding, but `tool.offhand`'s invoker still reports engagement by
1944
- * pushing an id — this retires only if that contract changes. */
1952
+ /** Ids the host reports as hotkey-engaged. A held `offhand` trigger reaches
1953
+ * here the same way a palette pick does: the `tool.offhand` action pushes
1954
+ * the tool's id onto the active-tool context's hotkey stack. */
1945
1955
  engagedIds?: ReadonlySet<string>;
1946
1956
  /** Whether the active mode allows these capability tags. Omitted → allow. */
1947
1957
  allows?: (tags: readonly CapabilityTag[]) => boolean;
@@ -1983,7 +1993,9 @@ declare function mergeContributions(...bundles: readonly Contribution[][]): Cont
1983
1993
  */
1984
1994
  interface ToolDef<TScratch = void, TOverlay = unknown> {
1985
1995
  id: string;
1986
- /** Capability tags for modality eligibility. Forwarded onto `Tool.capabilities`. */
1996
+ /** Capability tags for modality eligibility. `defineTool` forwards these
1997
+ * onto `Tool.eligibility.capabilities`, which is where every gate reads
1998
+ * them — the assembled `Tool` carries no `capabilities` of its own. */
1987
1999
  capabilities?: CapabilityTag[];
1988
2000
  /**
1989
2001
  * Actions this tool owns and needs registered while it is in the tools
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { i as ALWAYS, c as Action, j as ActionDeps, k as ActionDisabledReason, k as ActionDisabledReasonValue, l as ActionDispatch, m as ActionEnabledResult, n as ActionEntry, o as ActionPresentation, p as ActionSource, q as ActionsProp, A as ActionsRegistry, a as AffordanceHit, r as AnyTool, d as AnyToolOf, B as BindingOpts, s as BindingScope, t as BindingSource, v as BodyPredicate, w as BoundGesture, x as Bounds, y as BuildRuleCtxArgs, z as COARSE_TARGET_SCALE, E as Condition, F as Conflict, C as Contribution, G as ContributionChrome, H as ContributionRouting, I as DEFAULT_ALLOWED_CAPABILITIES, J as DEFAULT_DEVICE_PROFILE, K as DebugSink, L as DepName, b as DepSchema, M as DetectedDeviceFacts, N as DeviceProfile, P as DispatchLogEntry, D as Dispatcher, Q as DispatcherContext, U as DragSample, V as Eligibility, W as EligibilityState, X as GestureBinding, Y as HandleKind, Z as HitShape, _ as HotkeyTrigger, $ as INGEST_STRING_MIMES, a0 as ImmediateInvoker, a1 as InvocationCtx, a2 as Invoker, a3 as KeyBinding, a4 as MatchResult, a5 as ModeSwitchLogEntry, a6 as ModifierState, a7 as NEVER, a8 as NodeId, a9 as OngoingHandle, aa as OngoingInvoker, ab as OngoingOverlay, O as OverlayPosition, ac as OverlayRole, ad as PREDICATE_TARGET, ae as Point2, af as PointerSession, ag as PointerSessionCallbacks, ah as PointerSessionCancelReason, ai as PointerSessionOptions, aj as RegistryEntry, ak as ResizeAnchor, al as ResolveAllOptions, am as ResolveOnlyResult, an as ResolvedCandidate, ao as Rule, R as RuleCtx, S as ScopedBinding, ap as ScratchKey, aq as ScratchStore, ar as SelectionApi, as as SelectionExtendKey, at as SelectionMode, au as Selector, av as TOOL_OFFHAND_ID, T as Tool, aw as ToolBounds, ax as ToolCtx, ay as ToolDef, az as ToolKeybinding, aA as ToolModifiers, aB as ToolOffhandBindingSpec, aC as ToolPresentation, aD as ToolSlot, aE as TraceLogEntry, aF as UiOngoingControl, aG as View, aH as ViewportToolDef, aI as actionBindings, aJ as buildDepsFromRequires, aK as buildRouteRegistry, aL as buildRuleCtx, aM as buildToolOffhandBindings, aN as clientToCanvas, aO as clientToCanvasRect, aP as createDispatcher, aQ as defineTool, aR as defineViewportTool, aS as deleteScratch, aT as describeRule, aU as dlog, aV as evaluate, aW as evaluateEnabled, aX as filterEligible, aY as findConflicts, aZ as getScratch, a_ as isAnchor, a$ as isAnchorOrControl, b0 as isBody, b1 as isControlHandle, b2 as isEditableTarget, b3 as isEmpty, b4 as isResizeHandle, b5 as isRotateHandle, b6 as isSelectedBody, b7 as isUnselectedBody, b8 as itemsFromClipboardData, b9 as itemsFromDataTransfer, ba as itemsFromFiles, bb as liveScope, bc as makeToolOffhandAction, bd as matchBest, be as matchSorted, bf as matchesKeyBinding, bg as mergeContributions, bh as offhandKeyFor, bi as openPointerSession, bj as pointerGestureId, bk as recordModeSwitch, bl as reportRouteConflicts, bm as resolveDeviceProfile, bn as resolveParams, bo as routeGestureForSpecKind, bp as routesForSpec, bq as scopeBindings, br as scratchKey, bs as setScratch, bt as specificity, bu as targetConsultsAffordance, bv as validateActionDefaultBinding, bw as validateActionId } from './index-BOlkWrA-.js';
1
+ export { i as ALWAYS, c as Action, j as ActionDeps, k as ActionDisabledReason, k as ActionDisabledReasonValue, l as ActionDispatch, m as ActionEnabledResult, n as ActionEntry, o as ActionPresentation, p as ActionSource, q as ActionsProp, A as ActionsRegistry, a as AffordanceHit, r as AnyTool, d as AnyToolOf, B as BindingOpts, s as BindingScope, t as BindingSource, v as BodyPredicate, w as BoundGesture, x as Bounds, y as BuildRuleCtxArgs, z as COARSE_TARGET_SCALE, E as Condition, F as Conflict, C as Contribution, G as ContributionChrome, H as ContributionRouting, I as DEFAULT_ALLOWED_CAPABILITIES, J as DEFAULT_DEVICE_PROFILE, K as DebugSink, L as DepName, b as DepSchema, M as DetectedDeviceFacts, N as DeviceProfile, P as DispatchLogEntry, D as Dispatcher, Q as DispatcherContext, U as DragSample, V as Eligibility, W as EligibilityState, X as GestureBinding, Y as HandleKind, Z as HitShape, _ as HotkeyTrigger, $ as INGEST_STRING_MIMES, a0 as ImmediateInvoker, a1 as InvocationCtx, a2 as Invoker, a3 as KeyBinding, a4 as MatchResult, a5 as ModeSwitchLogEntry, a6 as ModifierState, a7 as NEVER, a8 as NodeId, a9 as OngoingHandle, aa as OngoingInvoker, ab as OngoingOverlay, O as OverlayPosition, ac as OverlayRole, ad as PREDICATE_TARGET, ae as Point2, af as PointerSession, ag as PointerSessionCallbacks, ah as PointerSessionCancelReason, ai as PointerSessionOptions, aj as RegistryEntry, ak as ResizeAnchor, al as ResolveAllOptions, am as ResolveOnlyResult, an as ResolvedCandidate, ao as Rule, R as RuleCtx, S as ScopedBinding, ap as ScratchKey, aq as ScratchStore, ar as SelectionApi, as as SelectionExtendKey, at as SelectionMode, au as Selector, av as TOOL_OFFHAND_ID, T as Tool, aw as ToolBounds, ax as ToolCtx, ay as ToolDef, az as ToolKeybinding, aA as ToolModifiers, aB as ToolOffhandBindingSpec, aC as ToolPresentation, aD as ToolSlot, aE as TraceLogEntry, aF as UiOngoingControl, aG as View, aH as ViewportToolDef, aI as actionBindings, aJ as buildDepsFromRequires, aK as buildRouteRegistry, aL as buildRuleCtx, aM as buildToolOffhandBindings, aN as clientToCanvas, aO as clientToCanvasRect, aP as createDispatcher, aQ as defineTool, aR as defineViewportTool, aS as deleteScratch, aT as describeRule, aU as dlog, aV as evaluate, aW as evaluateEnabled, aX as filterEligible, aY as findConflicts, aZ as getScratch, a_ as isAnchor, a$ as isAnchorOrControl, b0 as isBody, b1 as isControlHandle, b2 as isEditableTarget, b3 as isEmpty, b4 as isResizeHandle, b5 as isRotateHandle, b6 as isSelectedBody, b7 as isUnselectedBody, b8 as itemsFromClipboardData, b9 as itemsFromDataTransfer, ba as itemsFromFiles, bb as liveScope, bc as makeToolOffhandAction, bd as matchBest, be as matchSorted, bf as matchesKeyBinding, bg as mergeContributions, bh as offhandKeyFor, bi as openPointerSession, bj as pointerGestureId, bk as recordModeSwitch, bl as reportRouteConflicts, bm as resolveDeviceProfile, bn as resolveParams, bo as routeGestureForSpecKind, bp as routesForSpec, bq as scopeBindings, br as scratchKey, bs as setScratch, bt as specificity, bu as targetConsultsAffordance, bv as validateActionDefaultBinding, bw as validateActionId } from './index-D4hKg8yu.js';
2
2
  export { ChannelRef, DescribeRouteOptions, GESTURE_DESCRIPTORS, GestureArgSpec, GestureDescriptor, GestureName, IngestItem, InputEvent, ModRequirement, ModifierKey, ParsedModifiers, ParsedRoute, PhaseAtom, PhaseContext, RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, ROUTE_FIELD_DEFINITIONS, ROUTE_TERMS, RouteDescriptionPart, RouteFieldName, RouteTermLabel, canonicalModifiers, collapseShiftPairs, describeRoute, describeRouteParts, formatPhaseAtom, formatRoute, getGestureDescriptor, isKnownGestureName, matchKey, matchModifiers, matchPhase, matchSpec, matchTarget, parseRoute } from '@weasel-js/gestures';
3
3
  import '@weasel-js/modes';
4
4
  import 'react';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { isDev } from './chunk-Y5FHAA4U.js';
2
- export { ALWAYS, COARSE_TARGET_SCALE, DEFAULT_ALLOWED_CAPABILITIES, DEFAULT_DEVICE_PROFILE, GESTURE_DESCRIPTORS, INGEST_STRING_MIMES, NEVER, PREDICATE_TARGET, RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, ROUTE_FIELD_DEFINITIONS, ROUTE_TERMS, TOOL_OFFHAND_ID, actionBindings, buildDepsFromRequires, buildRouteRegistry, buildRuleCtx, buildToolOffhandBindings, canonicalModifiers, clientToCanvas, clientToCanvasRect, collapseShiftPairs, createDispatcher, describeRoute, describeRouteParts, describeRule, dlog, evaluate, filterEligible, findConflicts, formatPhaseAtom, formatRoute, getGestureDescriptor, isEditableTarget, isKnownGestureName, itemsFromClipboardData, itemsFromDataTransfer, itemsFromFiles, liveScope, makeToolOffhandAction, matchBest, matchKey, matchModifiers, matchPhase, matchSorted, matchSpec, matchTarget, matchesKeyBinding, offhandKeyFor, openPointerSession, parseRoute, pointerGestureId, recordModeSwitch, reportRouteConflicts, resolveDeviceProfile, resolveParams, routeGestureForSpecKind, routesForSpec, scopeBindings, specificity, targetConsultsAffordance, validateActionDefaultBinding, validateActionId } from './chunk-Y5FHAA4U.js';
1
+ import { isDev } from './chunk-H5AGTB2J.js';
2
+ export { ALWAYS, COARSE_TARGET_SCALE, DEFAULT_ALLOWED_CAPABILITIES, DEFAULT_DEVICE_PROFILE, GESTURE_DESCRIPTORS, INGEST_STRING_MIMES, NEVER, PREDICATE_TARGET, RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, ROUTE_FIELD_DEFINITIONS, ROUTE_TERMS, TOOL_OFFHAND_ID, actionBindings, buildDepsFromRequires, buildRouteRegistry, buildRuleCtx, buildToolOffhandBindings, canonicalModifiers, clientToCanvas, clientToCanvasRect, collapseShiftPairs, createDispatcher, describeRoute, describeRouteParts, describeRule, dlog, evaluate, filterEligible, findConflicts, formatPhaseAtom, formatRoute, getGestureDescriptor, isEditableTarget, isKnownGestureName, itemsFromClipboardData, itemsFromDataTransfer, itemsFromFiles, liveScope, makeToolOffhandAction, matchBest, matchKey, matchModifiers, matchPhase, matchSorted, matchSpec, matchTarget, matchesKeyBinding, offhandKeyFor, openPointerSession, parseRoute, pointerGestureId, recordModeSwitch, reportRouteConflicts, resolveDeviceProfile, resolveParams, routeGestureForSpecKind, routesForSpec, scopeBindings, specificity, targetConsultsAffordance, validateActionDefaultBinding, validateActionId } from './chunk-H5AGTB2J.js';
3
3
  import { RESERVED_ID_PREFIXES, RESERVED_ID_NAMES } from '@weasel-js/gestures';
4
4
 
5
5
  // src/interactions/actions/action.ts
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/interactions/actions/action.ts","../src/interactions/actions/actionEnabled.ts","../src/interactions/dispatcher/predicates.ts","../src/contributions/merge.ts","../src/tools/defineTool.ts","../src/tools/defineViewportTool.ts","../src/interactions/scratchKey.ts"],"names":["RESERVED_ID_PREFIXES","RESERVED_ID_NAMES"],"mappings":";;;;;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W;AAAC,KAC9C;AAAA,IACA,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,GAAA;AAAA,IACA,cAAc,GAAA,CAAI,YAAA;AAAA,IAClB,YAAY,GAAA,CAAI,UAAA;AAAA,IAChB,YAAY,GAAA,CAAI,UAAA;AAAA,IAChB,cAAc,GAAA,CAAI,YAAA;AAAA,IAClB,WAAA,EAAa,GAAA,CAAI,WAAA,KAAgB,MAAM,IAAA,CAAA;AAAA,IACvC,MAAA,EAAQ,aAAA;AAAA,IACR,UAAU,GAAA,CAAI,QAAA;AAAA,IACd,SAAS,GAAA,CAAI,OAAA;AAAA,IACb,iBAAiB,GAAA,CAAI;AAAA,GACvB;AACF;;;ACzDO,SAAS,mBACd,GAAA,EAC0B;AAC1B,EAAA,OAAO,WAA+B,GAAG,CAAA;AAC3C;;;AC+BO,SAAS,WAAc,IAAA,EAA6B;AACzD,EAAA,OAAO,EAAE,IAAA,EAAK;AAChB;AAIO,SAAS,UAAA,CACd,OACA,GAAA,EACe;AACf,EAAA,OAAO,KAAA,CAAM,IAAI,IAAI,CAAA;AACvB;AAGO,SAAS,UAAA,CACd,KAAA,EACA,GAAA,EACA,KAAA,EACM;AACN,EAAA,KAAA,CAAM,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AACpB;AAIO,SAAS,aAAA,CACd,OACA,GAAA,EACS;AACT,EAAA,IAAI,OAAO,SAAA,CAAU,cAAA,CAAe,KAAK,KAAA,EAAO,GAAA,CAAI,IAAI,CAAA,EAAG;AACzD,IAAA,OAAO,KAAA,CAAM,IAAI,IAAI,CAAA;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * @experimental\n * The `Action` descriptor, split along the line the dispatcher reads.\n * `ActionDispatch` is everything routing consults to decide whether an action\n * runs and what happens when it does; `ActionPresentation` is what a palette,\n * menu or toolbar renders. `Action` is both.\n */\nimport type { ReactNode } from 'react';\nimport type { CursorSpec } from '@weasel-js/cursor';\nimport type { ActionDeps, Invoker } from './invoker';\nimport type { BindingSource } from './binding';\nimport type { DepName } from '../../index';\n\n/**\n * @experimental\n * Closed enum of reasons an action might report itself as disabled. The\n * consumer (palette, menu, etc.) maps these symbolic values to display\n * strings via its own label map.\n */\nexport const ActionDisabledReason = {\n SelectionRequired: 'selection-required',\n SceneEmpty: 'scene-empty',\n NotApplicable: 'not-applicable',\n /** Sentinel: the predicate threw. Surfaced by `evaluateEnabled`'s catch. */\n PredicateThrew: 'predicate-threw',\n} as const;\n/** Why an action is unavailable right now. */\nexport type ActionDisabledReason =\n (typeof ActionDisabledReason)[keyof typeof ActionDisabledReason];\n\n/**\n * @experimental\n * What a palette, menu or toolbar renders for an action. No part of this is\n * read during dispatch.\n */\nexport interface ActionPresentation {\n label: string;\n /** Inline-SVG icon for palette / toolbar surfaces. Mirrors\n * `ToolPresentation.icon` so a generic `<ActionBar>` can render from\n * action metadata the same way `<ToolPalette>` renders from tool\n * metadata. May be a static `ReactNode` or a function (rare; useful\n * for state-aware icons like a \"lock\" toggle). */\n icon?: ReactNode | (() => ReactNode);\n /** Grouping key for palette/menu surfaces. Free-form string; the kit\n * ships defaults for `'align'` (six edges/centers), `'distribute'`\n * (two axes), and recommends `'pathfinder'` for boolean ops. */\n group?: string;\n /** Display override for the keyboard shortcut. When omitted, palette\n * surfaces derive a label from `defaultBinding` via their own\n * formatter. */\n shortcut?: string;\n}\n\n/**\n * @experimental\n * What routing consults: the bindings that reach the action, the deps its\n * invoker reads, the gates it passes, and the cursors it claims.\n */\nexport interface ActionDispatch extends BindingSource {\n /** Names of the deps this action's invoker reads (keys of `DepSchema`).\n * The dispatcher (and `trigger`, when `requires` is present) resolves\n * each name against the `DepRegistry` at invocation time and passes the\n * resulting bag to the invoker. Dev builds warn when the invoker reads a\n * dep it didn't declare here — see `buildDepsFromRequires`. */\n requires?: readonly DepName[];\n /** Pluggable invocation strategy. The gesture dispatcher routes matched\n * bindings through `invoker.start` / `invoker.run` depending on timing.\n * All kit-standard descriptors ship one; consumer-supplied actions\n * without an invoker can still register but won't be triggered. */\n invoker?: Invoker;\n /** When set to `'hotkey'`, this action's `defaultBinding` rides the hotkey\n * `BindingScope` instead of the ambient scope — meaning it beats any\n * active-tool binding on the same input shape. Use for tool-switch\n * shortcuts and global held-key triggers. Default: ambient. */\n scope?: 'hotkey';\n /**\n * @experimental\n * Optional predicate the command palette consults when rendering. Return\n * `true` when the action is currently triggerable. Return a reason string\n * (e.g. `'Selection required'`) when disabled — the palette greys out\n * the row, skips it in keyboard nav, ignores clicks, and shows the\n * reason next to the label. Keystroke dispatch (the registered binding)\n * is unaffected; the action's own `run` should self-guard.\n *\n * **Contract:** must be pure (no side effects), fast (< 4ms in dev), and\n * must not throw. If a call throws or exceeds the budget in dev mode,\n * `evaluateEnabled` logs a one-time warning per action id; throws are\n * caught and treated as disabled with reason `'(predicate threw)'`.\n *\n * Snapshot-on-open semantics: the palette evaluates `enabled` once when\n * opened and does NOT re-evaluate on selection changes while open. Live\n * reactive updates are deferred — palette is short-lived.\n *\n * The reason set is a closed enum — to add a new reason, edit\n * `ActionDisabledReason` and the consumer's display map.\n *\n * The optional `deps` argument is the same bag passed to\n * `ImmediateInvoker.run`; callers (`evaluateEnabled` / the ActionBar) may\n * synthesize it from the surrounding `DepRegistry` so predicates can\n * inspect selection / scene / etc. Predicates that don't need deps just\n * ignore the arg.\n */\n enabled?: (deps?: ActionDeps) => true | ActionDisabledReason;\n /**\n * Declarative eligibility rule, evaluated against the current\n * `RuleCtx` by the dispatcher before invoking `start()`. Omitted =\n * always eligible.\n *\n * Accepts either a fluent `Condition` (callable with `.rule`) or a\n * raw `Rule` tree; the dispatcher normalizes via `.rule` unwrap.\n *\n * Prefer `capability:`-based rules (e.g. `{ capability: 'transforms-selection' }`)\n * over `mode:` rules — capability rules survive new modes being added\n * that allow the same capability.\n */\n eligible?:\n | import('../../eligibility').Rule\n | import('../../eligibility').Condition;\n /**\n * CSS cursor shown while the pointer hovers a spot where this action\n * would win the drag. The hover-cursor pump (in `useGestureDispatcher`)\n * runs `Dispatcher.resolveOnly` on each idle pointermove — the same\n * match walk a real pointerdown takes — and applies the winning\n * action's `cursor`, so the hint and the actual click target stay in\n * sync by construction. Omitted = no override (the active tool's\n * `Tool.cursor` shows). Affordance hits are resolved earlier in the\n * pump via `AffordanceRegion.cursor` and never reach this field.\n *\n * Static value only. Prediction runs `enabled()` but cannot run the\n * invoker, so an action that matches yet bails at `start()` (empty\n * handle) may still show its cursor — keep `enabled` accurate for\n * actions that declare one.\n */\n cursor?: CursorSpec;\n /**\n * CSS cursor shown while THIS action's ongoing handle is in flight —\n * grabbing while panning, `move` while dragging a selection, `crosshair`\n * while pulling a marquee.\n *\n * Separate from `cursor` because the two answer different questions:\n * `cursor` is a prediction (\"a drag from here would pan\"), this is a state\n * (\"you are panning\"). An action can declare either, both, or neither;\n * with only `cursor` set, the hover hint holds for the duration of the\n * gesture.\n *\n * This is where mid-gesture cursors live now. They used to come from the\n * tool side — `ViewportToolDef.engaged.cursor` for a phase-gated string,\n * or a function-form `Tool.cursor` reading the gesture scratch out of the\n * tool-routing dispatcher. Both belonged to a pipeline whose whole job was\n * being taken over by bindings, and neither could describe a cursor for an\n * action a tool doesn't own.\n */\n activeCursor?: CursorSpec;\n}\n\n/**\n * @experimental\n * Single registered action. v1: one binding per action.\n */\nexport interface Action extends ActionDispatch, ActionPresentation {}\n\n/**\n * @experimental\n * The whole of an actions registry the dispatcher reads. It walks the list\n * once per event to build its actionId lookup and never mutates it, so the\n * routing side depends on this rather than on `ActionsRegistry`, whose\n * register / mute / trigger surface is the React provider's.\n */\nexport interface ActionSource {\n list(): readonly Action[];\n}\n","/**\n * @experimental\n * Palette-side evaluation of `Action.enabled`. The dispatcher calls the\n * predicate raw as a gate; this is the surface that also enforces the\n * contract the predicate's JSDoc states — no throwing, under 4ms in dev.\n */\nimport type { ActionDeps } from './invoker';\nimport { ActionDisabledReason, type Action } from './action';\nimport { isDev } from '../../devFlag';\n\n/**\n * @experimental\n * Result of evaluating an Action's `enabled` predicate.\n */\nexport interface ActionEnabledResult {\n enabled: boolean;\n reason?: ActionDisabledReason;\n}\n\nconst enabledSlowWarned = new Set<string>();\nconst enabledThrewWarned = new Set<string>();\nconst ENABLED_BUDGET_MS = 4;\n/**\n * @experimental\n * Safely evaluate an action's `enabled` predicate. Returns `{enabled: true}`\n * when no predicate is supplied. Catches throws and treats them as disabled\n * with reason `'(predicate threw)'`. In dev mode, warns once per action id\n * when a single call exceeds 4ms (single frame at 240fps — generous; real\n * predicates should be sub-millisecond).\n */\nexport function evaluateEnabled(\n action: Action,\n deps?: ActionDeps,\n): ActionEnabledResult {\n if (!action.enabled) return { enabled: true };\n const dev = isDev();\n const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')\n ? () => performance.now()\n : () => Date.now();\n const start = dev ? now() : 0;\n try {\n const result = action.enabled(deps);\n if (dev) {\n const elapsed = now() - start;\n if (elapsed > ENABLED_BUDGET_MS && !enabledSlowWarned.has(action.id)) {\n enabledSlowWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" took ${elapsed.toFixed(2)}ms ` +\n `(budget ${ENABLED_BUDGET_MS}ms). The predicate must be pure and fast — see Action.enabled JSDoc.`,\n );\n }\n }\n if (result === true) return { enabled: true };\n return { enabled: false, reason: result };\n } catch (e) {\n if (dev && !enabledThrewWarned.has(action.id)) {\n enabledThrewWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" threw; treating as disabled. ` +\n `The predicate must not throw — see Action.enabled JSDoc.`,\n e,\n );\n }\n return { enabled: false, reason: ActionDisabledReason.PredicateThrew };\n }\n}\n","/**\n * Named predicates for `defaultBinding.target.kindOf`. Each matches the\n * existing `kindOf` signature `(target: unknown, bodyTarget?: string) => boolean`\n * so they drop into action descriptors without a wrapper:\n *\n * target: { kindOf: isAnchor }\n *\n * Single source of truth for \"what does this affordance kind mean\" — adding\n * a new predicate here is what enables every action that needs the same\n * shape to read it. Drift prevention.\n */\n\n// ─── Body-class predicates (read the second arg) ───────────────────────\n\n/** A predicate that resolves from `bodyTarget` alone. The exclusive-claim\n * filter reads `readsAffordance`: without it a body predicate looks like it\n * consults the hit, and survives a claim that should have barred it. */\nexport type BodyPredicate = ((target: unknown, bodyTarget?: string) => boolean)\n & { readsAffordance: false };\n\nfunction bodyPredicate(\n fn: (target: unknown, bodyTarget?: string) => boolean,\n): BodyPredicate {\n return Object.assign(fn, { readsAffordance: false as const });\n}\n\n/** Matches any body hit — selected or unselected node body. */\nexport const isBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'selected-body' || bodyTarget === 'unselected-body');\n\n/** Body hit specifically already in the selection. */\nexport const isSelectedBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'selected-body');\n\n/** Body hit specifically NOT in the selection. */\nexport const isUnselectedBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'unselected-body');\n\n/** Empty-canvas hit — no node beneath cursor. */\nexport const isEmpty: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'empty');\n\n// ─── Affordance-kind predicates (read the first arg) ───────────────────\n\nfunction kindOf(target: unknown): string | undefined {\n if (typeof target !== 'object' || target === null) return undefined;\n const k = (target as { kind?: unknown }).kind;\n return typeof k === 'string' ? k : undefined;\n}\n\n/** Any corner resize handle — top-left/top-right/bottom-left/bottom-right. */\nexport const isResizeHandle = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && k.startsWith('handle:');\n};\n\n/** The rotate-around-center handle above the bounding box. */\nexport const isRotateHandle = (target: unknown): boolean =>\n kindOf(target) === 'rotate-handle';\n\n/** Any path anchor (the on-curve dot). */\nexport const isAnchor = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && /^anchor:\\d+$/.test(k);\n};\n\n/** Either control handle (controlIn or controlOut). */\nexport const isControlHandle = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && /^(controlIn|controlOut):\\d+$/.test(k);\n};\n\n/** Any of the three anchor-editing affordances (anchor + both controls). */\nexport const isAnchorOrControl = (target: unknown): boolean =>\n isAnchor(target) || isControlHandle(target);\n","import type { Contribution } from './types';\n\n/**\n * Concatenate contribution bundles into one registry, preserving order —\n * entry order decides which of two same-specificity bindings in one scope\n * tier wins, so it is part of the result, not an accident of it.\n *\n * Throws on a duplicate id rather than dropping one: a feature silently\n * losing its bindings is the failure this registry exists to make loud.\n */\nexport function mergeContributions(...bundles: readonly Contribution[][]): Contribution[] {\n const out: Contribution[] = [];\n const seen = new Set<string>();\n for (const bundle of bundles) {\n for (const entry of bundle) {\n if (seen.has(entry.id)) {\n throw new Error(\n `mergeContributions: duplicate contribution id \"${entry.id}\". `\n + `Two bundles registered the same id; rename one or merge them by hand.`,\n );\n }\n seen.add(entry.id);\n out.push(entry);\n }\n }\n return out;\n}\n","// src/tools/defineTool.ts\nimport type { Tool, ToolCtx } from './types';\nimport type { ToolDef } from './routeTypes';\nimport { RESERVED_ID_NAMES, RESERVED_ID_PREFIXES } from '@weasel-js/gestures';\nimport type { CursorSpec } from '@weasel-js/cursor';\n\n/** Validate that `id` is usable as a tool / channel id in the route\n * grammar. Rejects ids that start with a reserved sigil (would shadow\n * future grammar extensions) and ids that collide with phase keywords\n * (would parse as the bare-phase shorthand). */\nfunction validateId(id: string, kind: 'tool' | 'action'): void {\n if (id.length === 0) {\n throw new Error(`weasel: ${kind} id may not be empty`);\n }\n if (RESERVED_ID_PREFIXES.has(id[0]!)) {\n throw new Error(\n `weasel: ${kind} id \"${id}\" starts with reserved sigil \"${id[0]}\" ` +\n `(reserved set: ${[...RESERVED_ID_PREFIXES].join(' ')})`,\n );\n }\n if (RESERVED_ID_NAMES.has(id)) {\n throw new Error(\n `weasel: ${kind} id \"${id}\" collides with a reserved phase keyword ` +\n `(reserved: ${[...RESERVED_ID_NAMES].join(', ')})`,\n );\n }\n}\n\n/**\n * Build a `Tool<TScratch>` from a declarative `ToolDef<TScratch>`.\n *\n * This used to be a translator: `ToolDef` carried `initial` / `engaged` phase\n * tables of hit-keyed route handlers, and `defineTool` compiled them into the\n * imperative `pointer` / `drag` / `keyboard` / `wheel` handlers the\n * tool-routing dispatcher called. Both ends of that are gone — tools declare\n * `bindings` and the gesture dispatcher routes them — so what remains is\n * identity plumbing plus the id check and the cursor resolver.\n *\n * It stays a function rather than becoming a spread because the id validation\n * and the `initScratch` / `cursor` defaults are worth applying uniformly, and\n * because `Tool.def` gives reflection a handle on the authored form.\n */\nexport function defineTool<TScratch = void, TOverlay = unknown>(\n def: ToolDef<TScratch, TOverlay>,\n): Tool<TScratch, TOverlay> {\n validateId(def.id, 'tool');\n\n // Normalize `CursorSpec | ((ctx) => CursorSpec)` to the function form so\n // callers have one shape to deal with. Returns '' (not undefined) so the\n // signature satisfies `Tool.cursor: (ctx) => CursorSpec`.\n const resolveCursor = (ctx: ToolCtx<TScratch>): CursorSpec => {\n if (def.cursor == null) return '';\n return typeof def.cursor === 'function' ? def.cursor(ctx) : def.cursor;\n };\n\n return {\n id: def.id,\n eligibility: {\n focus: true,\n capabilities: def.capabilities,\n ...(def.hotkey ? { offhand: def.hotkey } : {}),\n },\n actions: def.actions,\n def,\n presentation: def.presentation as Tool<TScratch>['presentation'],\n keybinding: def.keybinding,\n onActivate: def.onActivate,\n onDeactivate: def.onDeactivate,\n initScratch: def.initScratch ?? (() => null as unknown as TScratch),\n cursor: resolveCursor,\n bindings: def.bindings,\n overlay: def.overlay,\n overlayPosition: def.overlayPosition,\n };\n}\n","import type { Tool } from './types';\nimport type { ViewportToolDef } from './routeTypes';\nimport { defineTool } from './defineTool';\n\n/**\n * Define a tool that acts on the viewport rather than the scene.\n *\n * This used to do real work: `ViewportPhaseDef` was a narrowed `PhaseDef`\n * (no click routes, drag restricted to the function form), and the factory\n * lifted it back to the permissive shape before handing it to `defineTool`.\n * With phase tables gone there is no shape left to narrow — a viewport tool\n * declares `bindings` like any other, pointing at `viewport.*` actions.\n *\n * It survives as an authoring signal. `defineViewportTool` at the top of a\n * hook says \"this tool moves the camera, not the drawing\", which is worth\n * more than the type gymnastics it replaced.\n */\nexport function defineViewportTool<TScratch = void, TOverlay = unknown>(\n def: ViewportToolDef<TScratch, TOverlay>,\n): Tool<TScratch, TOverlay> {\n return defineTool<TScratch, TOverlay>(def);\n}\n","/**\n * Typed keys for the gesture/behavior scratch store.\n *\n * Gestures expose `ctx.scratch: Record<string, unknown>` as a per-gesture\n * mutable bag that behaviors use to stash state across `onDown` / `onMove`\n * / `onEnd` calls. The store is `unknown`-valued because behaviors are\n * tool-agnostic — a single behavior may run under different tools with\n * different scratch shapes. Without a typing convention every read site\n * has to `(ctx.scratch as <some shape>)[KEY]`, and a writer changing the\n * shape can silently break readers with no compile-time signal.\n *\n * `ScratchKey<T>` is a phantom-typed string that carries its payload type\n * via a branded interface. `getScratch` and `setScratch` use the brand to\n * narrow / constrain at the typing layer; at runtime the key is just its\n * underlying string and the store remains a plain `Record`.\n *\n * @example\n * ```ts\n * // Module-level (or behavior-level) constant, shared by writer + reader:\n * const LASSO_VERTICES = scratchKey<readonly { x: number; y: number }[]>('lasso.vertices');\n *\n * // Writer (a tool's onMove):\n * setScratch(ctx.scratch, LASSO_VERTICES, vertices);\n *\n * // Reader (a behavior's onEnd):\n * const vertices = getScratch(ctx.scratch, LASSO_VERTICES) ?? [];\n * // ^? readonly { x: number; y: number }[] | undefined\n * ```\n */\n\n/** Phantom-typed key for a scratch slot. The `__scratchKeyPayload` phantom\n * field carries the value type without occupying any runtime memory. */\nexport interface ScratchKey<T> {\n readonly name: string;\n /** Phantom — never read at runtime. Only present so TypeScript can\n * recover `T` at use sites. */\n readonly __scratchKeyPayload?: (_: T) => T;\n}\n\n/** Compatible scratch store shape. The kit's gesture context's `scratch`\n * field already satisfies this; consumers don't need to construct one. */\nexport type ScratchStore = Record<string, unknown>;\n\n/**\n * Make a typed scratch key. Use module-level constants so the same key\n * is shared by writer and reader.\n *\n * Namespace the name by behavior or feature to avoid collisions\n * (`'behavior.field'` is a good convention). Two keys with the same\n * `name` refer to the same slot at runtime — the type parameter is a\n * compile-time contract, not a uniqueness guarantee.\n */\nexport function scratchKey<T>(name: string): ScratchKey<T> {\n return { name };\n}\n\n/** Read a typed slot from the scratch store. Returns `undefined` if\n * nothing has been written under the key. */\nexport function getScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n): T | undefined {\n return store[key.name] as T | undefined;\n}\n\n/** Write a value to a typed slot. Overwrites whatever was there. */\nexport function setScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n value: T,\n): void {\n store[key.name] = value;\n}\n\n/** Remove a slot from the scratch store. Returns `true` if it was set,\n * `false` if it wasn't. */\nexport function deleteScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n): boolean {\n if (Object.prototype.hasOwnProperty.call(store, key.name)) {\n delete store[key.name];\n return true;\n }\n return false;\n}\n"]}
1
+ {"version":3,"sources":["../src/interactions/actions/action.ts","../src/interactions/actions/actionEnabled.ts","../src/interactions/dispatcher/predicates.ts","../src/contributions/merge.ts","../src/tools/defineTool.ts","../src/tools/defineViewportTool.ts","../src/interactions/scratchKey.ts"],"names":["RESERVED_ID_PREFIXES","RESERVED_ID_NAMES"],"mappings":";;;;;AAmBO,IAAM,oBAAA,GAAuB;AAAA,EAClC,iBAAA,EAAmB,oBAAA;AAAA,EACnB,UAAA,EAAY,aAAA;AAAA,EACZ,aAAA,EAAe,gBAAA;AAAA;AAAA,EAEf,cAAA,EAAgB;AAClB;;;ACNA,IAAM,iBAAA,uBAAwB,GAAA,EAAY;AAC1C,IAAM,kBAAA,uBAAyB,GAAA,EAAY;AAC3C,IAAM,iBAAA,GAAoB,CAAA;AASnB,SAAS,eAAA,CACd,QACA,IAAA,EACqB;AACrB,EAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,EAAE,SAAS,IAAA,EAAK;AAC5C,EAAA,MAAM,MAAM,KAAA,EAAM;AA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O,SAAS,mBACd,GAAA,EAC0B;AAC1B,EAAA,OAAO,WAA+B,GAAG,CAAA;AAC3C;;;AC+BO,SAAS,WAAc,IAAA,EAA6B;AACzD,EAAA,OAAO,EAAE,IAAA,EAAK;AAChB;AAIO,SAAS,UAAA,CACd,OACA,GAAA,EACe;AACf,EAAA,OAAO,KAAA,CAAM,IAAI,IAAI,CAAA;AACvB;AAGO,SAAS,UAAA,CACd,KAAA,EACA,GAAA,EACA,KAAA,EACM;AACN,EAAA,KAAA,CAAM,GAAA,CAAI,IAAI,CAAA,GAAI,KAAA;AACpB;AAIO,SAAS,aAAA,CACd,OACA,GAAA,EACS;AACT,EAAA,IAAI,OAAO,SAAA,CAAU,cAAA,CAAe,KAAK,KAAA,EAAO,GAAA,CAAI,IAAI,CAAA,EAAG;AACzD,IAAA,OAAO,KAAA,CAAM,IAAI,IAAI,CAAA;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * @experimental\n * The `Action` descriptor, split along the line the dispatcher reads.\n * `ActionDispatch` is everything routing consults to decide whether an action\n * runs and what happens when it does; `ActionPresentation` is what a palette,\n * menu or toolbar renders. `Action` is both.\n */\nimport type { ReactNode } from 'react';\nimport type { CursorSpec } from '@weasel-js/cursor';\nimport type { ActionDeps, Invoker } from './invoker';\nimport type { BindingSource } from './binding';\nimport type { DepName } from '../../index';\n\n/**\n * @experimental\n * Closed enum of reasons an action might report itself as disabled. The\n * consumer (palette, menu, etc.) maps these symbolic values to display\n * strings via its own label map.\n */\nexport const ActionDisabledReason = {\n SelectionRequired: 'selection-required',\n SceneEmpty: 'scene-empty',\n NotApplicable: 'not-applicable',\n /** Sentinel: the predicate threw. Surfaced by `evaluateEnabled`'s catch. */\n PredicateThrew: 'predicate-threw',\n} as const;\n/** Why an action is unavailable right now. */\nexport type ActionDisabledReason =\n (typeof ActionDisabledReason)[keyof typeof ActionDisabledReason];\n\n/**\n * @experimental\n * What a palette, menu or toolbar renders for an action. No part of this is\n * read during dispatch.\n */\nexport interface ActionPresentation {\n label: string;\n /** Inline-SVG icon for palette / toolbar surfaces. Mirrors\n * `ToolPresentation.icon` so a generic `<ActionBar>` can render from\n * action metadata the same way `<ToolPalette>` renders from tool\n * metadata. May be a static `ReactNode` or a function (rare; useful\n * for state-aware icons like a \"lock\" toggle). */\n icon?: ReactNode | (() => ReactNode);\n /** Grouping key for palette/menu surfaces. Free-form string; the kit\n * ships defaults for `'align'` (six edges/centers), `'distribute'`\n * (two axes), and recommends `'pathfinder'` for boolean ops. */\n group?: string;\n /** Display override for the keyboard shortcut. When omitted, palette\n * surfaces derive a label from `defaultBinding` via their own\n * formatter. */\n shortcut?: string;\n}\n\n/**\n * @experimental\n * What routing consults: the bindings that reach the action, the deps its\n * invoker reads, the gates it passes, and the cursors it claims.\n */\nexport interface ActionDispatch extends BindingSource {\n /** Names of the deps this action's invoker reads (keys of `DepSchema`).\n * The dispatcher (and `trigger`, when `requires` is present) resolves\n * each name against the `DepRegistry` at invocation time and passes the\n * resulting bag to the invoker. Dev builds warn when the invoker reads a\n * dep it didn't declare here — see `buildDepsFromRequires`. */\n requires?: readonly DepName[];\n /** Pluggable invocation strategy. The gesture dispatcher routes matched\n * bindings through `invoker.start` / `invoker.run` depending on timing.\n * All kit-standard descriptors ship one; consumer-supplied actions\n * without an invoker can still register but won't be triggered. */\n invoker?: Invoker;\n /** When set to `'hotkey'`, this action's `defaultBinding` rides the hotkey\n * `BindingScope` instead of the ambient scope — meaning it beats any\n * active-tool binding on the same input shape. Use for tool-switch\n * shortcuts and global held-key triggers. Default: ambient. */\n scope?: 'hotkey';\n /**\n * @experimental\n * Optional predicate the command palette consults when rendering. Return\n * `true` when the action is currently triggerable. Return a reason string\n * (e.g. `'Selection required'`) when disabled — the palette greys out\n * the row, skips it in keyboard nav, ignores clicks, and shows the\n * reason next to the label. Keystroke dispatch (the registered binding)\n * is unaffected; the action's own `run` should self-guard.\n *\n * **Contract:** must be pure (no side effects), fast (< 4ms in dev), and\n * must not throw. If a call throws or exceeds the budget in dev mode,\n * `evaluateEnabled` logs a one-time warning per action id; throws are\n * caught and treated as disabled with reason `'(predicate threw)'`.\n *\n * Snapshot-on-open semantics: the palette evaluates `enabled` once when\n * opened and does NOT re-evaluate on selection changes while open. Live\n * reactive updates are deferred — palette is short-lived.\n *\n * The reason set is a closed enum — to add a new reason, edit\n * `ActionDisabledReason` and the consumer's display map.\n *\n * The optional `deps` argument is the same bag passed to\n * `ImmediateInvoker.run`; callers (`evaluateEnabled` / the ActionBar) may\n * synthesize it from the surrounding `DepRegistry` so predicates can\n * inspect selection / scene / etc. Predicates that don't need deps just\n * ignore the arg.\n *\n * `at` is the world point of the event being routed, when it has one — a\n * click, a press, a long-press. An action that only applies somewhere\n * (on a path segment, say) refuses other points here, so the dispatcher\n * falls through to the next binding and hover prediction shows the\n * action's `cursor` only where it would act. Palettes and keystrokes\n * pass no point; treat absent as \"anywhere\".\n */\n enabled?: (deps?: ActionDeps, at?: { x: number; y: number }) => true | ActionDisabledReason;\n /**\n * Declarative eligibility rule, evaluated against the current\n * `RuleCtx` by the dispatcher before invoking `start()`. Omitted =\n * always eligible.\n *\n * Accepts either a fluent `Condition` (callable with `.rule`) or a\n * raw `Rule` tree; the dispatcher normalizes via `.rule` unwrap.\n *\n * Prefer `capability:`-based rules (e.g. `{ capability: 'transforms-selection' }`)\n * over `mode:` rules — capability rules survive new modes being added\n * that allow the same capability.\n */\n eligible?:\n | import('../../eligibility').Rule\n | import('../../eligibility').Condition;\n /**\n * CSS cursor shown while the pointer hovers a spot where this action\n * would win the drag — or, when the drag's winner declares no cursor,\n * the click. The hover-cursor pump (in `useGestureDispatcher`) runs\n * `Dispatcher.resolveOnly` on each idle pointermove — the same match\n * walk a real press takes — and applies the winning action's `cursor`,\n * so the hint and the actual target stay in sync by construction. Omitted = no override (the active tool's\n * `Tool.cursor` shows). Affordance hits are resolved earlier in the\n * pump via `AffordanceRegion.cursor` and never reach this field.\n *\n * Static value only. Prediction runs `enabled()` but cannot run the\n * invoker, so an action that matches yet bails at `start()` (empty\n * handle) may still show its cursor — keep `enabled` accurate for\n * actions that declare one.\n */\n cursor?: CursorSpec;\n /**\n * CSS cursor shown while THIS action's ongoing handle is in flight —\n * grabbing while panning, `move` while dragging a selection, `crosshair`\n * while pulling a marquee.\n *\n * Separate from `cursor` because the two answer different questions:\n * `cursor` is a prediction (\"a drag from here would pan\"), this is a state\n * (\"you are panning\"). An action can declare either, both, or neither;\n * with only `cursor` set, the hover hint holds for the duration of the\n * gesture.\n *\n * This is where mid-gesture cursors live now. They used to come from the\n * tool side — `ViewportToolDef.engaged.cursor` for a phase-gated string,\n * or a function-form `Tool.cursor` reading the gesture scratch out of the\n * tool-routing dispatcher. Both belonged to a pipeline whose whole job was\n * being taken over by bindings, and neither could describe a cursor for an\n * action a tool doesn't own.\n */\n activeCursor?: CursorSpec;\n}\n\n/**\n * @experimental\n * Single registered action. v1: one binding per action.\n */\nexport interface Action extends ActionDispatch, ActionPresentation {}\n\n/**\n * @experimental\n * The whole of an actions registry the dispatcher reads. It walks the list\n * once per event to build its actionId lookup and never mutates it, so the\n * routing side depends on this rather than on `ActionsRegistry`, whose\n * register / mute / trigger surface is the React provider's.\n */\nexport interface ActionSource {\n list(): readonly Action[];\n}\n","/**\n * @experimental\n * Palette-side evaluation of `Action.enabled`. The dispatcher calls the\n * predicate raw as a gate; this is the surface that also enforces the\n * contract the predicate's JSDoc states — no throwing, under 4ms in dev.\n */\nimport type { ActionDeps } from './invoker';\nimport { ActionDisabledReason, type Action } from './action';\nimport { isDev } from '../../devFlag';\n\n/**\n * @experimental\n * Result of evaluating an Action's `enabled` predicate.\n */\nexport interface ActionEnabledResult {\n enabled: boolean;\n reason?: ActionDisabledReason;\n}\n\nconst enabledSlowWarned = new Set<string>();\nconst enabledThrewWarned = new Set<string>();\nconst ENABLED_BUDGET_MS = 4;\n/**\n * @experimental\n * Safely evaluate an action's `enabled` predicate. Returns `{enabled: true}`\n * when no predicate is supplied. Catches throws and treats them as disabled\n * with reason `'(predicate threw)'`. In dev mode, warns once per action id\n * when a single call exceeds 4ms (single frame at 240fps — generous; real\n * predicates should be sub-millisecond).\n */\nexport function evaluateEnabled(\n action: Action,\n deps?: ActionDeps,\n): ActionEnabledResult {\n if (!action.enabled) return { enabled: true };\n const dev = isDev();\n const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')\n ? () => performance.now()\n : () => Date.now();\n const start = dev ? now() : 0;\n try {\n const result = action.enabled(deps);\n if (dev) {\n const elapsed = now() - start;\n if (elapsed > ENABLED_BUDGET_MS && !enabledSlowWarned.has(action.id)) {\n enabledSlowWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" took ${elapsed.toFixed(2)}ms ` +\n `(budget ${ENABLED_BUDGET_MS}ms). The predicate must be pure and fast — see Action.enabled JSDoc.`,\n );\n }\n }\n if (result === true) return { enabled: true };\n return { enabled: false, reason: result };\n } catch (e) {\n if (dev && !enabledThrewWarned.has(action.id)) {\n enabledThrewWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" threw; treating as disabled. ` +\n `The predicate must not throw — see Action.enabled JSDoc.`,\n e,\n );\n }\n return { enabled: false, reason: ActionDisabledReason.PredicateThrew };\n }\n}\n","/**\n * Named predicates for `defaultBinding.target.kindOf`. Each matches the\n * existing `kindOf` signature `(target: unknown, bodyTarget?: string) => boolean`\n * so they drop into action descriptors without a wrapper:\n *\n * target: { kindOf: isAnchor }\n *\n * Single source of truth for \"what does this affordance kind mean\" — adding\n * a new predicate here is what enables every action that needs the same\n * shape to read it. Drift prevention.\n */\n\n// ─── Body-class predicates (read the second arg) ───────────────────────\n\n/** A predicate that resolves from `bodyTarget` alone. The exclusive-claim\n * filter reads `readsAffordance`: without it a body predicate looks like it\n * consults the hit, and survives a claim that should have barred it. */\nexport type BodyPredicate = ((target: unknown, bodyTarget?: string) => boolean)\n & { readsAffordance: false };\n\nfunction bodyPredicate(\n fn: (target: unknown, bodyTarget?: string) => boolean,\n): BodyPredicate {\n return Object.assign(fn, { readsAffordance: false as const });\n}\n\n/** Matches any body hit — selected or unselected node body. */\nexport const isBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'selected-body' || bodyTarget === 'unselected-body');\n\n/** Body hit specifically already in the selection. */\nexport const isSelectedBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'selected-body');\n\n/** Body hit specifically NOT in the selection. */\nexport const isUnselectedBody: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'unselected-body');\n\n/** Empty-canvas hit — no node beneath cursor. */\nexport const isEmpty: BodyPredicate = bodyPredicate((_target, bodyTarget) =>\n bodyTarget === 'empty');\n\n// ─── Affordance-kind predicates (read the first arg) ───────────────────\n\nfunction kindOf(target: unknown): string | undefined {\n if (typeof target !== 'object' || target === null) return undefined;\n const k = (target as { kind?: unknown }).kind;\n return typeof k === 'string' ? k : undefined;\n}\n\n/** Any corner resize handle — top-left/top-right/bottom-left/bottom-right. */\nexport const isResizeHandle = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && k.startsWith('handle:');\n};\n\n/** The rotate-around-center handle above the bounding box. */\nexport const isRotateHandle = (target: unknown): boolean =>\n kindOf(target) === 'rotate-handle';\n\n/** Any path anchor (the on-curve dot). */\nexport const isAnchor = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && /^anchor:\\d+$/.test(k);\n};\n\n/** Either control handle (controlIn or controlOut). */\nexport const isControlHandle = (target: unknown): boolean => {\n const k = kindOf(target);\n return k !== undefined && /^(controlIn|controlOut):\\d+$/.test(k);\n};\n\n/** Any of the three anchor-editing affordances (anchor + both controls). */\nexport const isAnchorOrControl = (target: unknown): boolean =>\n isAnchor(target) || isControlHandle(target);\n","import type { Contribution } from './types';\n\n/**\n * Concatenate contribution bundles into one registry, preserving order —\n * entry order decides which of two same-specificity bindings in one scope\n * tier wins, so it is part of the result, not an accident of it.\n *\n * Throws on a duplicate id rather than dropping one: a feature silently\n * losing its bindings is the failure this registry exists to make loud.\n */\nexport function mergeContributions(...bundles: readonly Contribution[][]): Contribution[] {\n const out: Contribution[] = [];\n const seen = new Set<string>();\n for (const bundle of bundles) {\n for (const entry of bundle) {\n if (seen.has(entry.id)) {\n throw new Error(\n `mergeContributions: duplicate contribution id \"${entry.id}\". `\n + `Two bundles registered the same id; rename one or merge them by hand.`,\n );\n }\n seen.add(entry.id);\n out.push(entry);\n }\n }\n return out;\n}\n","// src/tools/defineTool.ts\nimport type { Tool, ToolCtx } from './types';\nimport type { ToolDef } from './routeTypes';\nimport { RESERVED_ID_NAMES, RESERVED_ID_PREFIXES } from '@weasel-js/gestures';\nimport type { CursorSpec } from '@weasel-js/cursor';\n\n/** Validate that `id` is usable as a tool / channel id in the route\n * grammar. Rejects ids that start with a reserved sigil (would shadow\n * future grammar extensions) and ids that collide with phase keywords\n * (would parse as the bare-phase shorthand). */\nfunction validateId(id: string, kind: 'tool' | 'action'): void {\n if (id.length === 0) {\n throw new Error(`weasel: ${kind} id may not be empty`);\n }\n if (RESERVED_ID_PREFIXES.has(id[0]!)) {\n throw new Error(\n `weasel: ${kind} id \"${id}\" starts with reserved sigil \"${id[0]}\" ` +\n `(reserved set: ${[...RESERVED_ID_PREFIXES].join(' ')})`,\n );\n }\n if (RESERVED_ID_NAMES.has(id)) {\n throw new Error(\n `weasel: ${kind} id \"${id}\" collides with a reserved phase keyword ` +\n `(reserved: ${[...RESERVED_ID_NAMES].join(', ')})`,\n );\n }\n}\n\n/**\n * Build a `Tool<TScratch>` from a declarative `ToolDef<TScratch>`.\n *\n * This used to be a translator: `ToolDef` carried `initial` / `engaged` phase\n * tables of hit-keyed route handlers, and `defineTool` compiled them into the\n * imperative `pointer` / `drag` / `keyboard` / `wheel` handlers the\n * tool-routing dispatcher called. Both ends of that are gone — tools declare\n * `bindings` and the gesture dispatcher routes them — so what remains is\n * identity plumbing plus the id check and the cursor resolver.\n *\n * It stays a function rather than becoming a spread because the id validation\n * and the `initScratch` / `cursor` defaults are worth applying uniformly, and\n * because `Tool.def` gives reflection a handle on the authored form.\n */\nexport function defineTool<TScratch = void, TOverlay = unknown>(\n def: ToolDef<TScratch, TOverlay>,\n): Tool<TScratch, TOverlay> {\n validateId(def.id, 'tool');\n\n // Normalize `CursorSpec | ((ctx) => CursorSpec)` to the function form so\n // callers have one shape to deal with. Returns '' (not undefined) so the\n // signature satisfies `Tool.cursor: (ctx) => CursorSpec`.\n const resolveCursor = (ctx: ToolCtx<TScratch>): CursorSpec => {\n if (def.cursor == null) return '';\n return typeof def.cursor === 'function' ? def.cursor(ctx) : def.cursor;\n };\n\n return {\n id: def.id,\n eligibility: {\n focus: true,\n capabilities: def.capabilities,\n ...(def.hotkey ? { offhand: def.hotkey } : {}),\n },\n actions: def.actions,\n def,\n presentation: def.presentation as Tool<TScratch>['presentation'],\n keybinding: def.keybinding,\n onActivate: def.onActivate,\n onDeactivate: def.onDeactivate,\n initScratch: def.initScratch ?? (() => null as unknown as TScratch),\n cursor: resolveCursor,\n bindings: def.bindings,\n overlay: def.overlay,\n overlayPosition: def.overlayPosition,\n };\n}\n","import type { Tool } from './types';\nimport type { ViewportToolDef } from './routeTypes';\nimport { defineTool } from './defineTool';\n\n/**\n * Define a tool that acts on the viewport rather than the scene.\n *\n * This used to do real work: `ViewportPhaseDef` was a narrowed `PhaseDef`\n * (no click routes, drag restricted to the function form), and the factory\n * lifted it back to the permissive shape before handing it to `defineTool`.\n * With phase tables gone there is no shape left to narrow — a viewport tool\n * declares `bindings` like any other, pointing at `viewport.*` actions.\n *\n * It survives as an authoring signal. `defineViewportTool` at the top of a\n * hook says \"this tool moves the camera, not the drawing\", which is worth\n * more than the type gymnastics it replaced.\n */\nexport function defineViewportTool<TScratch = void, TOverlay = unknown>(\n def: ViewportToolDef<TScratch, TOverlay>,\n): Tool<TScratch, TOverlay> {\n return defineTool<TScratch, TOverlay>(def);\n}\n","/**\n * Typed keys for the gesture/behavior scratch store.\n *\n * Gestures expose `ctx.scratch: Record<string, unknown>` as a per-gesture\n * mutable bag that behaviors use to stash state across `onDown` / `onMove`\n * / `onEnd` calls. The store is `unknown`-valued because behaviors are\n * tool-agnostic — a single behavior may run under different tools with\n * different scratch shapes. Without a typing convention every read site\n * has to `(ctx.scratch as <some shape>)[KEY]`, and a writer changing the\n * shape can silently break readers with no compile-time signal.\n *\n * `ScratchKey<T>` is a phantom-typed string that carries its payload type\n * via a branded interface. `getScratch` and `setScratch` use the brand to\n * narrow / constrain at the typing layer; at runtime the key is just its\n * underlying string and the store remains a plain `Record`.\n *\n * @example\n * ```ts\n * // Module-level (or behavior-level) constant, shared by writer + reader:\n * const LASSO_VERTICES = scratchKey<readonly { x: number; y: number }[]>('lasso.vertices');\n *\n * // Writer (a tool's onMove):\n * setScratch(ctx.scratch, LASSO_VERTICES, vertices);\n *\n * // Reader (a behavior's onEnd):\n * const vertices = getScratch(ctx.scratch, LASSO_VERTICES) ?? [];\n * // ^? readonly { x: number; y: number }[] | undefined\n * ```\n */\n\n/** Phantom-typed key for a scratch slot. The `__scratchKeyPayload` phantom\n * field carries the value type without occupying any runtime memory. */\nexport interface ScratchKey<T> {\n readonly name: string;\n /** Phantom — never read at runtime. Only present so TypeScript can\n * recover `T` at use sites. */\n readonly __scratchKeyPayload?: (_: T) => T;\n}\n\n/** Compatible scratch store shape. The kit's gesture context's `scratch`\n * field already satisfies this; consumers don't need to construct one. */\nexport type ScratchStore = Record<string, unknown>;\n\n/**\n * Make a typed scratch key. Use module-level constants so the same key\n * is shared by writer and reader.\n *\n * Namespace the name by behavior or feature to avoid collisions\n * (`'behavior.field'` is a good convention). Two keys with the same\n * `name` refer to the same slot at runtime — the type parameter is a\n * compile-time contract, not a uniqueness guarantee.\n */\nexport function scratchKey<T>(name: string): ScratchKey<T> {\n return { name };\n}\n\n/** Read a typed slot from the scratch store. Returns `undefined` if\n * nothing has been written under the key. */\nexport function getScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n): T | undefined {\n return store[key.name] as T | undefined;\n}\n\n/** Write a value to a typed slot. Overwrites whatever was there. */\nexport function setScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n value: T,\n): void {\n store[key.name] = value;\n}\n\n/** Remove a slot from the scratch store. Returns `true` if it was set,\n * `false` if it wasn't. */\nexport function deleteScratch<T>(\n store: ScratchStore,\n key: ScratchKey<T>,\n): boolean {\n if (Object.prototype.hasOwnProperty.call(store, key.name)) {\n delete store[key.name];\n return true;\n }\n return false;\n}\n"]}
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as Dispatcher, A as ActionsRegistry, T as Tool, a as AffordanceHit, R as RuleCtx, b as DepSchema, c as Action, d as AnyToolOf, O as OverlayPosition, C as Contribution, S as ScopedBinding } from './index-BOlkWrA-.js';
2
- export { e as DepRegistry, f as DepRegistryProvider, u as useDepRegistry, g as useDepSource, h as useOptionalDepRegistry } from './index-BOlkWrA-.js';
1
+ import { D as Dispatcher, A as ActionsRegistry, T as Tool, a as AffordanceHit, R as RuleCtx, b as DepSchema, c as Action, d as AnyToolOf, O as OverlayPosition, C as Contribution, S as ScopedBinding } from './index-D4hKg8yu.js';
2
+ export { e as DepRegistry, f as DepRegistryProvider, u as useDepRegistry, g as useDepSource, h as useOptionalDepRegistry } from './index-D4hKg8yu.js';
3
3
  import { RefObject, ReactNode, ReactElement } from 'react';
4
4
  import { BodyClassification } from '@weasel-js/gestures';
5
5
  import { PaintedCursorState } from '@weasel-js/cursor';
@@ -64,6 +64,20 @@ interface ViewIdResolver {
64
64
  };
65
65
  end(pointerId: number): void;
66
66
  }
67
+ /** Per-channel switches for the listeners `useGestureDispatcher` attaches to
68
+ * the canvas element. Omitted or `true` attaches the channel. */
69
+ interface DispatcherChannels {
70
+ /** `pointerdown`, hover `pointermove`, `pointerleave` — press, drag, click,
71
+ * long-press, multi-touch and the hover-cursor pump. */
72
+ pointer?: boolean;
73
+ /** `wheel`. */
74
+ wheel?: boolean;
75
+ /** `contextmenu`. Off leaves the browser's native menu in place. */
76
+ contextMenu?: boolean;
77
+ /** OS drop on the element plus `paste` on the window. Off leaves the
78
+ * element a non-drop-target and stops `weasel-dropover` being applied. */
79
+ ingest?: boolean;
80
+ }
67
81
  /** Options for `useGestureDispatcher`: the element to listen on, the actions
68
82
  * and tools in play, and the hooks that turn raw DOM events into the world
69
83
  * coordinates and hit targets bindings match against. */
@@ -205,6 +219,22 @@ interface UseGestureDispatcherOptions {
205
219
  * wires this; tests / harnesses without chrome-caps state can omit it.
206
220
  */
207
221
  getRuleCtx?: () => RuleCtx | undefined;
222
+ /**
223
+ * Which of the canvas element's input channels to attach. Every one
224
+ * defaults to `true`; naming a channel `false` leaves its listeners
225
+ * unattached, so the element behaves as if the dispatcher were not there.
226
+ *
227
+ * A mount that binds two gestures should not also have to take the rest of
228
+ * the pipeline's side effects: `contextMenu` suppresses the native menu
229
+ * unconditionally, and `ingest` makes the element a valid drop target and
230
+ * styles it while an OS drag hovers. `@weasel-js/labkit`'s loupe mounts on
231
+ * a lab's own canvas host for a wheel and a held key, and turning the other
232
+ * three off is what keeps right-click and file drops working there.
233
+ *
234
+ * The window keyboard channel is `keyboard` instead of an entry here,
235
+ * because `<SceneCanvas enableKeybindings>` drives it.
236
+ */
237
+ channels?: DispatcherChannels;
208
238
  /**
209
239
  * Routing for a canvas hosting more than one view: the non-root dispatch
210
240
  * records to choose between, read fresh per event, and the resolver that
@@ -402,4 +432,4 @@ interface ContributionsApi<TOverlay = unknown> {
402
432
  */
403
433
  declare function useContributions<TOverlay = unknown>(opts: UseContributionsOptions<TOverlay>): ContributionsApi<TOverlay>;
404
434
 
405
- export { ActionsProvider, ActionsScope, ActiveToolContextProvider, ActiveToolContextProviderIfRoot, type ActiveToolContextProviderProps, type ActiveToolContextValue, type ContributionsApi, type DispatcherViewTarget, type ToolsApi, type UseContributionsOptions, type UseGestureDispatcherOptions, type UseToolsOptions, type ViewIdResolver, useAction, useActionsRegistry, useActiveToolContext, useContributions, useGestureDispatcher, useOptionalActiveToolContext, useTools };
435
+ export { ActionsProvider, ActionsScope, ActiveToolContextProvider, ActiveToolContextProviderIfRoot, type ActiveToolContextProviderProps, type ActiveToolContextValue, type ContributionsApi, type DispatcherChannels, type DispatcherViewTarget, type ToolsApi, type UseContributionsOptions, type UseGestureDispatcherOptions, type UseToolsOptions, type ViewIdResolver, useAction, useActionsRegistry, useActiveToolContext, useContributions, useGestureDispatcher, useOptionalActiveToolContext, useTools };
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createDispatcher, buildDepsFromRequires, validateActionId, validateActionDefaultBinding, scopeBindings, liveScope, offhandKeyFor, makeToolOffhandAction, buildToolOffhandBindings, isDev, reportRouteConflicts, dlog, isEditableTarget, clientToCanvasRect, openPointerSession, pointerGestureId, itemsFromDataTransfer, itemsFromClipboardData } from './chunk-Y5FHAA4U.js';
1
+ import { createDispatcher, buildDepsFromRequires, validateActionId, validateActionDefaultBinding, scopeBindings, liveScope, offhandKeyFor, makeToolOffhandAction, buildToolOffhandBindings, isDev, reportRouteConflicts, dlog, isEditableTarget, clientToCanvasRect, openPointerSession, pointerGestureId, itemsFromDataTransfer, itemsFromClipboardData } from './chunk-H5AGTB2J.js';
2
2
  import { createContext, useState, useCallback, useMemo, useContext, useRef, useEffect } from 'react';
3
3
  import { jsx, Fragment } from 'react/jsx-runtime';
4
4
  import { resolveCursorTier } from '@weasel-js/cursor';
@@ -134,7 +134,11 @@ function computeMultiTouchGeometry(positions) {
134
134
  return { centroid, spread };
135
135
  }
136
136
  function useGestureDispatcher(opts) {
137
- const { canvasRef, actions, toolsById, enabled = true, keyboard = true, affordanceAt, classifyTarget, dispatcher: dispatcherOpt, clientToWorld, requestRedraw, paintedCursor, getRuleCtx, onDoubleClick, views } = opts;
137
+ const { canvasRef, actions, toolsById, enabled = true, keyboard = true, affordanceAt, classifyTarget, dispatcher: dispatcherOpt, clientToWorld, requestRedraw, paintedCursor, getRuleCtx, onDoubleClick, views, channels } = opts;
138
+ const pointerChannel = channels?.pointer !== false;
139
+ const wheelChannel = channels?.wheel !== false;
140
+ const contextMenuChannel = channels?.contextMenu !== false;
141
+ const ingestChannel = channels?.ingest !== false;
138
142
  const onDoubleClickRef = useRef(onDoubleClick);
139
143
  onDoubleClickRef.current = onDoubleClick;
140
144
  const activeTool = useActiveToolContext();
@@ -297,8 +301,10 @@ function useGestureDispatcher(opts) {
297
301
  if (result === "unhandled") {
298
302
  dispatch({
299
303
  kind: "contextmenu",
300
- worldX: down.worldX,
301
- worldY: down.worldY,
304
+ x: down.worldX,
305
+ y: down.worldY,
306
+ clientX: down.clientX,
307
+ clientY: down.clientY,
302
308
  ...shared
303
309
  });
304
310
  }
@@ -448,7 +454,7 @@ function useGestureDispatcher(opts) {
448
454
  shiftKey: e.shiftKey
449
455
  }
450
456
  });
451
- dispatch({ ...ev, stage: "press" });
457
+ if (held.size < 2) dispatch({ ...ev, stage: "press" });
452
458
  if ((e.pointerType === "touch" || e.pointerType === "pen") && held.size === 1) {
453
459
  cancelLongPress(e.pointerId);
454
460
  longPressTimers.set(
@@ -588,24 +594,25 @@ function useGestureDispatcher(opts) {
588
594
  const hoverBody = target().classifyTarget?.(w);
589
595
  const bodyTarget = hoverBody?.body;
590
596
  const bodyKind = hoverBody?.kind;
591
- const predicted = dispatcherNow().resolveOnly(
592
- {
593
- kind: "pointerdown",
594
- x: w.x,
595
- y: w.y,
596
- clientX: h.clientX,
597
- clientY: h.clientY,
598
- altKey: h.altKey,
599
- ctrlKey: h.ctrlKey,
600
- metaKey: h.metaKey,
601
- shiftKey: h.shiftKey,
602
- ...affordance !== void 0 ? { affordance } : {},
603
- ...bodyTarget !== void 0 ? { bodyTarget } : {},
604
- ...bodyKind !== void 0 ? { bodyKind } : {}
605
- },
606
- ctxNow()
607
- );
608
- applyHoverCursor(predicted?.action.cursor ?? null);
597
+ const where = {
598
+ altKey: h.altKey,
599
+ ctrlKey: h.ctrlKey,
600
+ metaKey: h.metaKey,
601
+ shiftKey: h.shiftKey,
602
+ ...affordance !== void 0 ? { affordance } : {},
603
+ ...bodyTarget !== void 0 ? { bodyTarget } : {},
604
+ ...bodyKind !== void 0 ? { bodyKind } : {}
605
+ };
606
+ const ctx = ctxNow();
607
+ const dragCursor = dispatcherNow().resolveOnly(
608
+ { kind: "pointerdown", x: w.x, y: w.y, clientX: h.clientX, clientY: h.clientY, ...where },
609
+ ctx
610
+ )?.action.cursor;
611
+ const cursor = dragCursor ?? dispatcherNow().resolveOnly(
612
+ { kind: "click", x: w.x, y: w.y, pressX: w.x, pressY: w.y, ...where },
613
+ ctx
614
+ )?.action.cursor;
615
+ applyHoverCursor(cursor ?? null);
609
616
  }
610
617
  const scheduleHoverCursorRefresh = (e) => {
611
618
  if (!lastHover) return;
@@ -691,8 +698,10 @@ function useGestureDispatcher(opts) {
691
698
  ctrlKey: e.ctrlKey,
692
699
  metaKey: e.metaKey,
693
700
  shiftKey: e.shiftKey,
694
- worldX: wClick.x,
695
- worldY: wClick.y,
701
+ x: wClick.x,
702
+ y: wClick.y,
703
+ clientX: e.clientX,
704
+ clientY: e.clientY,
696
705
  pressX: down.worldX,
697
706
  pressY: down.worldY,
698
707
  ...down.affordance !== void 0 ? { affordance: down.affordance } : {},
@@ -712,8 +721,10 @@ function useGestureDispatcher(opts) {
712
721
  ctrlKey: e.ctrlKey,
713
722
  metaKey: e.metaKey,
714
723
  shiftKey: e.shiftKey,
715
- worldX: wClick.x,
716
- worldY: wClick.y,
724
+ x: wClick.x,
725
+ y: wClick.y,
726
+ clientX: e.clientX,
727
+ clientY: e.clientY,
717
728
  ...down.affordance !== void 0 ? { affordance: down.affordance } : {},
718
729
  ...down.bodyTarget !== void 0 ? { bodyTarget: down.bodyTarget } : {},
719
730
  ...down.bodyKind !== void 0 ? { bodyKind: down.bodyKind } : {}
@@ -770,8 +781,10 @@ function useGestureDispatcher(opts) {
770
781
  ctrlKey: e.ctrlKey,
771
782
  metaKey: e.metaKey,
772
783
  shiftKey: e.shiftKey,
773
- worldX: w.x,
774
- worldY: w.y,
784
+ x: w.x,
785
+ y: w.y,
786
+ clientX: e.clientX,
787
+ clientY: e.clientY,
775
788
  ...affordance !== void 0 ? { affordance } : {},
776
789
  ...menuBody?.body !== void 0 ? { bodyTarget: menuBody.body } : {},
777
790
  ...menuBody?.kind !== void 0 ? { bodyKind: menuBody.kind } : {}
@@ -839,16 +852,20 @@ function useGestureDispatcher(opts) {
839
852
  window.addEventListener("blur", onWindowBlur);
840
853
  window.addEventListener("keydown", scheduleHoverCursorRefresh);
841
854
  window.addEventListener("keyup", scheduleHoverCursorRefresh);
842
- canvas?.addEventListener("pointerleave", onHoverPointerLeave);
843
- canvas?.addEventListener("wheel", onWheel, { passive: false });
844
- canvas?.addEventListener("pointerdown", onPointerDown);
845
- canvas?.addEventListener("pointermove", onHoverMove);
846
- canvas?.addEventListener("contextmenu", onContextMenu);
847
- canvas?.addEventListener("dragenter", onDragOver);
848
- canvas?.addEventListener("dragover", onDragOver);
849
- canvas?.addEventListener("dragleave", onDragLeave);
850
- canvas?.addEventListener("drop", onDrop);
851
- window.addEventListener("paste", onPaste);
855
+ if (pointerChannel) {
856
+ canvas?.addEventListener("pointerleave", onHoverPointerLeave);
857
+ canvas?.addEventListener("pointerdown", onPointerDown);
858
+ canvas?.addEventListener("pointermove", onHoverMove);
859
+ }
860
+ if (wheelChannel) canvas?.addEventListener("wheel", onWheel, { passive: false });
861
+ if (contextMenuChannel) canvas?.addEventListener("contextmenu", onContextMenu);
862
+ if (ingestChannel) {
863
+ canvas?.addEventListener("dragenter", onDragOver);
864
+ canvas?.addEventListener("dragover", onDragOver);
865
+ canvas?.addEventListener("dragleave", onDragLeave);
866
+ canvas?.addEventListener("drop", onDrop);
867
+ window.addEventListener("paste", onPaste);
868
+ }
852
869
  return () => {
853
870
  if (keyboard) {
854
871
  window.removeEventListener("keydown", onKeyDown);
@@ -875,7 +892,7 @@ function useGestureDispatcher(opts) {
875
892
  held.clear();
876
893
  for (const d of allDispatchers()) d.cancelAll("cancel");
877
894
  };
878
- }, [enabled, keyboard, canvasRef]);
895
+ }, [enabled, keyboard, canvasRef, pointerChannel, wheelChannel, contextMenuChannel, ingestChannel]);
879
896
  }
880
897
  var ActionsContext = createContext(null);
881
898
  function useMuted(base) {
@@ -1026,7 +1043,6 @@ function ActionsProvider({ children }) {
1026
1043
  scene: r.get("scene"),
1027
1044
  history: r.get("history"),
1028
1045
  view: r.get("view"),
1029
- pointer: r.get("pointer"),
1030
1046
  activeTool: r.get("activeTool"),
1031
1047
  booleansAdapter: r.get("booleansAdapter")
1032
1048
  };
@@ -1061,7 +1077,6 @@ function ActionsProvider({ children }) {
1061
1077
  scene: r.get("scene"),
1062
1078
  history: r.get("history"),
1063
1079
  view: r.get("view"),
1064
- pointer: r.get("pointer"),
1065
1080
  activeTool: r.get("activeTool"),
1066
1081
  booleansAdapter: r.get("booleansAdapter")
1067
1082
  };
@@ -1102,7 +1117,6 @@ function useAction(action) {
1102
1117
  return reg.register(action);
1103
1118
  }, [reg, action]);
1104
1119
  }
1105
- var NO_TRIGGERS = /* @__PURE__ */ new Set();
1106
1120
  function useContributions(opts) {
1107
1121
  const ctx = useActiveToolContext();
1108
1122
  const actionsRegistry = useActionsRegistry();
@@ -1141,7 +1155,7 @@ function useContributions(opts) {
1141
1155
  }
1142
1156
  return {
1143
1157
  ordered,
1144
- state: { focusedId: focusedRef.current, heldTriggers: NO_TRIGGERS, engagedIds }
1158
+ state: { focusedId: focusedRef.current, engagedIds }
1145
1159
  };
1146
1160
  }, []);
1147
1161
  const scopedBindings = useCallback(() => {