@weasel-js/routing 1.13.0 → 1.14.0

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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/interactions/actions/actionItems.ts","../src/interactions/actions/actionSettings.ts","../src/interactions/actions/binding.ts","../src/interactions/actions/actionShortcuts.ts","../src/interactions/actions/action.ts","../src/interactions/actions/actionEnabled.ts","../src/interactions/actions/buildDeps.ts","../src/interactions/actions/scopeNode.ts","../src/interactions/actions/depNode.ts","../src/interactions/actions/registry.ts","../src/interactions/actions/invoker.ts","../src/interactions/actions/modifierRoles.ts","../src/interactions/actions/tuning.ts","../src/interactions/actions/bindingOverrides.ts","../src/interactions/dispatcher/inputFacts.ts","../src/interactions/actions/toolOffhand.ts","../src/tools/routing/reflection/registry.ts","../src/interactions/dispatcher/matcher.ts","../src/eligibility/deviceProfile.ts","../src/eligibility/rule.ts","../src/eligibility/exclusive.ts","../src/eligibility/ruleCtx.ts","../src/interactions/dispatcher/gestureIds.ts","../src/contributions/eligibility.ts","../src/contributions/assemble.ts","../src/interactions/dispatcher/dispatchTrace.ts","../src/interactions/dispatcher/ranking.ts","../src/interactions/dispatcher/buildDispatchRecord.ts","../src/interactions/dispatcher/gestureFacts.ts","../src/interactions/dispatcher/inFlightGestures.ts","../src/interactions/dispatcher/invocationCtx.ts","../src/interactions/dispatcher/gestureRun.ts","../src/interactions/dispatcher/uiOngoing.ts","../src/interactions/dispatcher/walk.ts","../src/interactions/dispatcher/predict.ts","../src/interactions/dispatcher/keymapRoute.ts","../src/interactions/dispatcher/dispatcher.ts","../src/interactions/dispatcher/longPressState.ts","../src/interactions/pointerSession/pointerSession.ts","../src/interactions/carry/carry.ts","../src/keymaps/keymapStack.ts","../src/keymaps/keymapContribution.ts","../src/keymaps/describeKeymap.ts","../src/tools/types.ts","../src/tools/routing/reflection/conflictKeys.ts","../src/tools/routing/reflection/conflicts.ts","../src/interactions/keyHelpers.ts","../src/ingestion/ingestItems.ts","../src/viewport/clientToCanvas.ts","../src/dlog.ts","../src/menus/pickMenu.ts","../src/menus/resolveMenu.ts","../src/menus/menuHost.ts"],"names":["isDev","admitted","createEmitter","explain","matches","EMPTY_ENGAGED","MODIFIER_KEYS","capabilitiesAllowed","isPlainEscape","activeModeOf","read"],"mappings":";;;;;;;;;;AAOA,IAAM,OAAA,GAA6B,MAAA,CAAO,MAAA,CAAO,EAAE,CAAA;AAkB5C,SAAS,YAAY,MAAA,EAA8B;AACxD,EAAA,IAAI,MAAA,CAAO,OAAA,EAAS,MAAA,KAAW,WAAA,SAAoB,EAAC;AACpD,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,EAAU,MAAA,EAAQ;AAC5B,IAAA,OAAO,CAAC,EAAE,GAAA,EAAK,MAAA,CAAO,EAAA,EAAI,QAAQ,KAAA,EAAO,MAAA,CAAO,KAAA,EAAO,IAAA,EAAM,OAAO,IAAA,EAAM,IAAA,EAAM,MAAA,CAAO,IAAA,IAAQ,SAAS,CAAA;AAAA,EAC1G;AACA,EAAA,OAAO,MAAA,CAAO,QAAA,CAAS,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IACjC,KAAK,CAAA,EAAG,MAAA,CAAO,EAAE,CAAA,CAAA,EAAI,EAAE,GAAG,CAAA,CAAA;AAAA,IAC1B,MAAA;AAAA,IACA,OAAO,CAAA,CAAE,KAAA;AAAA,IACT,IAAA,EAAM,CAAA,CAAE,IAAA,IAAQ,MAAA,CAAO,IAAA;AAAA,IACvB,IAAA,EAAM,CAAA,CAAE,IAAA,GAAO,CAAC,GAAI,MAAA,CAAO,IAAA,IAAQ,OAAA,EAAU,GAAG,CAAA,CAAE,IAAI,CAAA,GAAI,OAAO,IAAA,IAAQ,OAAA;AAAA,IACzE,QAAQ,CAAA,CAAE;AAAA,GACZ,CAAE,CAAA;AACJ;AAKO,SAAS,gBAAgB,IAAA,EAA0B;AACxD,EAAA,IAAI,KAAK,GAAA,KAAQ,IA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AAA,MAAM,CAAA,GAAI,IAAA,CAAK,OAAA,CAAQ,KAAK,CAAA;AAC5B,QAAA,IAAI,CAAA,IAAK,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,MAC9B,CAAA;AAAA,IACF,CAAA;AAAA,IACA,KAAK,GAAA,EAAK;AACR,MAAA,MAAM,OAAA,GAAU,QAAQ,GAAG,CAAA;AAC3B,MAAA,IAAI,CAAC,QAAQ,MAAA,EAAQ;AACnB,QAAA,KAAA,EAAM;AACN,QAAA,OAAO,KAAA;AAAA,MACT;AACA,MAAA,IAAA,GAAO;AAAA,QACL,KAAK,EAAE,GAAA;AAAA,QAAK,OAAA;AAAA,QAAS,QAAQ,GAAA,CAAI,MAAA;AAAA,QAAQ,OAAO,GAAA,CAAI,KAAA;AAAA,QACpD,GAAI,IAAI,KAAA,GAAQ,EAAE,OAAO,GAAA,CAAI,KAAA,KAAU,EAAC;AAAA,QACxC,GAAI,IAAI,IAAA,GAAO,EAAE,MAAM,GAAA,CAAI,IAAA,KAAS,EAAC;AAAA,QACrC,MAAA,EAAQ,IAAI,MAAA,IAAU;AAAA,OACxB;AACA,MAAA,IAAA,EAAK;AACL,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AAAA,IACA,KAAK,CAAC,GAAA,KAAQ,OAAA,CAAQ,GAAG,EAAE,MAAA,GAAS,CAAA;AAAA,IACpC,KAAA;AAAA,IACA,SAAS,MAAM,IAAA;AAAA,IACf,UAAU,EAAA,EAAI;AACZ,MAAA,SAAA,CAAU,IAAI,EAAE,CAAA;AAChB,MAAA,OAAO,MAAM;AAAE,QAAA,SAAA,CAAU,OAAO,EAAE,CAAA;AAAA,MAAG,CAAA;AAAA,IACvC;AAAA,GACF;AACF","file":"chunk-XVWEZTUX.js","sourcesContent":["/**\n * The entries an action contributes to a bar, menu or palette — one per\n * variant, or the action itself when it declares none.\n */\nimport type { IconRef } from '@weasel-js/icons';\nimport type { Action } from './action';\n\nconst NO_TAGS: readonly string[] = Object.freeze([]);\n\n/** One renderable entry: an action, optionally with params. */\nexport interface ActionItem {\n /** `action.id`, or `action.id:variant.key` — unique across a registry. */\n key: string;\n action: Action;\n label: string;\n icon?: IconRef;\n /** The action's tags, then the variant's own. */\n tags: readonly string[];\n /** What to pass to `trigger(action.id, params)`; absent for a plain action. */\n params?: Readonly<Record<string, unknown>>;\n}\n\n/** Expand `action` into the entries a surface renders. An\n * action without an immediate invoker has none: `trigger` cannot start a\n * drag, so a button for one would do nothing. */\nexport function actionItems(action: Action): ActionItem[] {\n if (action.invoker?.timing !== 'immediate') return [];\n if (!action.variants?.length) {\n return [{ key: action.id, action, label: action.label, icon: action.icon, tags: action.tags ?? NO_TAGS }];\n }\n return action.variants.map((v) => ({\n key: `${action.id}:${v.key}`,\n action,\n label: v.label,\n icon: v.icon ?? action.icon,\n tags: v.tags ? [...(action.tags ?? NO_TAGS), ...v.tags] : action.tags ?? NO_TAGS,\n params: v.params,\n }));\n}\n\n/** How a palette titles `item`: a variant reads as its action's\n * label and its own (\"New: A4\"), unless its label already holds the action's\n * as whole words (\"Zoom In\", \"Reset Zoom\"). */\nexport function actionItemTitle(item: ActionItem): string {\n if (item.key === item.action.id) return item.label;\n const words = (s: string) => s.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [];\n const head = words(item.action.label);\n const label = words(item.label);\n for (let i = 0; i + head.length <= label.length; i++) {\n if (head.every((w, j) => label[i + j] === w)) return item.label;\n }\n return `${item.action.label}: ${item.label}`;\n}\n","/**\n * A settings form an action carries: what a surface draws in place of a bare\n * trigger for an action whose job is to change settings on the selection.\n */\nimport type { PrefGroup } from '@weasel-js/prefs';\nimport type { Action } from './action';\nimport type { ActionDeps } from './invoker';\n\n/** What a settings form shows for the selection right now. */\nexport interface ActionSettingsState {\n /** The values, nested as the schema's groups nest. */\n values: Record<string, unknown>;\n /** The leaf paths where the selected items disagree. */\n mixed?: readonly string[];\n}\n\n/**\n * The settings form an action carries. A bar or a panel draws the action as a\n * button opening it, a menu as a submenu of its fields, and a palette as a\n * dialog; each change triggers the action with the params it makes.\n */\nexport interface ActionSettings {\n /** The form. Its `name` titles the popover, submenu or dialog. */\n schema: PrefGroup;\n /** The selection's current values, from the deps `enabled` is given. Under\n * `enabled`'s contract: pure, fast, and it must not throw. */\n read(deps: ActionDeps): ActionSettingsState;\n /** The params one field's change triggers the action with, or `null` for\n * none. Default: `{ [path]: value }`. */\n params?(path: string, value: unknown): Record<string, unknown> | null;\n}\n\nconst EMPTY: ActionSettingsState = { values: {} };\n\n/** `action`'s settings as they stand under `deps`, or `null` for an action\n * with no settings. A `read` that throws shows nothing rather than breaking\n * the surface. */\nexport function readActionSettings(action: Action, deps: ActionDeps | undefined): ActionSettingsState | null {\n const settings = action.settings;\n if (!settings) return null;\n try {\n return settings.read(deps ?? {});\n } catch {\n return EMPTY;\n }\n}\n\n/** The params a change of the field at `path` to `value` triggers the action with. */\nexport function actionSettingsParams(\n settings: ActionSettings,\n path: string,\n value: unknown,\n): Record<string, unknown> | null {\n return settings.params ? settings.params(path, value) : { [path]: value };\n}\n","/**\n * GestureBinding — connects a GestureSpec to an Action id (with per-binding\n * options). Tools own arrays of these on their `bindings` field; ambient\n * gesture-bindings are registered globally.\n */\n\nimport type { GestureSpec } from '@weasel-js/gestures';\nimport type { BindingOpts } from './invoker';\n\n/** An interaction: a gesture spec composed with the id of the action it\n * invokes. Tools declare arrays of these; the dispatcher matches an incoming\n * input event against them and runs the winner's action. */\nexport interface GestureBinding {\n spec: GestureSpec;\n actionId: string;\n opts?: BindingOpts;\n}\n\n/**\n * A single entry in `Action.defaultBinding[]`. Either a bare `GestureSpec`\n * (no per-binding opts) or an object form that pairs a spec with\n * `BindingOpts` for parametric actions (e.g. `{ params: { axis: 'x' } }`).\n * Use the object form when two bindings for the same action differ only in\n * a runtime parameter — the dispatcher extracts `opts.params` and passes\n * them to `ImmediateInvoker.run` as its second argument.\n */\nexport type BoundGesture = GestureSpec | { spec: GestureSpec; opts: BindingOpts };\n\n/**\n * The whole of an action `actionBindings` reads. Routing needs this much and\n * none of `Action`'s palette fields, so it is the narrowest type the\n * dispatcher's binding walk can be written against.\n */\nexport interface BindingSource {\n id: string;\n /** The gesture-spec form of the binding, read by the gesture dispatcher.\n * May be a single `GestureSpec`, a bare `GestureSpec[]` (any-of semantics),\n * or a `BoundGesture[]` where each entry is either a bare `GestureSpec` or\n * `{ spec, opts }` — use the object form for parametric actions where two\n * bindings for the same action differ only by `opts.params` (e.g. `flip`\n * with `axis: 'x'` vs `'y'`). The dispatcher extracts `opts.params` and\n * passes them to `ImmediateInvoker.run` as its second argument. */\n defaultBinding?: GestureSpec | BoundGesture[];\n}\n\n/**\n * Flatten an action's `defaultBinding` into `GestureBinding`s. A bare\n * `GestureSpec` has `kind` at top level; the object form has `spec`.\n */\nexport function actionBindings(action: BindingSource): GestureBinding[] {\n const gs = action.defaultBinding;\n if (!gs) return [];\n const raw: BoundGesture[] = Array.isArray(gs) ? gs : [gs as BoundGesture];\n return raw.map((entry) => {\n const isBoundObj = !('kind' in entry);\n const spec = isBoundObj ? (entry as { spec: GestureSpec }).spec : (entry as GestureSpec);\n const opts = isBoundObj ? (entry as { opts: BindingOpts }).opts : undefined;\n return { spec, actionId: action.id, ...(opts !== undefined ? { opts } : {}) };\n });\n}\n","/**\n * Project an action's keyboard bindings into the shape a shortcut chip\n * renders from (`formatShortcut` / `formatShortcutParts` in `@weasel-js/ui`).\n */\nimport type { GestureSpec } from '@weasel-js/gestures';\nimport type { MenuShortcut } from '@weasel-js/menu';\nimport type { Action } from './action';\nimport { actionBindings } from './binding';\n\n/** One keyboard shortcut, flattened for display: the chip a menu row draws\n * (`MenuShortcut` in `@weasel-js/menu`, `ShortcutInput` in `@weasel-js/gestures`). */\nexport type ActionShortcut = MenuShortcut;\n\n/**\n * The chip form of a single gesture spec, or `undefined` when the spec has\n * none.\n *\n * - A spec's `key` may list spellings of one keycap (`['[', '{']` — the\n * shifted bracket reports as `'{'`). The first is the shortcut's name.\n * - A modifier declared `'optional'` matches held or unheld, so it isn't\n * part of what the user has to press.\n *\n * Non-keyboard specs (drag, wheel, click) have no chip form. Neither does a\n * *required* `ctrl` or `meta`: the display shape carries only `mod`.\n */\nexport function keySpecShortcut(spec: GestureSpec): ActionShortcut | undefined {\n if (spec.kind !== 'key' && spec.kind !== 'key-held') return undefined;\n const key = Array.isArray(spec.key) ? spec.key[0] : spec.key;\n if (typeof key !== 'string' || key.length === 0) return undefined;\n const mods = 'mods' in spec ? spec.mods : undefined;\n return {\n key,\n mod: mods?.mod === true,\n alt: mods?.alt === true,\n shift: mods?.shift === true,\n };\n}\n\n/**\n * Every keyboard shortcut an action answers to, in declaration order.\n * Specs `keySpecShortcut` has no chip for are skipped, and bindings it leaves\n * identical are emitted once; an action bound only to those returns empty.\n *\n * With `params` — an `ActionItem`'s — only the bindings that pass those same\n * values count, so each variant of `flip` gets its own key.\n */\nexport function actionShortcuts(\n action: Action,\n params?: Readonly<Record<string, unknown>>,\n): readonly ActionShortcut[] {\n const out: ActionShortcut[] = [];\n const seen = new Set<string>();\n for (const { spec, opts } of actionBindings(action)) {\n if (params && !paramsMatch(opts?.params, params)) continue;\n const shortcut = keySpecShortcut(spec);\n if (!shortcut) continue;\n const token = `${shortcut.key}|${shortcut.mod}|${shortcut.alt}|${shortcut.shift}`;\n if (seen.has(token)) continue;\n seen.add(token);\n out.push(shortcut);\n }\n return out;\n}\n\n/** Whether `bound` (a binding's `opts.params`) carries every value in `wanted`. */\nexport function paramsMatch(bound: unknown, wanted: Readonly<Record<string, unknown>>): boolean {\n if (typeof bound !== 'object' || bound === null) return false;\n return Object.entries(wanted).every(([k, v]) => (bound as Record<string, unknown>)[k] === v);\n}\n","/**\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 { ModifierRoles } from './modifierRoles';\nimport type { IconRef } from '@weasel-js/icons';\nimport type { CursorSpec } from '@weasel-js/cursor';\nimport type { ActionDeps, Invoker } from './invoker';\nimport type { ActionSettings } from './actionSettings';\nimport type { BindingSource } from './binding';\nimport type { DepName } from '../../index';\nimport type { IngestItem } from '@weasel-js/gestures';\n\n/** What content being routed brings to `Action.enabled`: a drop's or a\n * paste's items, or a carry's payload with no items. */\nexport interface Carried {\n items: readonly IngestItem[];\n carry?: { type: string; value: unknown };\n}\n\n/**\n * The kit's symbolic reasons an action might report itself as disabled. The\n * consumer (palette, menu, etc.) maps these to display strings via its own\n * label map. An action may also answer with any other string, which is\n * display text and shown as is — see {@link ActionUnavailable}.\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/** What `enabled` answers with when the action cannot run: one of the\n * symbolic {@link ActionDisabledReason}s, or a sentence to show as it is. */\nexport type ActionUnavailable = ActionDisabledReason | (string & {});\n\n/**\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 /** The action's icon, by qualified name: `icon('group')` in the package that draws it. */\n icon?: IconRef;\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 /** Words the action is also found by and gathered under. Where `group` is\n * the one place an action sits, an action carries any number of tags: a\n * palette search matches them as it matches the label, and\n * `actionsTagged` / `taggedActionItems` gather every action or entry\n * carrying one, for a bar or a menu built from a tag. */\n tags?: readonly 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 /** The distinct things a parametric action does, one per set of params —\n * `flip` flips horizontally or vertically, `reorder.forward` moves one step\n * or all the way. A bar, menu or palette shows one entry per variant and\n * triggers the action with that variant's `params`. Omitted = the action\n * is one entry. See `actionItems`. */\n variants?: readonly ActionVariant[];\n /** A form of the settings the action changes on the selection. A surface\n * draws the action as that form instead of a bare trigger, and each change\n * triggers it with the params `settings.params` makes. Not combined with\n * `variants`. */\n settings?: ActionSettings;\n}\n\n/**\n * One entry a parametric action contributes to a bar, menu or palette.\n */\nexport interface ActionVariant {\n /** Unique within the action; joined to its id to make the entry's key. */\n key: string;\n label: string;\n /** Falls back to the action's own `icon`. */\n icon?: IconRef;\n /** Tags this variant carries besides its action's, which it carries too. */\n tags?: readonly string[];\n /** Passed to `trigger`, and matched against each binding's\n * `opts.params` to find the variant's shortcuts. */\n params: Readonly<Record<string, unknown>>;\n}\n\n/**\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 * Optional predicate saying whether the action can run right now. Return\n * `true` when it can, or an `ActionDisabledReason` or a sentence of display\n * text when it cannot. The\n * command palette greys out a disabled row, skips it in keyboard nav,\n * ignores clicks, and shows the reason next to the label. The dispatcher\n * skips a disabled action too, on a key as on a pointer, and falls through\n * to the next binding that matches. `ActionsRegistry.trigger` asks too, but\n * with no point, so a `run` whose answer depends on `at` should still\n * self-guard.\n *\n * **Contract:** must be pure (no side effects), fast (< 4ms in dev), and\n * must not throw. A throw is caught and treated as disabled with reason\n * `ActionDisabledReason.PredicateThrew`.\n *\n * The palette evaluates `enabled` once when opened and does NOT re-evaluate\n * on selection changes while open.\n *\n * `deps` is the same bag passed to `ImmediateInvoker.run`.\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. `trigger` passes the\n * `worldX`/`worldY` its params carry, so a menu row is run under the\n * question it was shown enabled for. Palettes and keystrokes pass no\n * point; treat absent as \"anywhere\".\n *\n * `carried` is what a drop, a paste or a carry being routed brings. For\n * an OS drag still in flight its items hold a MIME and nothing else, since\n * a browser withholds contents until the drop. A carry has no items and\n * hands over its payload whole. An action that takes only some content\n * refuses the rest here, so a drag it would not take is not accepted and a\n * paste it would not take stays the page's.\n */\n enabled?: (\n deps?: ActionDeps,\n at?: { x: number; y: number },\n carried?: Carried,\n ) => true | ActionUnavailable;\n /**\n * Whether the action reads as held down right now: bold on the selected\n * text, snapping switched on. A toolbar button draws it as pressed.\n * Omitted = the action has no pressed state, which is not the same as\n * one that is off. Never read during dispatch.\n *\n * Under the same contract as `enabled`: pure, fast, and it must not\n * throw. `deps` is the bag `enabled` is given.\n */\n active?: (deps?: ActionDeps) => boolean;\n /**\n * Show what running the action now would do, and change nothing: the\n * result an operation would make, drawn over the canvas. A toolbar asks\n * while its button is hovered or focused, through\n * `ActionsRegistry.preview`, and calls what this returns when that ends.\n * Asked only while `enabled` says yes, with the deps and params `run`\n * would get. Omitted = the action has nothing to show.\n */\n preview?: (deps: ActionDeps, params?: Record<string, unknown>) => (() => void) | void;\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 runs the same match walk a real press\n * takes, so the hint and the actual target stay in sync. Omitted = no\n * override (the active tool's `Tool.cursor` shows). Affordance hits are\n * resolved earlier in the pump via `AffordanceRegion.cursor` and never\n * reach this field.\n *\n * A function is asked each time with the params the winning binding would\n * start the action with, tunings included, so a cursor can follow them — a\n * brush ring as wide as the brush. Read it through {@link actionCursor}.\n * Prediction runs `enabled()` but cannot run the invoker, so an action that\n * matches yet bails at `start()` (empty handle) may still show its cursor —\n * keep `enabled` accurate for actions that declare one.\n */\n cursor?: CursorSpec | ((params: Record<string, unknown> | undefined) => CursorSpec | undefined);\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 activeCursor?: CursorSpec;\n /**\n * The modifiers an ongoing action reads while it runs, by role: Shift\n * holding a handle's angle, Alt breaking its mirror. The dispatcher resolves\n * each into `InvocationCtx.roles` on the press, every move, and the release,\n * so a binding's `opts.roles` or a tuning's `roles` can move one to another\n * key. Read them with {@link roleReader}. A binding's own `mods` are matched\n * once, at the press; these are read throughout.\n */\n modifierRoles?: ModifierRoles;\n}\n\n/**\n * Single registered action.\n */\nexport interface Action extends ActionDispatch, ActionPresentation {}\n\n/**\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/** `action`'s hover cursor for an invocation given `params`: its `cursor`,\n * asked when it is a function. */\nexport function actionCursor(\n action: Pick<Action, 'cursor'> | undefined,\n params?: Record<string, unknown>,\n): CursorSpec | undefined {\n const c = action?.cursor;\n return typeof c === 'function' ? c(params) : c;\n}\n","/**\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, type ActionUnavailable } from './action';\nimport { isDev } from '@weasel-js/react';\n\n/**\n * Result of evaluating an Action's `enabled` predicate.\n */\nexport interface ActionEnabledResult {\n enabled: boolean;\n reason?: ActionUnavailable;\n}\n\nconst enabledSlowWarned = new Set<string>();\nconst enabledThrewWarned = new Set<string>();\nconst ENABLED_BUDGET_MS = 4;\n/**\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 at?: { x: number; y: number },\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, at);\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/**\n * Safely evaluate an action's `active` predicate. `undefined` for an action\n * with no pressed state; a predicate that throws reads as not active.\n */\nexport function evaluateActive(action: Action, deps?: ActionDeps): boolean | undefined {\n if (!action.active) return undefined;\n try {\n return action.active(deps) === true;\n } catch {\n return false;\n }\n}\n","/**\n * Shared dep-bag builder — the single implementation behind both the gesture\n * dispatcher's per-invocation `buildDeps` and `ActionsRegistry.trigger`'s\n * `requires` branch. Reads the action's declared `requires`, resolves each\n * name against the `DepRegistry`, and (dev builds only) wraps the bag in a\n * Proxy that warns on undeclared reads.\n */\nimport type { Action } from './action';\nimport type { DepRegistry } from './depNode';\nimport type { ActionDeps } from './invoker';\nimport { isDev } from '@weasel-js/react';\n\n/** True in dev builds; false in production. Tree-shakes the Proxy out of\n * prod entirely. (Mirrors the dispatcher's own `DEV` const.) */\nconst DEV = isDev();\n\n/** Build the deps bag for an action from its declared `requires`. */\nexport function buildDepsFromRequires(action: Action, depRegistry: DepRegistry): ActionDeps {\n const requires = action.requires ?? [];\n const entries = requires.map((name) => [name, depRegistry.get(name)]);\n const deps = Object.fromEntries(entries) as ActionDeps;\n\n // Dev-only: wrap deps in a Proxy that warns when the invoker reads a\n // key not declared in `requires`. Catches silent-failure-by-typo or\n // forgotten-requires (the #1 bug class in this codebase pre-Phase-14e).\n // Production builds: bypass the Proxy entirely (zero overhead).\n if (DEV) {\n const declared = new Set<string>(requires);\n return new Proxy(deps as Record<string, unknown>, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !declared.has(prop) && prop !== 'then') {\n const message =\n `[weasel:dispatcher] action \"${action.id}\" read deps.${prop} but did not declare it in \\`requires\\`. ` +\n `Add \\`requires: [...'${prop}']\\` to the descriptor or the dep will be undefined at runtime.`;\n // Warn first so the console trail survives even when the throw is\n // swallowed by a caller, then throw so the gesture fails visibly\n // instead of silently running without the dep.\n console.warn(message);\n throw new Error(message);\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as ActionDeps;\n }\n return deps;\n}\n","/**\n * The tree both input registries hang on. A provider is a root; every canvas\n * mounts a scope under the registry in scope; a yoke sits between the two. A\n * registration lives in the node it was made in, and a lookup starts at a leaf\n * and walks up, so one canvas never answers for another.\n */\nimport { createEmitter, type Emitter } from '@weasel-js/registry';\n\n/** What every node of one tree shares: a version and the listeners to it. */\nexport interface ScopeTree {\n version: number;\n readonly listeners: Emitter;\n}\n\nexport class ScopeNode<N extends ScopeNode<N>> {\n readonly tree: ScopeTree;\n private readonly children: N[] = [];\n private activeChild: N | null = null;\n\n /** `descends`: whether reads made here answer from the active child down —\n * true for a root or a yoke, which chrome reads through; false for a scope,\n * which answers for itself even with a scope nested inside it. */\n constructor(readonly parent: N | null, readonly descends: boolean) {\n this.tree = parent ? parent.tree : { version: 0, listeners: createEmitter() };\n }\n\n /** Bump the tree's version and tell every listener in it. */\n changed(): void {\n this.tree.version++;\n this.tree.listeners.emit();\n }\n\n /** Join the parent's children, newest last; returns the leave. */\n mount(): () => void {\n const parent = this.parent;\n if (!parent) return () => {};\n parent.children.push(this as unknown as N);\n this.changed();\n let left = false;\n return () => {\n if (left) return;\n left = true;\n const i = parent.children.lastIndexOf(this as unknown as N);\n if (i !== -1) parent.children.splice(i, 1);\n if (parent.activeChild === (this as unknown as N)) parent.activeChild = null;\n this.changed();\n };\n }\n\n /** Make this node the one its ancestors resolve through. */\n activate(): void {\n let moved = false;\n for (let n = this as unknown as N; n.parent; n = n.parent) {\n if (n.parent.activeChild !== n) {\n n.parent.activeChild = n;\n moved = true;\n }\n }\n if (moved) this.changed();\n }\n\n /** The node a lookup made here starts from: down the active children, or the\n * newest where nothing has been activated yet. A yoke with no members yet\n * is passed over — there is no canvas behind it to answer. */\n leaf(): N {\n let n = this as unknown as N;\n for (;;) {\n const next: N | null = n.activeChild ?? n.newestMember();\n if (!next) return n;\n n = next;\n }\n }\n\n private newestMember(): N | null {\n for (let i = this.children.length - 1; i >= 0; i--) {\n const c = this.children[i]!;\n if (!(c.descends && c.children.length === 0)) return c;\n }\n return null;\n }\n\n /** Where a read made through this node starts. */\n start(): N {\n return this.descends ? this.leaf() : (this as unknown as N);\n }\n\n /** Whether this node is on the path a read from the root takes. */\n isActive(): boolean {\n let root = this as unknown as N;\n while (root.parent) root = root.parent;\n for (const n of root.leaf().chain()) if (n === (this as unknown as N)) return true;\n return false;\n }\n\n /** This node, then each ancestor up to the root. */\n *chain(): Generator<N> {\n for (let n: N | null = this as unknown as N; n; n = n.parent) yield n;\n }\n}\n\n/**\n * Push `value` onto an owner stack and hand back its release.\n *\n * Newest wins, but the release takes out *its own* entry wherever it now sits,\n * so a displaced owner leaving cannot disturb the one above it. A `null` value\n * registers nothing and releases to a no-op. Double-release safe.\n */\nexport function pushOwner<T>(stack: T[], value: T | null): () => void {\n if (value === null) return () => {};\n stack.push(value);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const i = stack.lastIndexOf(value);\n if (i !== -1) stack.splice(i, 1);\n };\n}\n","/**\n * The dep registry: named \"live source\" thunks. Actions declare\n * `requires: ['selection']`; the dispatcher calls `registry.get('selection')`\n * at invocation time to build a typed Deps bag.\n */\nimport type { DepSchema, DepName } from '../../index';\nimport { ScopeNode } from './scopeNode';\n\n/** Holds the live sources an action's declared dependencies resolve to.\n * Sources are thunks, read at invocation time, so an action never captures\n * stale state. */\nexport interface DepRegistry {\n /** Adds a live source for `name` over any already there. `below` answers\n * what the registry would without this source, so one can handle part of\n * a dep and hand the rest to the default it displaced. */\n register<K extends DepName>(name: K, source: DepSource<K>): () => void;\n get<K extends DepName>(name: K): DepSchema[K] | undefined;\n /** Hear that what the registry answers may have changed: a source was\n * registered or released anywhere in its tree, or an owner called\n * {@link DepRegistry.changed}. Returns the unsubscribe. A hand-built\n * registry whose answers never change leaves this and `changed` out. */\n subscribe?(listener: () => void): () => void;\n /** Say that a source's value changed. A source is a thunk read on demand,\n * so its owner is the only one who knows; chrome showing an action's\n * `enabled` or `active` state re-reads on this. */\n changed?(): void;\n /** Every name a `get` here would answer, sorted, with where its live\n * source sits. For inspection; a hand-built registry may leave it out. */\n list?(): readonly DepListing[];\n}\n\n/** A live source for dep `K`: a thunk read at invocation time. `below` reads\n * the source this one displaced, under it in its scope or in a scope above. */\nexport type DepSource<K extends DepName> = (below: () => DepSchema[K] | undefined) => DepSchema[K];\n\n/** One name a dep registry answers, as {@link DepRegistry.list} reports it. */\nexport interface DepListing {\n name: string;\n /** How many scopes above the asking one the live source was registered: 0 for its own. */\n depth: number;\n /** How many sources that scope holds under the name, the live one included. */\n stacked: number;\n}\n\n/** One node of the dep tree: the sources registered at it, over its parent's.\n * Each name holds a stack of sources, newest live, so a displaced source is\n * restored when the one above it leaves. */\nexport class DepNode extends ScopeNode<DepNode> {\n private readonly sources = new Map<string, Source[]>();\n\n readonly registry: DepRegistry = {\n register: <K extends DepName>(name: K, source: DepSource<K>) => {\n const key = name as string;\n const entry = source as Source;\n const stack = this.sources.get(key);\n if (stack) stack.push(entry);\n else this.sources.set(key, [entry]);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const cur = this.sources.get(key);\n if (!cur) return;\n // Our own entry, wherever it now sits: a source already displaced must\n // take itself out without disturbing the one above it.\n const i = cur.lastIndexOf(entry);\n if (i === -1) return;\n cur.splice(i, 1);\n if (cur.length === 0) this.sources.delete(key);\n this.changed();\n };\n },\n get: <K extends DepName>(name: K) => {\n const stacks = [...this.start().chain()].map((n) => n.sources.get(name as string) ?? []);\n return readFrom(stacks, 0, (stacks[0]?.length ?? 0) - 1) as DepSchema[K] | undefined;\n },\n subscribe: (listener: () => void) => this.tree.listeners.subscribe(listener),\n list: () => {\n const found = new Map<string, DepListing>();\n let depth = 0;\n for (const n of this.start().chain()) {\n for (const [name, stack] of n.sources) {\n if (!found.has(name)) found.set(name, { name, depth, stacked: stack.length });\n }\n depth++;\n }\n return [...found.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n },\n changed: () => this.changed(),\n };\n\n constructor(parent: DepNode | null, descends: boolean) {\n super(parent, descends);\n NODES.set(this.registry, this);\n }\n}\n\ntype Source = (below: () => unknown) => unknown;\n\n/** The source at `stacks[scope][index]`, or the first one under it, read with\n * its own `below`. `stacks` runs from the asking scope outward. */\nfunction readFrom(stacks: readonly (readonly Source[])[], scope: number, index: number): unknown {\n if (scope >= stacks.length) return undefined;\n if (index < 0) return readFrom(stacks, scope + 1, (stacks[scope + 1]?.length ?? 0) - 1);\n return stacks[scope]![index]!(() => readFrom(stacks, scope, index - 1));\n}\n\nconst NODES = new WeakMap<DepRegistry, DepNode>();\n\n/** The tree node behind `registry`, when it is one of ours. */\nexport function depNodeOf(registry: DepRegistry | null): DepNode | null {\n return registry ? (NODES.get(registry) ?? null) : null;\n}\n\n/**\n * A stock dep registry with no parent: what `<DepRegistryProvider>` mounts,\n * for a dispatcher driven without React. Sources registered under one name\n * stack, newest live, and releasing one restores the one beneath it.\n */\nexport function createDepRegistry(): DepRegistry {\n return new DepNode(null, true).registry;\n}\n","/**\n * The actions store contract and the `actions` prop that seeds it. The\n * provider that implements this lives in `ActionsProvider.tsx`; nothing here\n * touches React.\n */\nimport type { GestureSpec, PhaseSpec } from '@weasel-js/gestures';\nimport type { BoundGesture } from './binding';\nimport type { Action } from './action';\nimport type { ActionTuning } from './tuning';\nimport type { BindingOverrides, ResolvedBindingOverrides } from './bindingOverrides';\nimport { RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, type PhaseAtom } from '../../tools/routing/routeGrammar';\nimport type { Dispatcher, UiOngoingControl } from '../dispatcher/dispatcher';\nexport type { UiOngoingControl } from '../dispatcher/dispatcher';\n\n\n\n\n\n/**\n * Partial override or full descriptor passed via `<SceneCanvas actions={...}>`.\n * `null` disables a default at this id.\n */\nexport type ActionEntry = null | Partial<Action> | Action;\n\n/**\n * Shape of the `actions` prop on `<SceneCanvas>`. `null` disables all defaults.\n */\nexport type ActionsProp = null | Record<string, ActionEntry>;\n\n/**\n * Imperative API exposed by `useActionsRegistry()`.\n */\nexport interface ActionsRegistry {\n /** Add an action and return its release. Registrants for one id stack,\n * newest live, so releasing yours uncovers whoever you displaced. Call it\n * from an effect and release it in that effect's cleanup — registering from\n * a render body pushes an entry per render and releases none. */\n register(action: Action): () => void;\n /** Drop every registrant of `id`. This is the \"this action should not exist\"\n * door, not a release — for that, call what `register` returned. */\n unregister(id: string): void;\n /** Declare `id` not for this scope: it stays registered wherever it was,\n * but here — and in scopes below — it lists as absent and neither\n * `trigger` nor `begin` will fire it. Returns a release. This is the\n * \"not for me\" door — `unregister` is the \"should not exist\" one. */\n mute(id: string): () => void;\n /** Tune `id` here and in scopes below: its params and added bindings\n * apply to whichever descriptor is live for it, registered before the\n * tuning or after. Returns a release. See {@link ActionTuning}. */\n tune(id: string, tuning: ActionTuning): () => void;\n /** The params an invocation of `id` from this scope starts with when it\n * passes `given`: every tuning's params, `given` laid over them. What a\n * tool's chrome reads to show what the action it binds will do. */\n paramsOf(id: string, given?: Record<string, unknown>): Record<string, unknown>;\n /** Replace or remove bindings by id, here and in scopes below. Holders\n * merge: an inner scope's beats an outer one's, and a later one beats an\n * earlier one in the same scope. Returns a release. See {@link BindingOverrides}. */\n overrideBindings(overrides: BindingOverrides): () => void;\n /** Every override in force from this scope, read into specs. */\n bindingOverrides(): ResolvedBindingOverrides;\n list(): readonly Action[];\n /** Fire an immediate-invoker action by id. The optional `params` arg is\n * forwarded to `ImmediateInvoker.run` as its second argument — use it for\n * parametric actions (e.g. `trigger('tool.activate', { toolId: 'rect' })`).\n * Returns whether it ran one: `false` for an unknown id, for an action\n * whose `enabled` refuses, and for an ongoing-invoker action, which\n * `trigger` cannot reach (see `begin`). `enabled` is asked at\n * `{ x: params.worldX, y: params.worldY }` when both are numbers, and with\n * no point otherwise. */\n trigger(id: string, params?: Record<string, unknown>): boolean;\n /** Show what firing `id` with `params` would do, by its `Action.preview`,\n * and return what takes it down; calling that twice is harmless. Shows\n * nothing for an unknown id, one with no preview, and one whose `enabled`\n * refuses, asked as `trigger` asks it. */\n preview(id: string, params?: Record<string, unknown>): () => void;\n /**\n * Subscribe to registry mutations. The callback fires after any\n * `register`/`unregister` that changes the version. Returns an\n * unsubscribe function. Designed for `useSyncExternalStore`-driven\n * surfaces (e.g. `<ActionBar>` in `@weasel-js/ui`) that need to\n * re-render when the action set changes.\n */\n subscribe(listener: () => void): () => void;\n\n /**\n * Start an ongoing action driven by UI (color picker, opacity slider).\n * Returns a control object with `update(params)` and `end(reason)`.\n *\n * Returns `null` if no dispatcher is wired into this registry, the\n * action is unknown, or its invoker is not ongoing.\n *\n * See `Dispatcher.beginUiOngoing` for full semantics including\n * auto-commit when a prior UI handle for the same action is in flight.\n */\n begin(id: string, params?: Record<string, unknown>): UiOngoingControl | null;\n\n /** Wire a dispatcher into the registry so `begin()` can delegate to it.\n * Returns a release that takes out only this dispatcher; a `null` wires\n * nothing. */\n setDispatcher(d: Dispatcher | null): () => void;\n\n /** Make this registry's scope the one chrome above it reaches, and the one\n * keys go to: `trigger`, `begin` and `list` on any ancestor then answer from\n * here. A dispatcher calls it on the pointerdown and wheel that land in its\n * scope; moving DOM focus alone does not. */\n activate(): void;\n\n /** Whether a lookup made from the root of this registry's tree starts here.\n * A dispatcher with no canvas to press in asks this before handling a\n * keystroke. */\n isActive(): boolean;\n\n /** Whether this registry's scope is the one last activated on the page, in\n * any tree: the question a canvas's dispatcher asks before handling a key\n * or a paste that reached the page. No scope holds the keys before the\n * first activation. */\n holdsKeys(): boolean;\n\n /** Let go of the keys if this scope holds them, as its canvas unmounts. */\n dropKeys(): void;\n}\n\n// ─── Registration-time validation ─────────────────────────────────────────\n\n/** Validate that `id` is usable as an action id in the route grammar.\n * Rejects ids that start with a reserved sigil (would shadow future\n * grammar extensions) and ids that collide with phase keywords (would\n * parse as the bare-phase shorthand). Mirrors `defineTool`'s tool-id\n * validation. */\nexport function validateActionId(id: string): void {\n if (id.length === 0) {\n throw new Error(`weasel: action id may not be empty`);\n }\n if (RESERVED_ID_PREFIXES.has(id[0]!)) {\n throw new Error(\n `weasel: action 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: action id \"${id}\" collides with a reserved phase keyword ` +\n `(reserved: ${[...RESERVED_ID_NAMES].join(', ')})`,\n );\n }\n}\n\n/** Reject any '&'-channel phase atom in an Action's defaultBinding —\n * actions have no owning tool, so '&' can't resolve. Tool-side bindings\n * (Tool.bindings) are the right place for '&' atoms. */\nexport function validateActionDefaultBinding(action: Action): void {\n const gs = action.defaultBinding;\n if (!gs) return;\n const entries: BoundGesture[] = Array.isArray(gs) ? gs : [gs as BoundGesture];\n for (const entry of entries) {\n const spec = ('kind' in entry ? entry : entry.spec) as GestureSpec;\n const phase: PhaseSpec | undefined = spec.phase;\n if (phase === undefined) continue;\n const atoms: readonly PhaseAtom[] = Array.isArray(phase)\n ? phase\n : [{ channel: '&', phase: phase }];\n for (const atom of atoms) {\n if (atom.channel === '&') {\n throw new Error(\n `weasel: action \"${action.id}\" defaultBinding uses '&' channel ` +\n `which has no owning tool to resolve to. Use a named tool channel ` +\n `(e.g. '[rect:engaged]') or '*' instead, or move this binding to ` +\n `the tool's own Tool.bindings.`,\n );\n }\n }\n }\n}\n\n","/**\n * Invoker — pluggable invocation strategy for an Action.\n *\n * An Action's `invoker` field describes how it's run. `immediate` invokers\n * fire once (delete, align, undo). `ongoing` invokers open a phase machine\n * driven by the dispatcher (move, resize, pinch-zoom).\n */\n\nimport type { ModifierState, ResizeAnchor } from '../../vocabulary';\nimport type { ClaimableGesture } from '@weasel-js/gestures';\nimport type { Point } from '@weasel-js/geom';\n\nimport type { CursorSpec } from '@weasel-js/cursor';\nimport type { DepSchema } from '../../index';\nimport type { OngoingOverlay } from './overlay';\nimport type { RoleRebinds } from './modifierRoles';\n\nexport type { ModifierState } from '../../vocabulary';\n\n/** A 2D point in either world or screen coordinates; geom's `Point`. */\nexport type Point2 = Point;\n\n/**\n * Which UI affordance was hit at pointerdown. Populated by the dispatcher when\n * the `affordanceAt` thunk is provided to `useGestureDispatcher`.\n *\n * `kind` is a discriminator string:\n * - `'handle:top-left'` / `'handle:top-right'` / `'handle:bottom-left'` /\n * `'handle:bottom-right'` — corner resize handles.\n * - `'handle:top'` / `'handle:right'` / `'handle:bottom'` / `'handle:left'` —\n * edge resize handles.\n * - `'rotate-handle'` — the rotation affordance.\n * - `'anchor:N'` — a path anchor at index N.\n */\nexport interface AffordanceHit {\n /** Discriminator string, e.g. `'handle:bottom-right'`. */\n kind: string;\n /** Id of whatever produced this hit — a kit affordance's `id`, or the\n * registered layer's id. */\n owner?: string;\n /** `'exclusive'` means no binding may act on this point unless its target\n * consults the affordance. `'shared'` (the default) competes on scope and\n * specificity as bindings always have. */\n strength?: 'exclusive' | 'shared';\n /** Which gestures an exclusive claim bars. Omitted bars all of them. */\n claimedKinds?: readonly ClaimableGesture[];\n /** World-space fixed/pivot point. For resize: opposite corner. For rotate: pivot. */\n fixedPoint?: { x: number; y: number };\n /** Which nodes this affordance belongs to. */\n targetIds?: string[];\n /** Set only when `kind` matches `'handle:*'`: which corner or edge stays\n * fixed during a resize; `'free'` on the axis an edge handle leaves alone. */\n anchor?: ResizeAnchor;\n /** Cursor to show while the pointer hovers this affordance (no gesture in\n * flight). Unset falls through to action-cursor prediction, then to the\n * active tool's cursor. */\n cursor?: CursorSpec;\n /**\n * Free-form payload from whatever produced the hit, carried through to the\n * matching action untouched. Kit affordances leave it unset; it exists for\n * a registered layer's own chrome, where the hit-test already resolved\n * *which* of its pieces was hit.\n */\n payload?: unknown;\n}\n\n/**\n * One accumulated point on a drag trail: world-space position plus whatever\n * stylus state the originating `PointerEvent` carried.\n *\n * The stylus fields are absent for mouse/touch on browsers that don't report\n * them, and for synthetic events.\n */\nexport interface DragSample extends Point2 {\n /** 0..1. Mouse/touch report 0.5 while a button is held, per the spec. */\n pressure?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltX?: number;\n /** Degrees, ±90. Zero for mouse/touch. */\n tiltY?: number;\n}\n\n/** Per-invocation runtime context the dispatcher hands to an Invoker.\n * Gesture-kind-specific fields (`drag`, `wheel`, `multiTouch`, `key`) are\n * populated only for matching gesture kinds. */\nexport interface InvocationCtx {\n world: Point2;\n /**\n * The pointer in client/screen pixels, for an action that has to place DOM\n * at the pointer. Absent on every invocation whose event carries no client\n * coordinates — a keystroke, a UI-driven trigger, a synthetic probe — so\n * read it with a fallback rather than assuming a point.\n *\n * A view-mutating drag wants `drag.screenDelta`, not the difference of two\n * of these: world deltas are self-referential mid-pan, and so is any delta\n * taken across a view change.\n */\n screen?: Point2;\n modifiers: ModifierState;\n deps: ActionDeps;\n drag?: {\n start: Point2;\n current: Point2;\n delta: Point2;\n /**\n * Drag delta in client/screen coordinates (CSS pixels from the drag\n * origin). Use this — never `delta` — for any action whose effect\n * mutates the viewport itself (pan, view-zoom), because world-space\n * deltas become self-referential as the view shifts mid-drag.\n *\n * Absent when the underlying pointer events carried no\n * `clientX`/`clientY`.\n */\n screenDelta?: Point2;\n affordance?: AffordanceHit;\n /**\n * Full pointermove history for the current drag, in world space, with\n * per-sample stylus state when the browser reported it.\n * Available only during `onMove` and `onEnd` calls (not on `start`).\n *\n * During `onMove` this is the dispatcher's live accumulator, and it grows\n * under you — read it, don't retain it. On `onEnd` it is a snapshot, so\n * that is where an action that keeps the trail should take it.\n */\n points?: DragSample[];\n };\n wheel?: { deltaX: number; deltaY: number; deltaZ: number };\n /** One `pinch` sample: `scale` is a multiplier since the previous sample,\n * `rotation` degrees since it. See `PinchEvent`. */\n pinch?: { scale: number; rotation: number };\n multiTouch?: {\n /** Canvas-local CSS pixels — see `MultiTouchEvent.centroid`. Neither\n * `world` nor `screen`: it is the space `zoomAt` anchors in, so passing\n * it through `clientToWorld` removes the canvas origin twice. */\n centroid: Point2;\n /** Distance between the two primary pointers, in CSS pixels. */\n spread: number;\n /** Degrees the line between the two primary pointers has turned since\n * the gesture began, clockwise positive. It keeps counting past a half\n * turn. Zero where the events carry no `MultiTouchEvent.angle`. */\n rotation: number;\n /**\n * Pinch-zoom geometry, populated while a multitouch handle is in flight.\n * `startSpread` is the spread at the moment the gesture began.\n */\n pinch?: {\n startSpread: number;\n currentSpread: number;\n /** Canvas-local, same as the enclosing `centroid`. */\n centroid: Point2;\n };\n };\n key?: { key: string; repeat: boolean };\n /** What a carry over the surface brings: its payload, as `startCarry` was\n * handed it. Present for every event of a `carry` binding's gesture. */\n carry?: { type: string; value: unknown };\n /**\n * The view the input landed in, as the surface's view resolver assigned it:\n * a view id, or `null` for the surface's own camera. Absent where no\n * surface routed the input — a UI-driven trigger, a bare dispatcher.\n */\n viewId?: string | null;\n /**\n * Per-invocation parameters. Populated by `ActionsRegistry.begin()` for\n * UI-driven ongoing actions (color picker, opacity slider). The gesture\n * dispatcher does not populate this field; gesture-driven actions receive\n * params via `BindingOpts.params` on `start` (the `opts` arg).\n */\n params?: Record<string, unknown>;\n /**\n * Which of the action's `modifierRoles` are held for this event, by role\n * id. The dispatcher fills it on every event of a gesture whose action\n * declares roles; absent otherwise. Read it through `roleReader`, which\n * falls back to the roles' default keys where it is absent.\n */\n roles?: Readonly<Record<string, boolean>>;\n}\n\n/** Per-invocation options the dispatcher reads from a `GestureBinding`'s\n * `opts` field and passes to `OngoingInvoker.start`. */\nexport interface BindingOpts {\n /** The id a binding override names this binding by, `<owner>.<role>`:\n * `undo.key`, `rect.drag`, `nudge.left.big`. Without one it is its owner and\n * its position (`<entry>#<n>`, `<action>@<n>`), which moves when the defaults\n * are reordered, so a binding a host may persist an override for declares one. */\n id?: string;\n /** Gesture behaviors the action's own invoker runs. Routing carries the\n * array to the action and never reads an element, so the element type is\n * open here; `@weasel-js/core` narrows it. */\n behaviors?: unknown[];\n /** Per-binding action parameters, which an immediate invoker reads via the\n * second arg to `run`.\n *\n * May also be a thunk evaluated each time the value is needed, so a tool\n * can close over refs that mutate during a gesture (e.g. polygon `sides`\n * adjusted mid-drag via ArrowUp). An ongoing invoker that wants the latest\n * values at commit re-calls it inside `onEnd` via\n * `resolveParams(opts?.params)`. */\n params?: Record<string, unknown> | (() => Record<string, unknown>);\n /**\n * The views this binding is live in, by id, where `null` is the surface's\n * own camera. Omitted means every view.\n *\n * A binding that names the view an input landed in outranks every binding\n * that does not, whatever their scope tiers: naming a view is the most\n * specific thing a binding can say about where it applies. Without that, a\n * drag bound inside a minimap view loses to the active tool's marquee.\n */\n views?: readonly (string | null)[];\n /**\n * Says this binding is declared ahead of another on the same input on\n * purpose: its action declines through `enabled()` when the input is not its\n * to take, and the next binding fires. The dispatcher does that for any\n * binding; this tells the route-conflict check the order is the design.\n */\n yields?: boolean;\n /**\n * For a key binding: live while the pointer is over the surface, whichever\n * canvas holds the keys, and only then. For a key that means \"here\" — a\n * magnifier's peek — on a page with more than one surface that hears it.\n */\n over?: boolean;\n /**\n * Keys for some of the action's `modifierRoles` on this binding, by role\n * id, over the action's defaults and any tuning's.\n */\n roles?: RoleRebinds;\n}\n\n/** Resolve `BindingOpts.params` to a concrete record (calling the thunk if\n * needed). Returns `undefined` for absent params. */\nexport function resolveParams(\n params: BindingOpts['params'],\n): Record<string, unknown> | undefined {\n if (params === undefined) return undefined;\n return typeof params === 'function' ? params() : params;\n}\n\n/** The deps an action receives, composed per call from what it `requires`.\n * Each name resolves to its {@link DepSchema} entry, and is absent when no\n * source registered it; a name nothing has declared passes through as\n * `unknown`. */\nexport interface ActionDeps extends Partial<DepSchema> {\n [k: string]: unknown;\n}\n\nexport type { OngoingOverlay, OverlayRole } from './overlay';\n\n/** Handle returned from an `OngoingInvoker.start`. The dispatcher pumps\n * `onMove` on subsequent input events of the same gesture and calls\n * `onEnd` exactly once (with `'commit'` on natural completion or `'cancel'`\n * on pointercancel / blur / escape). */\nexport interface OngoingHandle {\n /**\n * Optional logical action kind — a stable, human-readable tag the\n * dispatcher exposes via `getActiveAction()`, e.g. `'marquee'`, `'move'`,\n * `'resize'`, `'pan'`.\n *\n * When omitted, `getActiveAction().kind` reports `null` even though a\n * handle is in flight.\n */\n kind?: string;\n\n /**\n * The cursor this gesture shows now, read after every move. Wins over the\n * action's `activeCursor`, for a cursor that follows the gesture — the\n * rotate glyph turning about its pivot. `undefined` defers to the action.\n */\n cursor?(): CursorSpec | undefined;\n\n onMove?(ctx: InvocationCtx): void;\n onEnd?(ctx: InvocationCtx, reason: 'commit' | 'cancel'): void;\n\n /**\n * Optional preview surface: the in-flight state the canvas's preview-ghost\n * layer renders on top of the committed scene during the gesture.\n *\n * `previewIds()` enumerates the displaced node ids; `previewPose(id)`\n * returns the interim pose for one of them (shape opaque — the canvas\n * casts to its `TPose` parameter). `previewIds` returning `null`, or\n * omitted, means \"no preview this gesture\". An id with no `previewPose`\n * is shown at its effective pose: an action that publishes its poses to\n * the scene's pose overrides, as move, resize and rotate do, leaves\n * `previewPose` out rather than answering the same pose twice. `<SceneCanvas>`\n * also shows both answers to the scene as overrides (core's\n * `publishPreviews`), so what derives from a previewed node follows it.\n */\n previewIds?(): Iterable<string> | null;\n previewPose?(id: string): unknown | null;\n\n /**\n * Subset of `previewIds()` the ghost layer paints at full opacity. The\n * ghost alpha says \"this is in flight under the pointer\"; a node the\n * gesture merely displaces — a layout sibling reflowing into its\n * destination slot — is not, and reads better settled. Honored at\n * subtree-root granularity.\n */\n previewOpaqueIds?(): Iterable<string> | null;\n\n /**\n * When `false`, the preview-ghost layer paints the ghost AND the source\n * node stays visible at its committed pose, as a clone wants. Defaults to\n * `true`: the ghost replaces the source during the gesture.\n */\n previewHidesSource?: boolean;\n\n /**\n * Optional per-id preview *data*, for a gesture that mutates `node.data`\n * (e.g. anchor-edit on nodes that store the polygon on `data.path`) rather\n * than, or in addition to, the pose. Falls back to the committed\n * `node.data` when null/absent.\n */\n previewData?(id: string): unknown | null;\n\n /**\n * Optional chrome surface: a non-ghost visual (marquee rectangle, lasso\n * polyline) painted while the gesture is in flight — one, or a list for a\n * gesture showing several runs at once. Returning `null`, or omitting the\n * method, means \"no overlay this gesture\". Read it through\n * {@link overlaysOf}, which answers a list either way.\n */\n overlay?(): OngoingOverlay | readonly OngoingOverlay[] | null;\n\n /**\n * A wheel turned while this gesture is in flight — scrubbing a value the\n * drag is using, say. Return `true` to claim the wheel, so no wheel binding\n * (the viewport's zoom or pan) sees it; anything else lets it through.\n * Omit it and the wheel goes to the bindings as usual.\n */\n onWheel?(ctx: InvocationCtx): boolean | void;\n}\n\n/** Fire-once invocation. Runs to completion synchronously (or fires off an\n * async side-effect; the registry doesn't wait). */\nexport interface ImmediateInvoker {\n timing: 'immediate';\n /** `params` carries the matched binding's opts.params. Invoked from the\n * command palette, or anywhere else with no per-binding context, `params`\n * is undefined; descriptors should default to a sensible variant. */\n run(deps: ActionDeps, params?: Record<string, unknown>): void;\n}\n\n/** Phase-machine invocation. `start` opens the phase and returns the handle\n * the dispatcher pumps. */\nexport interface OngoingInvoker {\n timing: 'ongoing';\n start(ctx: InvocationCtx, opts?: BindingOpts): OngoingHandle;\n}\n\n/** Pluggable invocation strategy for an Action. */\nexport type Invoker = ImmediateInvoker | OngoingInvoker;\n","/**\n * Modifier roles: the modifiers an ongoing action reads while it runs, named\n * by what they do rather than which key they are, so a binding or a tuning can\n * move one to another key without forking the action.\n */\nimport { isApplePlatform, type ModifierKey } from '@weasel-js/gestures';\nimport type { ModifierState } from '../../vocabulary';\n\n/** The keys that hold a role: any one of them held holds it. `'mod'` is Cmd\n * on a Mac and Ctrl elsewhere. An empty list never holds it. */\nexport type RoleKeys = readonly ModifierKey[];\n\n/** One modifier an action reads mid-gesture. */\nexport interface ModifierRole {\n label: string;\n /** The keys that hold it unless a tuning or a binding says otherwise. */\n keys: RoleKeys;\n}\n\n/** An action's roles by id, e.g. `'handle.holdAngle'`. */\nexport type ModifierRoles = Readonly<Record<string, ModifierRole>>;\n\n/** Keys a tuning or a binding gives some of an action's roles. */\nexport type RoleRebinds = Readonly<Record<string, RoleKeys>>;\n\n/** Whether any of `keys` is held. */\nexport function keysHeld(keys: RoleKeys, modifiers: ModifierState, isMac: boolean): boolean {\n return keys.some((k) => {\n if (k === 'mod') return isMac ? modifiers.meta : modifiers.ctrl;\n return modifiers[k];\n });\n}\n\n/** The keys each of `roles` answers to with `rebinds` laid over them, or\n * undefined when the action declares none. A rebind naming a role the action\n * does not declare is dropped. */\nexport function roleKeysOf(\n roles: ModifierRoles | undefined,\n rebinds?: RoleRebinds,\n): Readonly<Record<string, RoleKeys>> | undefined {\n if (!roles) return undefined;\n const out: Record<string, RoleKeys> = {};\n for (const id of Object.keys(roles)) out[id] = rebinds?.[id] ?? roles[id].keys;\n return out;\n}\n\n/** `keys` with each `'mod'` written as the key it is on this platform. */\nexport function platformRoleKeys(\n keys: Readonly<Record<string, RoleKeys>>,\n isMac: boolean,\n): Readonly<Record<string, RoleKeys>> {\n const out: Record<string, RoleKeys> = {};\n for (const id of Object.keys(keys)) out[id] = keys[id].map((k) => (k === 'mod' ? (isMac ? 'meta' : 'ctrl') : k));\n return out;\n}\n\n/** Which roles `modifiers` hold. */\nexport function resolveRoles(\n keys: Readonly<Record<string, RoleKeys>>,\n modifiers: ModifierState,\n isMac: boolean,\n): Record<string, boolean> {\n const out: Record<string, boolean> = {};\n for (const id of Object.keys(keys)) out[id] = keysHeld(keys[id], modifiers, isMac);\n return out;\n}\n\n/** `roles` with `rebinds` written into their keys. */\nexport function rebindRoles(roles: ModifierRoles, rebinds: RoleRebinds): ModifierRoles {\n const out: Record<string, ModifierRole> = {};\n for (const id of Object.keys(roles)) {\n out[id] = rebinds[id] ? { ...roles[id], keys: rebinds[id] } : roles[id];\n }\n return out;\n}\n\n/**\n * A reader for an action's own roles. It answers from `ctx.roles`, which the\n * dispatcher resolves on every event, and falls back to the role's default\n * keys where nothing resolved them: an invoker called directly, or a context\n * a cancel-all built with no event.\n */\nexport function roleReader<R extends ModifierRoles>(roles: R) {\n return (ctx: { roles?: Readonly<Record<string, boolean>>; modifiers: ModifierState }, id: keyof R & string): boolean =>\n ctx.roles?.[id] ?? keysHeld(roles[id].keys, ctx.modifiers, isApplePlatform());\n}\n","/**\n * Tuning: what a host changes about an action it did not write — the params\n * every invocation starts from, and bindings added beside the action's own —\n * without restating the descriptor. `ActionsRegistry.tune` holds tunings and\n * applies them to whatever descriptor is live for the id.\n */\nimport type { GestureSpec } from '@weasel-js/gestures';\nimport type { Action } from './action';\nimport type { BoundGesture } from './binding';\nimport { resolveParams, type BindingOpts, type Invoker } from './invoker';\nimport { rebindRoles, type RoleRebinds } from './modifierRoles';\n\n/** An action's params, or a thunk read each time the action asks for them. */\nexport type ActionParams<P = Record<string, unknown>> = Partial<P> | (() => Partial<P>);\n\n/** A binding added for an action: a gesture alone, or a gesture with the\n * options it passes — the {@link BoundGesture} shape, its params typed. */\nexport type TunedBinding<P = Record<string, unknown>> =\n | GestureSpec\n | { spec: GestureSpec; opts: Omit<BindingOpts, 'params'> & { params?: ActionParams<P> } };\n\n/** What a host changes about one action. */\nexport interface ActionTuning<P = Record<string, unknown>> {\n /** Params every invocation starts from. What a binding or a `trigger` call\n * passes is laid over them, so these fill in what it leaves out. A thunk is\n * read on every call, and an ongoing action resolving its `opts.params`\n * mid-gesture sees the value as it is then. */\n params?: ActionParams<P>;\n /** Bindings added after the action's own `defaultBinding`. */\n bindings?: readonly TunedBinding<P>[];\n /** Keys for some of the action's `modifierRoles`, by role id. A binding's\n * own `opts.roles` is laid over these. */\n roles?: RoleRebinds;\n}\n\ntype Params = BindingOpts['params'];\n\nconst WRAPS = new WeakMap<Invoker, { inner: Invoker; params: ActionParams }>();\n\nfunction layered(under: ActionParams, over: Params): Params {\n if (typeof under !== 'function' && typeof over !== 'function') return tunedParams([{ params: under }], over);\n return () => tunedParams([{ params: under }], resolveParams(over));\n}\n\nfunction wrapInvoker(invoker: Invoker, params: ActionParams): Invoker {\n for (let w: Invoker | undefined = invoker; w; w = WRAPS.get(w)?.inner) {\n if (WRAPS.get(w)?.params === params) return invoker;\n }\n const base = (given: Record<string, unknown> | undefined) => tunedParams([{ params }], given);\n const wrapped: Invoker = invoker.timing === 'immediate'\n ? { timing: 'immediate', run: (deps, given) => invoker.run(deps, base(given)) }\n : {\n timing: 'ongoing',\n start: (ctx, opts) => invoker.start(\n ctx.params ? { ...ctx, params: base(ctx.params) } : ctx,\n { ...opts, params: layered(params, opts?.params) },\n ),\n };\n WRAPS.set(wrapped, { inner: invoker, params });\n return wrapped;\n}\n\nfunction withBindings(\n own: Action['defaultBinding'],\n added: readonly TunedBinding[],\n): BoundGesture[] {\n const base: BoundGesture[] = own === undefined ? [] : Array.isArray(own) ? own : [own];\n return [...base, ...(added as readonly BoundGesture[]).filter((b) => !base.includes(b))];\n}\n\nconst CURSOR_WRAPS = new WeakMap<object, { inner: Action['cursor']; params: ActionParams }>();\n\n/** A cursor that reads params, handed the tuning's under the call's. */\nfunction wrapCursor(cursor: Action['cursor'], params: ActionParams): Action['cursor'] {\n if (typeof cursor !== 'function') return cursor;\n for (let w: Action['cursor'] = cursor; typeof w === 'function'; w = CURSOR_WRAPS.get(w)?.inner) {\n if (CURSOR_WRAPS.get(w)?.params === params) return cursor;\n }\n const wrapped = (given: Record<string, unknown> | undefined) => cursor(tunedParams([{ params }], given));\n CURSOR_WRAPS.set(wrapped, { inner: cursor, params });\n return wrapped;\n}\n\nconst PREVIEW_WRAPS = new WeakMap<object, { inner: Action['preview']; params: ActionParams }>();\n\n/** A preview handed the tuning's params under the call's, as `run` is. */\nfunction wrapPreview(preview: Action['preview'], params: ActionParams): Action['preview'] {\n if (!preview) return preview;\n for (let w: Action['preview'] = preview; w; w = PREVIEW_WRAPS.get(w)?.inner) {\n if (PREVIEW_WRAPS.get(w)?.params === params) return preview;\n }\n const wrapped: NonNullable<Action['preview']> = (deps, given) => preview(deps, tunedParams([{ params }], given));\n PREVIEW_WRAPS.set(wrapped, { inner: preview, params });\n return wrapped;\n}\n\nfunction tuneOnce(action: Action, tuning: ActionTuning): Action {\n const invoker = tuning.params && action.invoker ? wrapInvoker(action.invoker, tuning.params) : action.invoker;\n const cursor = tuning.params ? wrapCursor(action.cursor, tuning.params) : action.cursor;\n const preview = tuning.params ? wrapPreview(action.preview, tuning.params) : action.preview;\n const bindings = tuning.bindings?.length ? withBindings(action.defaultBinding, tuning.bindings) : null;\n const modifierRoles = tuning.roles && action.modifierRoles ? rebindRoles(action.modifierRoles, tuning.roles) : null;\n if (\n invoker === action.invoker && cursor === action.cursor && preview === action.preview &&\n bindings === null && modifierRoles === null\n ) {\n return action;\n }\n return {\n ...action,\n ...(modifierRoles ? { modifierRoles } : {}),\n ...(invoker ? { invoker } : {}),\n ...(cursor ? { cursor } : {}),\n ...(preview ? { preview } : {}),\n ...(bindings ? { defaultBinding: bindings } : {}),\n };\n}\n\n/** The params an invocation passing `given` starts with under `tunings`:\n * each tuning's params over the one before, and `given` over them all. */\nexport function tunedParams(\n tunings: readonly ActionTuning[],\n given?: Record<string, unknown>,\n): Record<string, unknown> {\n let out: Record<string, unknown> = {};\n for (const t of tunings) out = { ...out, ...resolveParams(t.params as Params) };\n return { ...out, ...given };\n}\n\n/** `action` with each tuning applied in turn, a later one's params over an\n * earlier one's. Applying a tuning to a copy it already tuned changes nothing. */\nexport function tuneAction(action: Action, tunings: readonly ActionTuning[]): Action {\n let out = action;\n for (const t of tunings) out = tuneOnce(out, t);\n return out;\n}\n","/**\n * Binding overrides: a host's replacements for bindings it did not write,\n * keyed by binding id. An override replaces or removes one binding, on an\n * action or on a contribution alike; adding a key beside the defaults is\n * `tune`'s job.\n */\nimport { bindingSpec, type BindingOverrideInput, type GestureSpec } from '@weasel-js/gestures';\nimport type { Action } from './action';\nimport { actionBindings, type BoundGesture, type GestureBinding } from './binding';\n\n/** Overrides by binding id: a route string or spec to bind instead, or `null` to unbind. */\nexport type BindingOverrides = Readonly<Record<string, BindingOverrideInput>>;\n\n/** Overrides read into specs, one per binding id. */\nexport type ResolvedBindingOverrides = ReadonlyMap<string, GestureSpec | null>;\n\nexport const NO_OVERRIDES: ResolvedBindingOverrides = new Map();\n\n/** A binding's id: its declared `opts.id`, else its owner and its position\n * there — `<entry>#<n>` for an entry's binding (`ownerId`), `<action>@<n>` for\n * an action's own (`ownerId` null), so an entry and an action of one id never\n * share a derived id. */\nexport function bindingId(b: GestureBinding, ownerId: string | null, index: number): string {\n return b.opts?.id ?? (ownerId === null ? `${b.actionId}@${index}` : `${ownerId}#${index}`);\n}\n\n/** Merge override maps into one, a later map winning per id. A route string\n * that does not parse is skipped with a warning, leaving the binding as it was. */\nexport function resolveBindingOverrides(maps: readonly BindingOverrides[]): ResolvedBindingOverrides {\n if (maps.length === 0) return NO_OVERRIDES;\n const out = new Map<string, GestureSpec | null>();\n for (const map of maps) {\n for (const [id, input] of Object.entries(map)) {\n try {\n out.set(id, bindingSpec(input));\n } catch (err) {\n console.warn(`weasel: binding override \"${id}\" is not a route: ${(err as Error).message}`);\n }\n }\n }\n return out;\n}\n\n/** `b` under its override: the same binding, one with another spec, or `null` when unbound. */\nexport function overridden(\n b: GestureBinding,\n id: string,\n overrides: ResolvedBindingOverrides,\n): GestureBinding | null {\n if (!overrides.has(id)) return b;\n const spec = overrides.get(id)!;\n return spec === null ? null : { ...b, spec };\n}\n\n/** The bindings `ownerId` declares, each under its override, the unbound ones\n * left out: what dispatch routes by. A `null` owner is an action's own. */\nexport function overriddenBindings(\n bindings: readonly GestureBinding[],\n ownerId: string | null,\n overrides: ResolvedBindingOverrides = NO_OVERRIDES,\n): GestureBinding[] {\n const out: GestureBinding[] = [];\n bindings.forEach((b, i) => {\n const next = overridden(b, bindingId(b, ownerId, i), overrides);\n if (next) out.push(next);\n });\n return out;\n}\n\n/** `action` with `overrides` applied to its own bindings, each keeping its id,\n * so every reader of `defaultBinding` — dispatch, menus, chips — sees the same keys. */\nexport function overrideActionBindings(action: Action, overrides: ResolvedBindingOverrides): Action {\n if (overrides.size === 0 || action.defaultBinding === undefined) return action;\n const declared = actionBindings(action);\n if (!declared.some((b, i) => overrides.has(bindingId(b, null, i)))) return action;\n const kept: BoundGesture[] = [];\n declared.forEach((b, i) => {\n const id = bindingId(b, null, i);\n const next = overridden(b, id, overrides);\n if (next) kept.push({ spec: next.spec, opts: { ...next.opts, id } });\n });\n return { ...action, defaultBinding: kept };\n}\n","/** What the dispatcher reads straight off an input event. */\nimport type { Carried } from '../actions/action';\nimport type { ModifierState } from '../../vocabulary';\nimport type { InputEvent } from './matcher';\n\n/**\n * Modifier flags as an immediate invoker sees them, in the kit's\n * `ModifierState` spelling rather than the DOM's `*Key` one.\n *\n * Most actions should still express modifier semantics as separate bindings\n * with `opts.params` — that is what makes them visible to conflict detection\n * and the inspector. This is for the cases where the modifier is data rather\n * than a route.\n */\nexport function modifierStateOf(e: {\n altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean;\n}): ModifierState {\n return { alt: e.altKey, ctrl: e.ctrlKey, meta: e.metaKey, shift: e.shiftKey };\n}\n\n/** The world point an event landed on, for `Action.enabled`'s position\n * argument. Undefined for events with no position (keys, drops, pastes). */\nexport function worldPointOf(event: InputEvent): { x: number; y: number } | undefined {\n switch (event.kind) {\n case 'pointerdown':\n case 'hover':\n case 'longpress':\n case 'click':\n case 'doubleclick':\n case 'contextmenu':\n return event.x !== undefined && event.y !== undefined ? { x: event.x, y: event.y } : undefined;\n case 'carry':\n return { x: event.x, y: event.y };\n default:\n return undefined;\n }\n}\n\n/** What a drop, a paste or a carry brings, for `Action.enabled`'s `carried`\n * argument. Undefined for every other event. */\nexport function carriedBy(event: InputEvent): Carried | undefined {\n if (event.kind === 'carry') return { items: [], carry: { type: event.type, value: event.value } };\n return event.kind === 'drop' || event.kind === 'paste' ? { items: event.items } : undefined;\n}\n\n/**\n * The params an immediate invoker runs with: what the event carries, under the\n * binding's own `resolved` params. An immediate invoker gets `(deps, params)`\n * and no `InvocationCtx`, so this is where it reads deltas and positions.\n */\nexport function immediateParams(\n event: InputEvent,\n resolved: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n switch (event.kind) {\n case 'wheel':\n return {\n deltaX: event.deltaX, deltaY: event.deltaY,\n clientX: event.clientX, clientY: event.clientY,\n affordance: event.affordance,\n ...resolved,\n };\n case 'pinch':\n return {\n scale: event.scale, rotation: event.rotation,\n clientX: event.clientX, clientY: event.clientY,\n affordance: event.affordance,\n ...resolved,\n };\n case 'click':\n case 'doubleclick':\n return {\n worldX: event.x, worldY: event.y,\n affordance: event.affordance,\n // The press point too: an action that places geometry at the click wants it.\n ...(event.kind === 'click' ? { pressX: event.pressX, pressY: event.pressY } : {}),\n mods: modifierStateOf(event),\n ...resolved,\n };\n // Only a `stage: 'press'` pointerdown reaches an immediate invoker: the\n // buffered copy matches `drag` specs, which are ongoing.\n case 'contextmenu':\n return {\n worldX: event.x, worldY: event.y,\n clientX: event.clientX, clientY: event.clientY,\n affordance: event.affordance,\n bodyTarget: event.bodyTarget,\n bodyKind: event.bodyKind,\n mods: modifierStateOf(event),\n ...resolved,\n };\n case 'pointerdown':\n case 'longpress':\n return {\n worldX: event.x, worldY: event.y,\n affordance: event.affordance,\n bodyTarget: event.bodyTarget,\n mods: modifierStateOf(event),\n ...resolved,\n };\n case 'hover':\n return {\n worldX: event.x, worldY: event.y,\n clientX: event.clientX, clientY: event.clientY,\n affordance: event.affordance,\n bodyTarget: event.bodyTarget,\n mods: modifierStateOf(event),\n held: event.held === true,\n ...resolved,\n };\n case 'carry':\n return {\n worldX: event.x, worldY: event.y,\n clientX: event.clientX, clientY: event.clientY,\n carry: { type: event.type, value: event.value },\n affordance: event.affordance,\n bodyTarget: event.bodyTarget,\n bodyKind: event.bodyKind,\n mods: modifierStateOf(event),\n ...resolved,\n };\n case 'drop':\n case 'paste':\n return {\n items: event.items,\n via: event.kind,\n ...(event.kind === 'drop' && event.x !== undefined ? { worldX: event.x, worldY: event.y } : {}),\n ...resolved,\n };\n default:\n return resolved;\n }\n}\n","import type { Action } from './action';\nimport type { BoundGesture } from './binding';\nimport { resolveParams, type InvocationCtx, type BindingOpts } from './invoker';\nimport type { HotkeyTrigger } from '../../contributions/types';\nimport type { KeyHeldSpec, ModSpec } from '@weasel-js/gestures';\n\n/** Canonical id of the consolidated tool-offhand action. One descriptor\n * serves every tool; the matched binding supplies `params.toolId` to select\n * which tool to engage while the key is held. */\nexport const TOOL_OFFHAND_ID = 'tool.offhand';\n\n/** Per-tool spec consumed by `buildToolOffhandBindings`. The key is the\n * held-key trigger (e.g. ' ' for Space-for-hand). */\nexport interface ToolOffhandBindingSpec {\n toolId: string;\n key: string | string[];\n}\n\n/** `KeyboardEvent.key` for a declared `Eligibility.offhand` trigger. The\n * named keys become their DOM names; any other trigger already is one. */\nexport function offhandKeyFor(trigger: HotkeyTrigger): string {\n switch (trigger) {\n case 'space': return ' ';\n case 'alt': return 'Alt';\n case 'ctrl': return 'Control';\n case 'meta': return 'Meta';\n case 'shift': return 'Shift';\n default: return trigger;\n }\n}\n\n/** Build the per-tool `BoundGesture` list for the consolidated action's\n * `defaultBinding`. Each entry pairs a `key-held` spec with\n * `opts.params.toolId`, so the invoker's `start` can pick out which tool\n * to engage, and is overridden as `tool.offhand.<toolId>`.\n *\n * An offhand tool engages only between gestures. Swapping the tool out\n * mid-drag would cancel the drag, and the key is free for the gesture's own\n * tool to use — Space repositions a shape being drawn. */\nexport function buildToolOffhandBindings(\n specs: readonly ToolOffhandBindingSpec[],\n): BoundGesture[] {\n return specs.map(({ toolId, key }) => ({\n spec: { ...heldKeySpec(key), phase: BETWEEN_GESTURES },\n opts: { id: `${TOOL_OFFHAND_ID}.${toolId}`, params: { toolId } },\n }));\n}\n\nconst BETWEEN_GESTURES = [{ channel: '*', phase: 'initial' }] as const;\n\n/** The `key-held` spec for holding `key` (a `KeyboardEvent.key`, or several).\n * A modifier key gets every modifier optional, since its own keydown reports\n * its flag set. Any other key engages with Shift or Alt already down and not\n * with Cmd or Ctrl, so a letter trigger leaves its browser chord alone.\n * Every hold-a-key binding builds its spec here, so that rule has one home. */\nexport function heldKeySpec(key: string | string[]): KeyHeldSpec {\n const isModifier = [key].flat().some((k) => MODIFIER_KEYS.has(k));\n return { kind: 'key-held', key, mods: { ...(isModifier ? ANY_MODS : SHIFT_OR_ALT) } };\n}\n\nconst MODIFIER_KEYS: ReadonlySet<string> = new Set(['Alt', 'Control', 'Meta', 'Shift']);\n\n// A modifier's own keydown reports its flag set, and which other modifiers are\n// already down when it lands is an accident of the order they were pressed in.\nconst ANY_MODS: ModSpec = { alt: 'optional', ctrl: 'optional', meta: 'optional', shift: 'optional' };\n\nconst SHIFT_OR_ALT: ModSpec = { alt: 'optional', shift: 'optional' };\n\n/** Build the consolidated `tool.offhand` action — \"hold a key to engage a\n * secondary tool\" (e.g. Space-for-hand). `bindings` enumerates one\n * `{ spec: keyHeld, opts: { params: { toolId } } }` per tool; the invoker\n * reads `params.toolId` from the matched binding, pushes the tool id onto\n * the active-tool context's hotkey stack on `start`, and pops it on `onEnd`.\n * Mirrors the parametric shape of `tool.activate`. */\nexport function makeToolOffhandAction(bindings: BoundGesture[]): Action {\n return {\n id: TOOL_OFFHAND_ID,\n label: 'Engage tool (offhand)',\n defaultBinding: bindings,\n scope: 'hotkey',\n invoker: {\n timing: 'ongoing',\n start: (ctx: InvocationCtx, opts?: BindingOpts) => {\n const activeTool = ctx.deps.activeTool;\n const toolId = resolveParams(opts?.params)?.toolId as string | undefined;\n if (!activeTool || !toolId) return {};\n activeTool.pushHotkey(toolId);\n return {\n onEnd: () => { activeTool.popHotkey(toolId); },\n };\n },\n },\n requires: ['activeTool'],\n };\n}\n","import type { Contribution } from '../../../contributions/types';\nimport { routeGestureForSpecKind, specKindForRouteGesture } from '@weasel-js/gestures';\nimport type { GestureSpec, ModSpec, TargetSpec, PhaseSpec } from '@weasel-js/gestures';\nimport type { ParsedModifiers, ModifierKey, PhaseAtom } from '../routeGrammar';\nimport { formatRoute } from '../routeGrammar';\nimport { getGestureDescriptor, type GestureName } from '../gestures';\n\n/**\n * One row in the route registry — a single `GestureBinding` on one tool,\n * flattened into the route grammar's vocabulary so the inspector, the\n * conflict checker, and `describeRoute` can all read the same shape.\n *\n * Multiple rows can share (gesture, arg, target, modifiers) if different tools\n * declare them; consumers walk the list and group client-side.\n */\nexport interface RegistryEntry {\n /** The id of the entry that declared the binding: a tool, or a contribution. */\n ownerId: string;\n /** Which phase the binding's `phase` spec restricts it to. `'any'` when it\n * declares none, declares `'*'`, or declares an atom list whose atoms\n * don't agree on one phase — such a binding fires in either phase, and\n * reporting it as `'initial'` made it collide with genuinely-initial\n * bindings in `findConflicts`' bucket key. */\n phase: 'initial' | 'engaged' | 'any';\n /** Structured v3 modifier requirements. Empty object = \"no modifiers\n * held\" (the strict default). */\n modifiers: ParsedModifiers;\n gesture: GestureName;\n /** Resolved arg value for arg-bearing gestures (wheel direction,\n * key name, multiTouchTap fingers). Undefined for gestures whose\n * descriptor has no `arg`. */\n arg: string | undefined;\n /** Every arg value this binding actually answers to, when the spec names\n * more than one — `key: ['Delete','Backspace']` answers to both, and\n * `matchKey` matches any member case-insensitively. `arg` collapses them\n * into one display token, which is right for a route string and wrong for\n * deciding whether two bindings collide. Absent when there is only one. */\n argAlternatives?: readonly string[];\n /** Target class for hit-testing gestures. `undefined` when the descriptor\n * has `hasTarget: false` or the spec declares no target;\n * {@link PREDICATE_TARGET} when the spec uses a `kindOf` predicate, which\n * the route grammar has no notation for. */\n target: string | undefined;\n /** The action this binding fires. */\n actionId: string;\n /** The `GestureSpec` this row was flattened from, by reference. Reflection\n * consumers that need something the grammar doesn't capture — the\n * specificity tuple, a `kindOf` predicate identity — read it here rather\n * than re-walking `Tool.bindings`. */\n spec: GestureSpec;\n /** The binding's `opts.views`: the views it is live in. Absent when it is\n * live in every view. */\n views?: readonly (string | null)[];\n /** The binding's `opts.params`, as declared: a thunk is not called. */\n params?: unknown;\n /** The binding's `opts.yields`, when it is set. */\n yields?: true;\n}\n\n/**\n * Stand-in target for a `{ kindOf }` predicate spec.\n *\n * The route grammar can name target *classes* (`empty`, `selected-body`,\n * `kind:rect`) but not arbitrary predicates, so three distinct select-tool\n * bindings all render as this one token. Narrowing it would mean giving the\n * grammar a way to describe a function, which is a real design question and\n * not one this reflection layer should answer by inventing syntax.\n */\nexport const PREDICATE_TARGET = 'predicate';\n\n/**\n * Flatten every tool's `bindings` into route-registry rows.\n *\n * This was `buildActionRegistry`, and it walked `ToolDef.initial` /\n * `.engaged` phase tables — the grammar that no longer exists. It was also\n * blind to `Tool.bindings` the entire time the two lived side by side, which\n * is why the inspector under-reported select by more than half. The rename\n * fixes a second thing: it never had anything to do with the Actions\n * Registry, and reading `buildActionRegistry` next to `ActionsRegistry`\n * suggested otherwise.\n */\nexport function buildRouteRegistry(\n entries: readonly Contribution<unknown>[],\n): RegistryEntry[] {\n const out: RegistryEntry[] = [];\n for (const owner of entries) {\n for (const binding of owner.bindings ?? []) {\n const row = entryFor(owner.id, binding.spec, binding.actionId);\n if (!row) continue;\n const { views, params, yields } = binding.opts ?? {};\n out.push({\n ...row,\n ...(views === undefined ? {} : { views }),\n ...(params === undefined ? {} : { params }),\n ...(yields ? { yields: true as const } : {}),\n });\n }\n }\n return out;\n}\n\n/**\n * Every route string one `GestureSpec` declares, in route-grammar notation.\n *\n * One string per arg alternative — a spec bound to `['ArrowUp','ArrowDown']`\n * yields two routes, because each is separately conflictable and separately\n * readable. Returns `[]` for spec kinds the grammar can't name.\n *\n * This is the display counterpart to {@link buildRouteRegistry}: same\n * projection of a spec onto the grammar, rendered as text instead of as a\n * conflict-checkable row.\n */\nexport function routesForSpec(spec: GestureSpec): readonly string[] {\n const gesture = routeGestureForSpecKind(spec.kind);\n if (!gesture) return [];\n const descriptor = getGestureDescriptor(gesture);\n const modifiers = parseModSpec('mods' in spec ? spec.mods : undefined);\n const phases = phaseAtomsForSpec('phase' in spec ? spec.phase : undefined);\n const target = descriptor.hasTarget\n ? routeTargetForSpec('target' in spec ? spec.target : undefined) ?? '*'\n : undefined;\n const args = descriptor.arg\n ? routeArgsForSpec(spec, descriptor.arg.default)\n : [undefined];\n const held = spec.kind === 'hover' && spec.held !== undefined\n ? { held: spec.held === true ? ('required' as const) : ('optional' as const) }\n : {};\n return args.map((arg) => formatRoute({ phases, gesture, arg, target, modifiers, ...held }));\n}\n\nfunction entryFor(\n ownerId: string,\n spec: GestureSpec,\n actionId: string,\n): RegistryEntry | null {\n const gesture = routeGestureForSpecKind(spec.kind);\n if (!gesture) return null;\n const descriptor = getGestureDescriptor(gesture);\n return {\n ownerId,\n actionId,\n gesture,\n phase: phaseOf('phase' in spec ? spec.phase : undefined),\n modifiers: parseModSpec('mods' in spec ? spec.mods : undefined),\n arg: descriptor.arg ? argOf(spec, descriptor.arg.default) : undefined,\n ...(descriptor.arg ? argAlternativesOf(spec, descriptor.arg.default) : {}),\n target: descriptor.hasTarget\n ? routeTargetForSpec('target' in spec ? spec.target : undefined)\n : undefined,\n spec,\n };\n}\n\n/** Collapse a `PhaseSpec` to the single phase a binding is restricted to, or\n * `'any'` when it isn't restricted to one.\n *\n * `PhaseAtom.channel` says which channel's phase state the binding reads,\n * not which phase it fires in, so it plays no part in this collapse — only\n * the set of distinct `atom.phase` values matters. */\nfunction phaseOf(phase: PhaseSpec | undefined): 'initial' | 'engaged' | 'any' {\n if (phase === undefined || phase === '*') return 'any';\n if (phase === 'initial' || phase === 'engaged') return phase;\n const distinct = new Set(phase.map((atom) => atom.phase));\n if (distinct.size !== 1) return 'any';\n const only = [...distinct][0];\n return only === 'initial' || only === 'engaged' ? only : 'any';\n}\n\n/** `ModSpec` (per-key tri-state) → `ParsedModifiers`. `false` and absent both\n * mean \"must not be held\", which the parsed form spells as an absent key. */\nfunction parseModSpec(mods: ModSpec | undefined): ParsedModifiers {\n if (!mods) return {};\n const out: ParsedModifiers = {};\n for (const [name, req] of Object.entries(mods)) {\n if (req === true) out[name as ModifierKey] = 'required';\n else if (req === 'optional') out[name as ModifierKey] = 'optional';\n }\n return out;\n}\n\n/** Expand a `PhaseSpec` to the atoms `formatRoute` renders. A spec with no\n * `phase` matches in either phase, which the grammar spells `[*]`. */\nfunction phaseAtomsForSpec(phase: PhaseSpec | undefined): readonly PhaseAtom[] {\n if (phase === undefined) return [{ channel: '*', phase: '*' }];\n if (phase === 'initial' || phase === 'engaged' || phase === '*') {\n return [{ channel: '&', phase }];\n }\n return phase;\n}\n\nfunction routeTargetForSpec(target: TargetSpec | undefined): string | undefined {\n if (target === undefined) return undefined;\n return typeof target === 'string' ? target : PREDICATE_TARGET;\n}\n\n/** Every arg value a spec's route slot can take, one per alternative. Both\n * the registry row and the route string read the arg here. */\nfunction routeArgsForSpec(\n spec: GestureSpec,\n fallback: string | undefined,\n): readonly (string | undefined)[] {\n if ('key' in spec) return Array.isArray(spec.key) ? spec.key : [spec.key];\n if ('fingers' in spec) return [String(spec.fingers)];\n if ('direction' in spec) return [spec.direction ?? fallback];\n if (spec.kind === 'hover') return [spec.motion ?? fallback];\n if ('types' in spec) return [spec.types?.length ? spec.types.join('|') : fallback];\n return [fallback];\n}\n\nfunction argOf(spec: GestureSpec, fallback: string | undefined): string | undefined {\n const args = routeArgsForSpec(spec, fallback);\n return args.length > 1 ? args.join('|') : args[0];\n}\n\n/** The alternatives a spec answers to, when there is more than one. A MIME\n * list is one too: `matchIngestTypes` accepts any member, so two `drop` specs\n * whose type sets overlap collide even though neither set contains the other. */\nfunction argAlternativesOf(\n spec: GestureSpec,\n fallback: string | undefined,\n): { argAlternatives?: readonly string[] } {\n const types = 'types' in spec ? spec.types : undefined;\n const alts = types?.length\n ? types\n : routeArgsForSpec(spec, fallback).filter((a): a is string => a !== undefined);\n return alts.length > 1 ? { argAlternatives: alts } : {};\n}\n\n// Re-export for downstream consumers.\nexport { getGestureDescriptor, routeGestureForSpecKind, specKindForRouteGesture };\nexport type { GestureName };\n","/**\n * Re-exports the pure matcher primitives from `@weasel-js/gestures` and layers\n * the actions-layer binding-scope / matchBest logic on top.\n */\n\nimport { matchSpec, matchModifiers, matchKey, matchTarget, matchPhase, parseTargetSpec, specificity } from '@weasel-js/gestures';\nimport type {\n GestureSpec, InputEvent, PhaseContext, TargetSpec,\n} from '@weasel-js/gestures';\nimport type { GestureBinding } from '../actions/binding';\nimport type { ClaimableGesture } from '@weasel-js/gestures';\nimport { isDev } from '@weasel-js/react';\n\nexport { matchSpec, matchModifiers, matchKey, matchTarget, matchPhase, specificity };\nexport type { InputEvent, PhaseContext };\n\n/** Where a binding came from, which is also its priority: a held hotkey beats\n * the active tool, which beats bindings that are always in scope. */\nexport type BindingScope = 'ambient' | 'active' | 'hotkey';\n\n/** A binding paired with where it came from, ready to be matched against an\n * event. */\nexport interface ScopedBinding {\n binding: GestureBinding;\n scope: BindingScope;\n /** Id of the tool or contribution that declared this binding —\n * `'&'`-channel phase atoms resolve to it. `null` for a registered\n * action's own binding. */\n ownerId: string | null;\n}\n\n/** The binding that won a match. */\nexport interface MatchResult {\n binding: GestureBinding;\n scope: BindingScope;\n /** Id of the entry that declared the binding — propagated from\n * `ScopedBinding` so the dispatcher can record it as the handle owner. */\n ownerId: string | null;\n}\n\nconst SCOPE_PRIORITY: readonly BindingScope[] = ['hotkey', 'active', 'ambient'];\n\n/**\n * True when a spec's target actually consults the affordance hit rather than\n * only the body classification. `kindOf` predicates are handed the hit;\n * `affordance:<k>` matches on its `kind`. The body-class strings (`'empty'`,\n * `'selected-body'`, `'unselected-body'`) and the `kind:` forms resolve from\n * `bodyTarget` / `bodyKind` and never see it.\n *\n * A predicate declares which it is with `readsAffordance`; one that declares\n * nothing, which only untyped code can write, counts as not reading the hit.\n */\nexport function targetConsultsAffordance(specTarget: TargetSpec | undefined): boolean {\n if (specTarget === undefined) return false;\n const form = parseTargetSpec(specTarget);\n if (form === null) return false;\n switch (form.form) {\n case 'predicate': return form.kindOf.readsAffordance === true;\n case 'affordance': return true;\n case 'body': return false;\n case 'kind': return false;\n default: {\n const _exhaustive: never = form;\n void _exhaustive;\n return false;\n }\n }\n}\n\nfunction specTargetOf(spec: GestureSpec): TargetSpec | undefined {\n return 'target' in spec ? spec.target : undefined;\n}\n\ninterface Claim {\n owner?: string;\n strength?: 'exclusive' | 'shared';\n claimedKinds?: readonly ClaimableGesture[];\n}\n\nfunction claimOf(e: InputEvent): Claim | undefined {\n return ('affordance' in e ? e.affordance : undefined) as Claim | undefined;\n}\n\n/** Event kind → the claim token that covers it. `null` for events a positional\n * claim has no opinion about — keys, drops, pastes, multitouch. */\nfunction claimGestureOf(e: InputEvent): ClaimableGesture | null {\n switch (e.kind) {\n case 'pointerdown':\n case 'click': return 'pointer';\n case 'doubleclick': return 'doubleClick';\n case 'contextmenu': return 'contextMenu';\n case 'longpress': return 'longPress';\n case 'wheel': return 'wheel';\n case 'pinch': return 'pinch';\n default: return null;\n }\n}\n\n/** `'exclusive'` when the event carries a claim that bars unnamed bindings\n * for this event's gesture. */\nfunction isExclusiveClaim(e: InputEvent): boolean {\n const claim = claimOf(e);\n if (claim?.strength !== 'exclusive') return false;\n const gesture = claimGestureOf(e);\n if (gesture === null) return false;\n return claim.claimedKinds === undefined || claim.claimedKinds.includes(gesture);\n}\n\nconst warnedDeadClaims = new Set<string>();\n\n/** Dev-only. An exclusive claim that matches no binding drops the press with\n * no diagnostic, which reads exactly like deliberate blocking. */\nfunction reportDeadClaim(owner: string | undefined, warn: (message: string) => void): void {\n if (!isDev()) return;\n const key = String(owner);\n if (warnedDeadClaims.has(key)) return;\n warnedDeadClaims.add(key);\n warn(\n `[weasel] exclusive claim by \"${key}\" matched no binding: no `\n + '`affordance:` or `kindOf` target resolved against it, so the press was dropped.',\n );\n}\n\n/** Sort callback: negative when `a` is MORE specific than `b`, so `a` sorts\n * first. */\nfunction compareSpecificity(a: GestureSpec, b: GestureSpec): number {\n const sa = specificity(a);\n const sb = specificity(b);\n for (let i = 0; i < sa.length; i++) {\n if (sa[i] !== sb[i]) return sb[i] - sa[i];\n }\n return 0;\n}\n\n/** The first of {@link matchSorted}'s matches, or null when nothing matches. */\nexport function matchBest(\n e: InputEvent,\n bindings: readonly ScopedBinding[],\n isMac: boolean,\n engagedChannels?: ReadonlySet<string>,\n): MatchResult | null {\n const sorted = matchSorted(e, bindings, isMac, engagedChannels);\n return sorted.length > 0 ? sorted[0] : null;\n}\n\n/**\n * Find every binding that matches the event, sorted by precedence\n * (best → worst). Ordering rules:\n *\n * - Scopes by priority: hotkey > active > ambient.\n * - Within a scope, more-specific bindings beat less-specific (see\n * `specificity()`).\n * - Among same-specificity bindings, first-declared wins.\n */\nexport function matchSorted(\n e: InputEvent,\n bindings: readonly ScopedBinding[],\n isMac: boolean,\n engagedChannels?: ReadonlySet<string>,\n warn: (message: string) => void = (m) => console.warn(m),\n): MatchResult[] {\n return matchSortedWithBarred(e, bindings, isMac, engagedChannels, { warn }).matches;\n}\n\n/** {@link matchSorted}, plus what an exclusive claim on the event barred. */\nexport interface MatchOutcome {\n matches: MatchResult[];\n /** Bindings whose spec matched the event but which the claim barred, in\n * the same order `matches` uses. Filled only when `collectBarred` is set. */\n barred: MatchResult[];\n /** Owner of the exclusive claim, when one applied. */\n claimOwner?: string;\n}\n\n/**\n * {@link matchSorted} that can also report the bindings an exclusive claim\n * kept out. Collecting them costs a spec match per barred binding, so it is\n * opt-in — the dispatcher asks only when it is recording.\n */\nexport function matchSortedWithBarred(\n e: InputEvent,\n bindings: readonly ScopedBinding[],\n isMac: boolean,\n engagedChannels?: ReadonlySet<string>,\n opts: { collectBarred?: boolean; warn?: (message: string) => void } = {},\n): MatchOutcome {\n const warn = opts.warn ?? ((m: string) => console.warn(m));\n const engaged = engagedChannels ?? EMPTY_ENGAGED;\n // An exclusive claim outranks the scope tier. Scope is the outermost sort\n // key below, so without this a vague active binding beats the claim owner's\n // precise ambient one.\n const exclusive = isExclusiveClaim(e);\n const admits = (sb: ScopedBinding): boolean =>\n !exclusive || targetConsultsAffordance(specTargetOf(sb.binding.spec));\n const out: MatchResult[] = [];\n const barred: MatchResult[] = [];\n for (const scope of SCOPE_PRIORITY) {\n const scopeMatches: MatchResult[] = [];\n const scopeBarred: MatchResult[] = [];\n for (const sb of bindings) {\n if (sb.scope !== scope) continue;\n const admitted = admits(sb);\n if (!admitted && !opts.collectBarred) continue;\n const phaseCtx: PhaseContext = { selfChannel: sb.ownerId, engagedChannels: engaged };\n if (matchSpec(e, sb.binding.spec, isMac, phaseCtx)) {\n (admitted ? scopeMatches : scopeBarred)\n .push({ binding: sb.binding, scope, ownerId: sb.ownerId });\n }\n }\n // Stable sort by specificity descending. Identical-specificity entries\n // keep their registration order (Array.prototype.sort is stable per ES2019).\n scopeMatches.sort((a, b) => compareSpecificity(a.binding.spec, b.binding.spec));\n scopeBarred.sort((a, b) => compareSpecificity(a.binding.spec, b.binding.spec));\n out.push(...scopeMatches);\n barred.push(...scopeBarred);\n }\n // Checked against the final result, not the pool: a binding can declare a\n // `kindOf`/`affordance:` target and still fail to match this particular claim.\n if (exclusive && out.length === 0 && bindings.length > 0) {\n reportDeadClaim(claimOf(e)?.owner, warn);\n }\n const owner = exclusive ? claimOf(e)?.owner : undefined;\n return { matches: out, barred, ...(owner !== undefined ? { claimOwner: owner } : {}) };\n}\n\nconst EMPTY_ENGAGED: ReadonlySet<string> = new Set();\n","import type { DeviceProfile } from '../vocabulary';\n\n/** The detected half of a profile — everything except the derived scale. */\nexport type DetectedDeviceFacts = Omit<DeviceProfile, 'targetScale'>;\n\n/**\n * Handle/hit multiplier applied on a coarse pointer.\n *\n * 8px handle → 14px; 24px rotation distance → 42px. Counting the\n * surrounding grab zone, that lands in the Apple HIG 44pt / Material 48dp\n * minimum-touch-target band. One constant so it is tunable in one place.\n */\nexport const COARSE_TARGET_SCALE = 1.75;\n\n/**\n * Fold consumer overrides over detected facts and derive `targetScale`.\n *\n * `targetScale` is re-derived AFTER the merge, so an override of\n * `coarsePointer` alone scales the chrome as expected. An explicit\n * `targetScale` override wins over the derivation.\n */\nexport function resolveDeviceProfile(\n detected: DetectedDeviceFacts,\n overrides?: Partial<DeviceProfile>,\n): DeviceProfile {\n const coarsePointer = overrides?.coarsePointer ?? detected.coarsePointer;\n const canHover = overrides?.canHover ?? detected.canHover;\n const dpr = overrides?.dpr ?? detected.dpr;\n const targetScale =\n overrides?.targetScale ?? (coarsePointer ? COARSE_TARGET_SCALE : 1);\n return { coarsePointer, canHover, dpr, targetScale };\n}\n\n/**\n * Assumed when `matchMedia` is unavailable (SSR, jsdom) and used as the\n * absent-means value for `RuleCtx.device`.\n *\n * Derived from `resolveDeviceProfile` rather than hand-written, so it can\n * never drift from what the function would compute for the same facts. A\n * mouse-like device is the safe default: it is what the kit has always\n * assumed, so an absent profile changes nothing for existing consumers.\n */\nexport const DEFAULT_DEVICE_PROFILE: DeviceProfile = resolveDeviceProfile({\n coarsePointer: false,\n canHover: true,\n dpr: 1,\n});\n","import type { ModifierState } from '../vocabulary';\nimport type { CapabilityTag } from '@weasel-js/modes';\nimport type { RuleCtx } from './ruleCtx';\nimport { DEFAULT_DEVICE_PROFILE } from './deviceProfile';\n\n/**\n * A selector is a conjunction of key/value tests. Multiple keys at the same\n * level AND together. Each key maps to a selector primitive in the evaluator.\n */\nexport interface Selector {\n selection?: { is?: number; atLeast?: number; empty?: boolean };\n mode?: string | { not: string } | { in: readonly string[] };\n capability?:\n | CapabilityTag\n | readonly CapabilityTag[]\n | { in: readonly CapabilityTag[] }\n | { not: CapabilityTag };\n gesturing?: boolean;\n actionIs?: string;\n modifierHeld?: keyof ModifierState;\n focused?: boolean;\n hovering?: boolean;\n hoveringSelected?: boolean;\n zoomAtLeast?: number;\n /** Matches `ctx.editingAnchors` — true while a path is in anchor-edit\n * mode. Absent flag is treated as `false`. */\n editingAnchors?: boolean;\n /** Matches `ctx.selectionResizable`. Absent flag is treated as `true`\n * (resizable), so `{ resizable: true }` passes for legacy ctx builders\n * that don't compute it. */\n resizable?: boolean;\n /** Matches `ctx.device.coarsePointer` — the primary pointer is imprecise\n * (touch, most styluses). Absent device is treated as `false`. */\n coarsePointer?: boolean;\n /** Matches `ctx.device.canHover` — the primary pointer can hover. Absent\n * device is treated as `true`. */\n canHover?: boolean;\n}\n\n/**\n * Composable visibility/eligibility rule. Trees of `all`/`any`/`not` nodes\n * over `Selector` leaves. `when` is the escape hatch — its closure is\n * opaque to introspection and should be avoided when a declarative form\n * exists. Empty `all` is true; empty `any` is false.\n */\nexport type Rule =\n | Selector\n | { all: readonly Rule[] }\n | { any: readonly Rule[] }\n | { not: Rule }\n | { when: (ctx: RuleCtx) => boolean };\n\n/** Constant rules. Kept here so they have a single source. */\nexport const ALWAYS: Rule = { all: [] };\n/** A rule that never passes. `any` of nothing is false. */\nexport const NEVER: Rule = { any: [] };\n\nexport function isAllRule(r: Rule): r is { all: readonly Rule[] } {\n return typeof r === 'object' && r !== null && 'all' in r;\n}\nexport function isAnyRule(r: Rule): r is { any: readonly Rule[] } {\n return typeof r === 'object' && r !== null && 'any' in r;\n}\nexport function isNotRule(r: Rule): r is { not: Rule } {\n return typeof r === 'object' && r !== null && 'not' in r;\n}\nexport function isWhenRule(r: Rule): r is { when: (ctx: RuleCtx) => boolean } {\n return typeof r === 'object' && r !== null && 'when' in r;\n}\nexport function isSelector(r: Rule): r is Selector {\n return !isAllRule(r) && !isAnyRule(r) && !isNotRule(r) && !isWhenRule(r);\n}\n\nfunction checkSelection(s: NonNullable<Selector['selection']>, ctx: RuleCtx): boolean {\n if (s.empty !== undefined && (ctx.selection.length === 0) !== s.empty) return false;\n if (s.is !== undefined && ctx.selection.length !== s.is) return false;\n if (s.atLeast !== undefined && ctx.selection.length < s.atLeast) return false;\n return true;\n}\n\nexport function checkMode(m: NonNullable<Selector['mode']>, ctx: Pick<RuleCtx, 'mode'>): boolean {\n if (typeof m === 'string') return ctx.mode === m;\n if ('not' in m) return ctx.mode !== m.not;\n if ('in' in m) return m.in.includes(ctx.mode);\n return false;\n}\n\nexport function checkCapability(c: NonNullable<Selector['capability']>, ctx: Pick<RuleCtx, 'allowedCapabilities'>): boolean {\n if (typeof c === 'string') return ctx.allowedCapabilities.has(c);\n if (Array.isArray(c)) return c.every((tag) => ctx.allowedCapabilities.has(tag));\n if ('in' in c) return c.in.some((tag) => ctx.allowedCapabilities.has(tag));\n if ('not' in c) return !ctx.allowedCapabilities.has(c.not);\n return false;\n}\n\nfunction evaluateSelector(s: Selector, ctx: RuleCtx): boolean {\n if (s.selection !== undefined && !checkSelection(s.selection, ctx)) return false;\n if (s.mode !== undefined && !checkMode(s.mode, ctx)) return false;\n if (s.capability !== undefined && !checkCapability(s.capability, ctx)) return false;\n if (s.gesturing !== undefined && (ctx.action.kind !== null) !== s.gesturing) return false;\n if (s.actionIs !== undefined && ctx.action.kind !== s.actionIs) return false;\n if (s.modifierHeld !== undefined && !ctx.modifiers[s.modifierHeld]) return false;\n if (s.focused !== undefined && ctx.focused !== s.focused) return false;\n if (s.hovering !== undefined && (ctx.hover !== null) !== s.hovering) return false;\n if (s.hoveringSelected !== undefined) {\n const isHovSel = ctx.hover !== null && ctx.selection.includes(ctx.hover);\n if (isHovSel !== s.hoveringSelected) return false;\n }\n if (s.editingAnchors !== undefined && (ctx.editingAnchors ?? false) !== s.editingAnchors) return false;\n if (s.zoomAtLeast !== undefined) {\n // A host that reports no zoom has no threshold to clear.\n if (ctx.zoom === undefined || ctx.zoom < s.zoomAtLeast) return false;\n }\n if (s.resizable !== undefined) {\n // Absent flag === resizable (back-compat for ctx builders that don't\n // compute it). Only an explicit `false` opts a selection out.\n const resizable = ctx.selectionResizable ?? true;\n if (resizable !== s.resizable) return false;\n }\n if (s.coarsePointer !== undefined) {\n const device = ctx.device ?? DEFAULT_DEVICE_PROFILE;\n if (device.coarsePointer !== s.coarsePointer) return false;\n }\n if (s.canHover !== undefined) {\n const device = ctx.device ?? DEFAULT_DEVICE_PROFILE;\n if (device.canHover !== s.canHover) return false;\n }\n return true;\n}\n\n/** Deepest nesting `describeRule` will walk before giving up: a backstop that\n * makes termination unconditional. */\nconst MAX_RULE_DEPTH = 10;\n\n/** Render a selector's value side. Capability arrays AND, so they join with `+`. */\nfunction describeValue(value: unknown, depth: number): string {\n if (depth > MAX_RULE_DEPTH) return '…';\n if (value === null || typeof value !== 'object') return String(value);\n if (Array.isArray(value)) return value.map((v) => describeValue(v, depth + 1)).join('+');\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 1 && keys[0] === 'not') return `not(${describeValue(obj.not, depth + 1)})`;\n if (keys.length === 1 && keys[0] === 'in') return `in(${describeValue(obj.in, depth + 1)})`;\n return keys.map((k) => `${k}=${describeValue(obj[k], depth + 1)}`).join(',');\n}\n\nfunction describeSelector(s: Selector, depth: number): string {\n const keys = Object.keys(s) as Array<keyof Selector>;\n // An empty selector matches every context — `evaluateSelector` has no test\n // to fail. `*` says that the way a CSS reader expects.\n if (keys.length === 0) return '*';\n return keys.map((k) => `${k}:${describeValue(s[k], depth + 1)}`).join(' & ');\n}\n\nfunction describeAt(rule: Rule, depth: number): string {\n if (depth > MAX_RULE_DEPTH) return '…';\n if (isAllRule(rule)) return `all(${rule.all.map((r) => describeAt(r, depth + 1)).join(', ')})`;\n if (isAnyRule(rule)) return `any(${rule.any.map((r) => describeAt(r, depth + 1)).join(', ')})`;\n if (isNotRule(rule)) return `not(${describeAt(rule.not, depth + 1)})`;\n // `when`'s predicate is a closure, so the function's name is all a reader gets.\n if (isWhenRule(rule)) return `when(${rule.when.name || 'ƒ'})`;\n return describeSelector(rule, depth);\n}\n\n/**\n * Render a {@link Rule} as a short human-readable string, for inspectors and\n * diagnostics that need to say WHICH rule decided something.\n *\n * ```\n * { capability: 'edits-page' } → capability:edits-page\n * { all: [{ mode: 'normal' }, { focused: true }] } → all(mode:normal, focused:true)\n * { not: { selection: { empty: true } } } → not(selection:empty=true)\n * { when: function hasPath() { … } } → when(hasPath)\n * ```\n *\n * Never throws and always terminates.\n */\nexport function describeRule(rule: Rule): string {\n return describeAt(rule, 0);\n}\n\n/** Evaluate a rule against a context. Pure, and cheap enough to run per\n * frame for every piece of chrome. */\nexport function evaluate(rule: Rule, ctx: RuleCtx): boolean {\n if (isAllRule(rule)) return rule.all.every((r) => evaluate(r, ctx));\n if (isAnyRule(rule)) return rule.any.some((r) => evaluate(r, ctx));\n if (isNotRule(rule)) return !evaluate(rule.not, ctx);\n if (isWhenRule(rule)) return rule.when(ctx);\n return evaluateSelector(rule, ctx);\n}\n\n/**\n * Composable eligibility predicate with a fluent surface. `cond(ctx)`\n * evaluates its `Rule` tree, carried at `.rule`; the fluent methods return new\n * Conditions wrapping new trees.\n *\n * **Chain semantics: strict left-to-right, no precedence.** `a.and(b).or(c)` is\n * `(a && b) || c`; `a.or(b).and(c)` is `(a || b) && c`. For grouped\n * disjunction, name the subexpression or use the top-level `or(...)`.\n */\nexport interface Condition {\n (ctx: RuleCtx): boolean;\n readonly rule: Rule;\n /** `this && other` */\n and(other: Condition | Rule): Condition;\n /** `this || other` */\n or(other: Condition | Rule): Condition;\n /** `this && !other` */\n andNot(other: Condition | Rule): Condition;\n /** `this || !other` */\n orNot(other: Condition | Rule): Condition;\n}\n","import type { ActiveMode, CapabilityTag } from '@weasel-js/modes';\nimport { checkCapability, checkMode, isAllRule, isAnyRule, isNotRule, isWhenRule, type Rule, type Selector } from './rule';\n\n/**\n * Whether two rules can never hold at once — no `RuleCtx` passes both.\n *\n * Conservative: `true` is a proof, `false` means \"may overlap\". It reasons\n * about the selector values themselves (two different `mode`s, an empty\n * selection against a non-empty one, `focused: true` against `false`) and\n * through `all` / `any` / `not`; a `when` closure is opaque, so it overlaps\n * everything. The route-conflict check uses it to stay quiet about bindings\n * that share a tuple but are never eligible together.\n */\nexport function rulesExclusive(a: Rule, b: Rule): boolean {\n if (isAllRule(a)) return a.all.some((r) => rulesExclusive(r, b));\n if (isAllRule(b)) return b.all.some((r) => rulesExclusive(a, r));\n if (isAnyRule(a)) return a.any.every((r) => rulesExclusive(r, b));\n if (isAnyRule(b)) return b.any.every((r) => rulesExclusive(a, r));\n if (isNotRule(a)) return rulesEqual(a.not, b);\n if (isNotRule(b)) return rulesEqual(b.not, a);\n if (isWhenRule(a) || isWhenRule(b)) return false;\n return selectorsExclusive(a, b);\n}\n\n/**\n * Whether `rule` can hold while `mode` is active. Only its `mode` and\n * `capability` tests are settled by the mode; every other test could go either\n * way, so `false` is a proof and `true` means \"may hold\".\n */\nexport function ruleCanHoldIn(rule: Rule, mode: ActiveMode): boolean {\n return decideIn(rule, mode) !== false;\n}\n\n/** Three-valued: `undefined` when the mode alone does not settle the rule. */\nfunction decideIn(rule: Rule, mode: ActiveMode): boolean | undefined {\n if (isAllRule(rule)) return all3(rule.all.map((r) => decideIn(r, mode)));\n if (isAnyRule(rule)) {\n const parts = rule.any.map((r) => decideIn(r, mode));\n if (parts.includes(true)) return true;\n return parts.every((p) => p === false) ? false : undefined;\n }\n if (isNotRule(rule)) {\n const inner = decideIn(rule.not, mode);\n return inner === undefined ? undefined : !inner;\n }\n if (isWhenRule(rule)) return undefined;\n const ctx = { mode: mode.id, allowedCapabilities: mode.allowedCapabilities as ReadonlySet<CapabilityTag> };\n const settled = [\n rule.mode === undefined ? true : checkMode(rule.mode, ctx),\n rule.capability === undefined ? true : checkCapability(rule.capability, ctx),\n ];\n const { mode: _m, capability: _c, ...rest } = rule;\n void _m; void _c;\n return all3([...settled, Object.keys(rest).length > 0 ? undefined : true]);\n}\n\nfunction all3(parts: readonly (boolean | undefined)[]): boolean | undefined {\n if (parts.includes(false)) return false;\n return parts.every((p) => p === true) ? true : undefined;\n}\n\nconst BOOLEAN_KEYS = [\n 'gesturing', 'focused', 'hovering', 'hoveringSelected', 'editingAnchors',\n 'resizable', 'coarsePointer', 'canHover',\n] as const satisfies readonly (keyof Selector)[];\n\nfunction selectorsExclusive(a: Selector, b: Selector): boolean {\n for (const key of BOOLEAN_KEYS) {\n if (a[key] !== undefined && b[key] !== undefined && a[key] !== b[key]) return true;\n }\n if (a.actionIs !== undefined && b.actionIs !== undefined && a.actionIs !== b.actionIs) return true;\n // `actionIs` holds only while some action runs.\n if (a.actionIs !== undefined && b.gesturing === false) return true;\n if (b.actionIs !== undefined && a.gesturing === false) return true;\n if (a.mode !== undefined && b.mode !== undefined && modesExclusive(a.mode, b.mode)) return true;\n if (a.selection && b.selection && selectionsExclusive(a.selection, b.selection)) return true;\n if (a.capability !== undefined && b.capability !== undefined\n && capabilitiesExclusive(a.capability, b.capability)) return true;\n return false;\n}\n\ntype ModeSet = { in: ReadonlySet<string> } | { notIn: ReadonlySet<string> };\n\nfunction modeSet(m: NonNullable<Selector['mode']>): ModeSet {\n if (typeof m === 'string') return { in: new Set([m]) };\n if ('not' in m) return { notIn: new Set([m.not]) };\n return { in: new Set(m.in) };\n}\n\nfunction modesExclusive(a: NonNullable<Selector['mode']>, b: NonNullable<Selector['mode']>): boolean {\n const x = modeSet(a);\n const y = modeSet(b);\n if ('in' in x && 'in' in y) return ![...x.in].some((m) => y.in.has(m));\n if ('in' in x && 'notIn' in y) return [...x.in].every((m) => y.notIn.has(m));\n if ('notIn' in x && 'in' in y) return [...y.in].every((m) => x.notIn.has(m));\n // Two exclusions always leave some mode both allow.\n return false;\n}\n\n/** The selection-length interval a `selection` selector admits. */\nfunction selectionRange(s: NonNullable<Selector['selection']>): [number, number] {\n let lo = 0;\n let hi = Infinity;\n if (s.empty === true) hi = 0;\n if (s.empty === false) lo = 1;\n if (s.is !== undefined) { lo = Math.max(lo, s.is); hi = Math.min(hi, s.is); }\n if (s.atLeast !== undefined) lo = Math.max(lo, s.atLeast);\n return [lo, hi];\n}\n\nfunction selectionsExclusive(\n a: NonNullable<Selector['selection']>,\n b: NonNullable<Selector['selection']>,\n): boolean {\n const [alo, ahi] = selectionRange(a);\n const [blo, bhi] = selectionRange(b);\n return Math.max(alo, blo) > Math.min(ahi, bhi);\n}\n\n/** Tags a capability selector requires, and the one it forbids. */\nfunction capabilityTerms(c: NonNullable<Selector['capability']>): {\n requires: readonly CapabilityTag[];\n forbids?: CapabilityTag;\n} {\n if (typeof c === 'string') return { requires: [c] };\n if (Array.isArray(c)) return { requires: c };\n if ('not' in c) return { requires: [], forbids: c.not };\n // `{ in }` requires any one of its tags, so no single tag is required.\n return { requires: [] };\n}\n\nfunction capabilitiesExclusive(\n a: NonNullable<Selector['capability']>,\n b: NonNullable<Selector['capability']>,\n): boolean {\n const x = capabilityTerms(a);\n const y = capabilityTerms(b);\n return (x.forbids !== undefined && y.requires.includes(x.forbids))\n || (y.forbids !== undefined && x.requires.includes(y.forbids));\n}\n\n/** Structural equality over rule trees; a `when` closure matches only itself. */\nfunction rulesEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a);\n const kb = Object.keys(b);\n if (ka.length !== kb.length) return false;\n return ka.every((k) => rulesEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));\n}\n","import type { NodeId, DeviceProfile, ModifierState } from '../vocabulary';\nimport { activeModeOf, NORMAL, type CapabilityTag } from '@weasel-js/modes';\n\n/**\n * Live state read by rule evaluation. Built once per frame on the consuming\n * surface — chrome-caps, the affordance pipeline, the dispatcher's\n * eligibility filter — and discarded.\n *\n * Adding a new field is additive: existing rules don't change, new\n * selector atoms can read it.\n */\nexport interface RuleCtx {\n readonly focused: boolean;\n readonly selection: readonly NodeId[];\n readonly multiActive: boolean;\n readonly modifiers: ModifierState;\n readonly action: { readonly kind: string | null; readonly id: string | null };\n readonly hover: NodeId | null;\n /**\n * How far the viewport is zoomed in, as one number — `1` at native scale.\n *\n * A scalar rather than the `View` this used to carry, because `zoomAtLeast`\n * is the only selector that ever read one and a number is all it needs. A\n * host whose viewport is a camera has no `View` to hand over and would\n * otherwise have to invent one to use eligibility at all; it omits this\n * instead, and `zoomAtLeast` declines rather than matching on a fiction.\n */\n readonly zoom?: number;\n /** Active mode id. `'normal'` when no non-default mode is engaged. */\n readonly mode: string;\n /** Capability tags allowed by the active mode (the union of\n * `ModeDefinition.allows` plus implicit tags). The `capability:`\n * selector reads this to determine whether a tag is permitted. */\n readonly allowedCapabilities: ReadonlySet<CapabilityTag>;\n /** Whether the current selection may be resized. `<SceneCanvas>` folds\n * `selectTool.resize.resizable` over the selection (true only when every\n * selected node is resizable). Read by the `resizable:` selector to gate\n * `selection.resize-handles`. Absent (legacy ctx builders) is treated as\n * resizable — back-compat: handles show unless a consumer opts a node out. */\n readonly selectionResizable?: boolean;\n /** Whether a path is currently in anchor-edit mode. Read by the\n * `editingAnchors:` selector, which gates the path-edit chrome.\n *\n * This is deliberately a fact about state, not about permission: the\n * anchor overlay and the anchor hit-test must agree, and the thing they\n * must agree on is \"is there an edited path right now\", which no\n * capability or mode id answers. A mode that allows `edits-anchors`\n * with nothing being edited should draw no anchors. Absent is treated\n * as false. */\n readonly editingAnchors?: boolean;\n /** Device facts — pointer coarseness, hover capability, density.\n *\n * Absent (legacy ctx builders) is treated as\n * {@link DEFAULT_DEVICE_PROFILE}: a fine pointer that can hover, at\n * density 1. That is what the kit assumed before this field existed, so\n * an absent profile is behavior-preserving by construction. */\n readonly device?: DeviceProfile;\n /** The view the input being dispatched landed in — a view id, or `null`\n * for the surface's own camera. The dispatcher fills it; absent anywhere\n * else a rule is evaluated. */\n readonly viewId?: string | null;\n}\n\n/** The live state a `RuleCtx` is assembled from — the chrome context plus\n * what the active mode allows. */\nexport interface BuildRuleCtxArgs {\n focused: boolean;\n selection: readonly NodeId[];\n multiActive: boolean;\n modifiers: ModifierState;\n action: { kind: string | null; id: string | null };\n hover: NodeId | null;\n /** See {@link RuleCtx.zoom}. */\n zoom?: number;\n mode: string;\n allowedCapabilities: ReadonlySet<CapabilityTag>;\n /** Optional — omitted means \"resizable\" (handles show). See {@link RuleCtx}. */\n selectionResizable?: boolean;\n /** Optional — omitted means \"no path is being anchor-edited\". */\n editingAnchors?: boolean;\n /** Optional — omitted means {@link DEFAULT_DEVICE_PROFILE}. */\n device?: DeviceProfile;\n}\n\n/**\n * Capability set to assume when no mode registry is wired.\n *\n * \"No modes configured\" means *everything the default mode permits*, not\n * *nothing permitted*. The empty set is the wrong default: it makes every\n * `capability:` rule evaluate false, so a kit default written the\n * recommended way (capability rules outlive new modes; mode rules have to\n * be edited) would silently hide its chrome for every consumer that hasn't\n * opted into modality. `NORMAL.allows` plus the implicit tags is what a\n * mode-less canvas actually behaves like.\n */\nexport const DEFAULT_ALLOWED_CAPABILITIES = activeModeOf(NORMAL).allowedCapabilities as ReadonlySet<CapabilityTag>;\n\n/** Gather the current canvas and mode state into the context that action\n * eligibility and chrome-visibility rules are evaluated against. */\nexport function buildRuleCtx(args: BuildRuleCtxArgs): RuleCtx {\n return {\n focused: args.focused,\n selection: args.selection,\n multiActive: args.multiActive,\n modifiers: args.modifiers,\n action: args.action,\n hover: args.hover,\n zoom: args.zoom,\n mode: args.mode,\n allowedCapabilities: args.allowedCapabilities,\n selectionResizable: args.selectionResizable,\n editingAnchors: args.editingAnchors,\n device: args.device,\n };\n}\n","/**\n * The slot an in-flight ongoing handle is keyed by:\n * - `key-held`: `key-held-<code>` (`key-held-Space`), so two keys that share a\n * `key`, such as the two Shifts, hold separately. An event with no code keys\n * by `key`.\n * - `pointerdown` and the drag that follows: `pointer-<pointerId>`. An event\n * with no `pointerId` (a synthesized probe, a programmatic drag, most tests)\n * keys to `pointer-mouse`.\n * - `multitouch`: `multitouch-<fingers>`.\n * - `carry`: `carry-<pointerId>`, keyed as a pointer is.\n * - any other kind that starts an ongoing invoker: `ongoing-<kind>`.\n */\nimport type { InputEvent } from './matcher';\n\n/**\n * The in-flight handle slot a pointer's gestures key into. Exported because\n * the React seam (`useGestureDispatcher`) has to name the same slot when it\n * asks `dispatcher.inFlight()` whether a given pointer is mid-drag.\n *\n * @param pointerId - `PointerEvent.pointerId`, or `undefined` for a\n * synthesized event with no originating DOM pointer.\n */\nexport function pointerGestureId(pointerId: number | undefined): string {\n return `pointer-${pointerId ?? 'mouse'}`;\n}\n\n/** The gesture id a carry by this pointer runs under. */\nexport function carryGestureId(pointerId: number | undefined): string {\n return `carry-${pointerId ?? 'mouse'}`;\n}\n\n/** The in-flight handle slot a multitouch gesture of `fingers` fingers keys into. */\nexport function multiTouchGestureId(fingers: number): string {\n return `multitouch-${fingers}`;\n}\n\n/** Whether `gestureId` is a multitouch gesture's, of any finger count. */\nexport function isMultiTouchGestureId(gestureId: string): boolean {\n return gestureId.startsWith('multitouch-');\n}\n\nexport function gestureIdFor(event: InputEvent): string {\n if (event.kind === 'key-held') {\n return `key-held-${event.code ?? event.key}`;\n }\n if (\n event.kind === 'pointerdown' ||\n event.kind === 'pointermove' ||\n event.kind === 'pointerup' ||\n event.kind === 'pointercancel'\n ) {\n return pointerGestureId(event.pointerId);\n }\n if (event.kind === 'multitouch') {\n return multiTouchGestureId(event.fingers);\n }\n if (event.kind === 'carry') {\n return carryGestureId(event.pointerId);\n }\n return `ongoing-${event.kind}`;\n}\n","import type { BindingScope } from '../interactions/dispatcher/matcher';\nimport type { CapabilityTag } from '@weasel-js/modes';\nimport type { Eligibility } from './types';\n\n/** What the registry knows at dispatch time. */\nexport interface EligibilityState {\n focusedId: string | null;\n /** Ids the host reports as hotkey-engaged. A held `offhand` trigger reaches\n * here the same way a palette pick does: the `tool.offhand` action pushes\n * the tool's id onto the active-tool context's hotkey stack. */\n engagedIds?: ReadonlySet<string>;\n /** Whether the active mode allows these capability tags. Omitted → allow. */\n allows?: (tags: readonly CapabilityTag[]) => boolean;\n /** The innermost open keymap's id: the one keymap entry that is live. */\n openKeymap?: string | null;\n}\n\n/**\n * The scope tier an entry's bindings are live at, or null when none are.\n * Ordered hotkey > active > ambient to match the dispatcher's own walk.\n */\nexport function liveScope(\n id: string,\n eligibility: Eligibility,\n state: EligibilityState,\n): BindingScope | null {\n const tags = eligibility.capabilities;\n if (tags && state.allows && !state.allows(tags)) return null;\n if (eligibility.keymap) return state.openKeymap === id ? 'hotkey' : null;\n if (state.engagedIds?.has(id)) return 'hotkey';\n if (eligibility.focus && state.focusedId === id) return 'active';\n if (eligibility.always || eligibility.claimed) return 'ambient';\n return null;\n}\n","import type { ScopedBinding } from '../interactions/dispatcher/matcher';\nimport { capabilitiesAllowed, type CapabilityTag } from '@weasel-js/modes';\nimport { NO_OVERRIDES, overriddenBindings, type ResolvedBindingOverrides } from '../interactions/actions/bindingOverrides';\nimport { liveScope, type EligibilityState } from './eligibility';\nimport type { Contribution } from './types';\n\n/**\n * Every binding the entry set contributes right now, each tiered by the\n * entry's own declared eligibility. Entries with no live tier are omitted.\n *\n * Order is preserved: `matchSorted` sorts by specificity within a scope and\n * breaks ties by declaration order, so the caller's entry order decides which\n * of two same-specificity bindings in one tier wins.\n */\nexport function scopeBindings(\n entries: Iterable<Contribution<unknown>>,\n state: EligibilityState,\n overrides: ResolvedBindingOverrides = NO_OVERRIDES,\n): ScopedBinding[] {\n const out: ScopedBinding[] = [];\n for (const entry of entries) {\n const scope = liveScope(entry.id, entry.eligibility ?? {}, state);\n if (scope === null) continue;\n for (const binding of overriddenBindings(entry.bindings ?? [], entry.id, overrides)) {\n out.push({ binding, scope, ownerId: entry.id });\n }\n }\n return out;\n}\n\n/** What decides which entries are live, and in what order they are walked. */\nexport interface AssemblyInputs {\n focusedId: string | null;\n /** Ids held by a hotkey, oldest first, as the active-tool context keeps them. */\n hotkeyStack: readonly string[];\n /** The capability tags the active mode allows. Omitted: no mode system, so\n * every entry is allowed. */\n allowedCapabilities?: ReadonlySet<CapabilityTag>;\n /** The innermost open keymap's id, if one is open. */\n openKeymap?: string | null;\n}\n\n/**\n * The entry set as routing walks it, with the state that tiers it. The\n * dispatcher's bindings and a canvas's tool overlays both come from here, so a\n * tool the dispatcher would not route to is never drawn, and two held tools\n * stack in one order.\n *\n * Held entries lead, newest hold first: the top of the stack is the one every\n * reader treats as engaged, so it wins a tie within the hotkey tier. A tagged\n * entry is live only while the mode allows every one of its tags.\n */\nexport function assembleEntries<T extends Contribution<unknown>>(\n entries: Iterable<T>,\n inputs: AssemblyInputs,\n): { ordered: T[]; state: EligibilityState } {\n const all = [...entries];\n const ordered: T[] = [];\n for (let i = inputs.hotkeyStack.length - 1; i >= 0; i--) {\n const entry = all.find((e) => e.id === inputs.hotkeyStack[i]);\n if (entry && !ordered.includes(entry)) ordered.push(entry);\n }\n for (const entry of all) {\n if (!ordered.includes(entry)) ordered.push(entry);\n }\n const allowed = inputs.allowedCapabilities;\n return {\n ordered,\n state: {\n focusedId: inputs.focusedId,\n engagedIds: new Set(inputs.hotkeyStack),\n ...(inputs.openKeymap ? { openKeymap: inputs.openKeymap } : {}),\n ...(allowed ? { allows: (tags: readonly CapabilityTag[]) => capabilitiesAllowed(allowed, tags) } : {}),\n },\n };\n}\n","/**\n * What a canvas's dispatchers did: one record per resolved input and one per\n * mode switch, in a rolling buffer the devtools hook reads.\n */\nimport { createEmitter } from '@weasel-js/registry';\nimport type { DispatchRecord } from './dispatchRecord';\nimport { isDev } from '@weasel-js/react';\n\n/** One entry per \"mode change\" — a kit state transition that isn't a\n * dispatched input event but explains why an input was (or wasn't) handled\n * later. Pushed via {@link DispatchTrace.recordModeSwitch}. */\nexport interface ModeSwitchLogEntry {\n kind: 'mode';\n ts: number;\n /** Logical mode name, e.g. `'editAnchors.editingId'`. */\n mode: string;\n from: string | null;\n to: string | null;\n /** Optional free-form context — `'enterPathEdit'`, `'exitPathEdit'`,\n * `'selection-dropped target'`, etc. */\n detail?: string;\n}\n\n/** A trace entry: one {@link DispatchRecord} per resolved input, or a mode switch. */\nexport type TraceLogEntry = DispatchRecord | ModeSwitchLogEntry;\n\n/** A rolling buffer that records in a dev build, and in any build while something watches it. */\nexport interface TraceRing<T> {\n /** Whether a push now keeps its entry. A caller building an entry checks first. */\n recording(): boolean;\n push(entry: T): void;\n /** The entries pushed after `cursor`, oldest first, and the cursor to pass\n * next time. Start from 0. Entries the buffer has dropped are skipped. */\n since(cursor: number): { entries: T[]; cursor: number };\n /** Turn recording on until the returned release is called. */\n watch(): () => void;\n /** Hear each kept push. Returns the unsubscribe. */\n subscribe(listener: () => void): () => void;\n}\n\n/** A {@link TraceRing} keeping the last `limit` entries. `dev` defaults to the build's. */\nexport function createTraceRing<T>(limit = 200, dev = isDev()): TraceRing<T> {\n const entries: T[] = [];\n const pushed = createEmitter();\n let total = 0;\n let watchers = 0;\n const recording = () => dev || watchers > 0;\n return {\n recording,\n push(entry) {\n if (!recording()) return;\n entries.push(entry);\n if (entries.length > limit) entries.shift();\n total++;\n pushed.emit();\n },\n since(cursor) {\n const first = total - entries.length;\n return { entries: entries.slice(Math.max(cursor, first) - first), cursor: total };\n },\n watch() {\n watchers++;\n let released = false;\n return () => {\n if (released) return;\n released = true;\n watchers--;\n };\n },\n subscribe: pushed.subscribe,\n };\n}\n\n/** One canvas's dispatch trace. `useGestureDispatcher` makes one, puts it on\n * every `DispatcherContext` it builds, and publishes it as the `dispatchTrace` dep. */\nexport interface DispatchTrace extends TraceRing<TraceLogEntry> {\n recordModeSwitch(mode: string, from: string | null, to: string | null, detail?: string): void;\n /** Offer the record for what a press at the pointer would do, built only\n * when {@link DispatchTrace.live} reads it. `null` withdraws it. */\n setLive(explain: (() => DispatchRecord) | null): void;\n live(): DispatchRecord | null;\n}\n\n/** A {@link DispatchTrace} keeping the last `limit` entries. `dev` defaults to the build's. */\nexport function createDispatchTrace(limit?: number, dev?: boolean): DispatchTrace {\n const ring = createTraceRing<TraceLogEntry>(limit, dev);\n let explain: (() => DispatchRecord) | null = null;\n return {\n ...ring,\n recordModeSwitch(mode, from, to, detail) {\n ring.push({ kind: 'mode', ts: Date.now(), mode, from, to, ...(detail !== undefined ? { detail } : {}) });\n },\n setLive(next) {\n explain = next;\n },\n live: () => explain?.() ?? null,\n };\n}\n","/**\n * How the dispatcher orders one input's candidates: the view a binding names,\n * its scope tier, its specificity, then whether its action is gated by a rule\n * that holds. Dispatch, prediction, and the trace record all rank through here.\n */\nimport type { GestureSpec } from '@weasel-js/gestures';\nimport type { Action } from '../actions/action';\nimport type { GestureBinding } from '../actions/binding';\nimport { describeRule, evaluate, type Condition, type Rule, type RuleCtx } from '../../eligibility';\nimport type { DispatcherContext, KeyReach } from './dispatcherApi';\nimport type { PlacedBy, SpecificityPart, WalkStep } from './dispatchRecord';\nimport { specificity, type MatchResult } from './matcher';\n\n/** Whether `binding` is live for input routed to `view`. */\nexport function liveInView(binding: GestureBinding, view: string | null): boolean {\n const views = binding.opts?.views;\n return views === undefined || views.includes(view);\n}\n\n/** Whether `binding` is live for a key that reached `reach`. See\n * `BindingOpts.over`. */\nexport function liveForKeys(binding: GestureBinding, reach: KeyReach | undefined): boolean {\n if (reach === undefined) return true;\n return binding.opts?.over ? reach.over : reach.held;\n}\n\n/** Stable partition: matches whose binding names `view` first. See\n * `BindingOpts.views` for why naming the view outranks the scope tier. */\nexport function namesView(binding: GestureBinding, view: string | null): boolean {\n return binding.opts?.views?.includes(view) ?? false;\n}\n\nexport function preferViewScoped<M extends { binding: GestureBinding }>(\n matches: readonly M[],\n view: string | null,\n): M[] {\n const named: M[] = [];\n const rest: M[] = [];\n for (const m of matches) {\n (namesView(m.binding, view) ? named : rest).push(m);\n }\n return named.length === 0 ? [...matches] : [...named, ...rest];\n}\n\n/** The routed view's rule context, carrying the view id. */\nexport function ruleCtxOf(ctx: DispatcherContext): RuleCtx | undefined {\n const r = ctx.getRuleCtx?.();\n return r ? { ...r, viewId: ctx.viewId ?? null } : undefined;\n}\n\n/**\n * Normalize an `Action.eligible` value to a raw `Rule`. Conditions are\n * callable functions carrying `.rule`; raw Rules are returned as-is.\n */\nfunction eligibleToRule(eligible: Rule | Condition): Rule {\n return typeof eligible === 'function' ? (eligible as Condition).rule : eligible;\n}\n\n/** Does `action`'s declared eligibility rule pass against `ruleCtx`?\n * An action with no `eligible` rule is always eligible. */\nexport function isEligible(action: Action, ruleCtx: RuleCtx): boolean {\n if (!action.eligible) return true;\n return evaluate(eligibleToRule(action.eligible), ruleCtx);\n}\n\n/** Render an `eligible` rule for display. `evaluate()` returns a bare\n * boolean, so there is no reason string to carry — the rule itself is the\n * most informative thing available. */\nexport function describeEligible(eligible: NonNullable<Action['eligible']>): string {\n return describeRule(eligibleToRule(eligible));\n}\n\n/**\n * Filter `matches` to only those whose backing action has no `eligible`\n * rule, or whose rule evaluates true against `ruleCtx`. Exported for\n * unit testing.\n *\n * @internal\n */\nexport function filterEligible<M extends { binding: { actionId: string } }>(\n matches: readonly M[],\n actionLookup: (id: string) => Action | undefined,\n ruleCtx: RuleCtx,\n): M[] {\n return matches.filter((m) => {\n const action = actionLookup(m.binding.actionId);\n if (!action) return true;\n return isEligible(action, ruleCtx);\n });\n}\n\n/**\n * Among matches tied on scope and specificity, put those whose action is\n * gated by an `eligible` rule that holds now ahead of those with no rule: a\n * binding that applies only in the current context — Escape while editing a\n * path — outranks one that applies everywhere. Otherwise stable.\n *\n * @internal\n */\nexport function preferContextual<M extends { binding: GestureBinding; scope: string }>(\n matches: readonly M[],\n actionLookup: (id: string) => Action | undefined,\n /** Whether a gated action's rule holds; skip re-asking where the matches\n * were already filtered by it. */\n holds: (action: Action) => boolean,\n /** The routed view: a binding naming it is never tied with one that does not. */\n view: string | null,\n): M[] {\n const out: M[] = [];\n let run: M[] = [];\n const flush = (): void => {\n const gated = run.filter((m) => {\n const action = actionLookup(m.binding.actionId);\n return action?.eligible !== undefined && holds(action);\n });\n out.push(...gated, ...run.filter((m) => !gated.includes(m)));\n run = [];\n };\n for (const m of matches) {\n const head = run[0];\n if (\n head\n && (head.scope !== m.scope\n || namesView(head.binding, view) !== namesView(m.binding, view)\n || !sameSpecificity(head.binding.spec, m.binding.spec))\n ) flush();\n run.push(m);\n }\n flush();\n return out;\n}\n\nconst SPECIFICITY_PARTS: readonly SpecificityPart[] = ['target', 'mods', 'phase', 'exact'];\n\n/** The ranking step that put `cur` directly below `prev`. `contextual` says\n * `prev` is gated by a rule that holds and `cur` is not — the only thing the\n * step after specificity looks at. */\nexport function placedBy(\n prev: MatchResult,\n cur: MatchResult,\n view: string | null,\n contextual: boolean,\n): PlacedBy {\n if (namesView(prev.binding, view) !== namesView(cur.binding, view)) return { step: 'view' };\n if (prev.scope !== cur.scope) return { step: 'tier' };\n const sp = specificity(prev.binding.spec);\n const sc = specificity(cur.binding.spec);\n const i = sp.findIndex((v, k) => v !== sc[k]);\n if (i >= 0) return { step: 'specificity', part: SPECIFICITY_PARTS[i]! };\n return contextual ? { step: 'context' } : { step: 'order' };\n}\n\nfunction sameSpecificity(a: GestureSpec, b: GestureSpec): boolean {\n const sa = specificity(a);\n const sb = specificity(b);\n return sa.every((v, i) => v === sb[i]);\n}\n\n/** One input's candidates, matched, filtered and ranked, before any is asked. */\nexport interface Ranking {\n /** Every match the claim admitted, best first — ineligible ones\n * included, in the place they would hold. */\n ordered: MatchResult[];\n /** Matches an exclusive claim barred; collected only when recording. */\n barred: MatchResult[];\n claimOwner?: string;\n actionMap: Map<string, Action>;\n ruleCtx: RuleCtx | undefined;\n /** Whether a match survives the eligibility filter. */\n eligible(m: MatchResult): boolean;\n}\n\nexport interface Walked {\n /** Survivors of both filters, best first, each with what the walk did. */\n steps: Array<{ match: MatchResult; step: WalkStep }>;\n /** Why the walk ended: a candidate fired (or would), one was misbound, or\n * every candidate was exhausted. */\n stop: 'fired' | 'misbound' | 'exhausted';\n winner: { match: MatchResult; action: Action } | null;\n}\n","import { routesForSpec } from '../../tools/routing/reflection/registry';\nimport type { DispatcherContext } from './dispatcherApi';\nimport type { DispatchRecord, DroppedCandidate, RankedCandidate, RecordCandidate } from './dispatchRecord';\nimport { modifierStateOf, worldPointOf } from './inputFacts';\nimport { specificity, type InputEvent, type MatchResult } from './matcher';\nimport { describeEligible, namesView, placedBy, type Ranking, type Walked } from './ranking';\n\n/** Project a ranking and its walk into a plain {@link DispatchRecord}. */\nexport function buildDispatchRecord(\n r: Ranking,\n walked: Walked,\n event: InputEvent,\n ctx: DispatcherContext,\n predicted: boolean,\n outcome: 'handled' | 'unhandled',\n): DispatchRecord {\n const view = ctx.viewId ?? null;\n const candidates = new Map<MatchResult, RecordCandidate>();\n const candidateOf = (m: MatchResult): RecordCandidate => {\n let c = candidates.get(m);\n if (!c) {\n const eligible = r.actionMap.get(m.binding.actionId)?.eligible;\n c = {\n actionId: m.binding.actionId,\n routes: routesForSpec(m.binding.spec),\n scope: m.scope,\n ownerId: m.ownerId,\n namesView: namesView(m.binding, view),\n specificity: specificity(m.binding.spec),\n ...(eligible !== undefined ? { eligible: describeEligible(eligible) } : {}),\n };\n candidates.set(m, c);\n }\n return c;\n };\n const dropped: DroppedCandidate[] = [\n ...r.barred.map((m): DroppedCandidate => ({\n candidate: candidateOf(m),\n filter: 'claim',\n ...(r.claimOwner !== undefined ? { owner: r.claimOwner } : {}),\n })),\n ];\n for (const m of r.ordered) {\n if (r.eligible(m)) continue;\n const c = candidateOf(m);\n dropped.push({ candidate: c, filter: 'ineligible', rule: c.eligible ?? '' });\n }\n const gated = (m: MatchResult): boolean =>\n r.actionMap.get(m.binding.actionId)?.eligible !== undefined;\n const ranked: RankedCandidate[] = walked.steps.map(({ match, step }, i) => {\n const prev = walked.steps[i - 1]?.match;\n return {\n candidate: candidateOf(match),\n placedBy: prev ? placedBy(prev, match, view, r.ruleCtx !== undefined && gated(prev) && !gated(match)) : { step: 'first' },\n walk: step,\n };\n });\n const eventKey = event.kind === 'key' || event.kind === 'key-held' ? event.key : undefined;\n const world = worldPointOf(event);\n return {\n kind: 'dispatch',\n ts: Date.now(),\n input: {\n eventKind: event.kind,\n ...(eventKey !== undefined ? { key: eventKey } : {}),\n modifiers: modifierStateOf(event),\n viewId: view,\n ...(world !== undefined ? { world } : {}),\n ...(r.ruleCtx !== undefined ? { mode: r.ruleCtx.mode } : {}),\n },\n matched: [...r.ordered, ...r.barred].map(candidateOf),\n dropped,\n ranked,\n predicted,\n fired: walked.winner?.action.id ?? null,\n outcome,\n };\n}\n","/**\n * What the dispatcher remembers about each gesture between its events: where\n * a drag began, the trail it has drawn, the spread a pinch opened at, and how\n * far its fingers have turned.\n */\nimport { stylusOf } from '@weasel-js/gestures';\nimport type { DragSample } from '../actions/invoker';\nimport type { RoleKeys } from '../actions/modifierRoles';\nimport type { InputEvent } from './matcher';\n\n/**\n * A drag's origin in world (`x`/`y`) and client coordinates, so a context can\n * carry both `drag.delta` and `drag.screenDelta`.\n */\nexport interface DragOrigin { x: number; y: number; clientX?: number; clientY?: number }\n\n/** One gesture's remembered facts, as an invocation context reads them. */\nexport interface GestureFacts {\n origin?: DragOrigin;\n /** The live accumulator: it grows with each move. */\n points?: DragSample[];\n startSpread?: number;\n /** Degrees a multitouch gesture's fingers have turned since it began. */\n rotation?: number;\n /** The keys each of the action's modifier roles answers to, `'mod'`\n * already resolved for the platform. */\n roleKeys?: Readonly<Record<string, RoleKeys>>;\n}\n\nexport interface GestureFactsStore {\n /** Record what the event that starts a gesture establishes, and the keys\n * its action's modifier roles answer to. */\n begin(gestureId: string, event: InputEvent, roleKeys?: Readonly<Record<string, RoleKeys>>): void;\n /** Add a move to the gesture's trail, whether or not its handle previews:\n * `onEnd` is handed the same trail, so an action that only reads the\n * finished path, and declares no `onMove`, still gets every vertex. */\n sample(gestureId: string, event: InputEvent & { kind: 'pointermove' }): void;\n /** Add a multitouch move's change of angle to the gesture's turn. */\n turn(gestureId: string, event: InputEvent & { kind: 'multitouch' }): void;\n of(gestureId: string | undefined): GestureFacts;\n drop(gestureId: string): void;\n clear(): void;\n}\n\nexport function createGestureFacts(): GestureFactsStore {\n const origins = new Map<string, DragOrigin>();\n const points = new Map<string, DragSample[]>();\n const startSpreads = new Map<string, number>();\n const turns = new Map<string, { last: number; total: number }>();\n const roles = new Map<string, Readonly<Record<string, RoleKeys>>>();\n return {\n begin(gestureId, event, roleKeys) {\n if (roleKeys) roles.set(gestureId, roleKeys);\n if (event.kind === 'pointerdown') {\n origins.set(gestureId, {\n x: event.x ?? 0,\n y: event.y ?? 0,\n ...(event.clientX !== undefined ? { clientX: event.clientX } : {}),\n ...(event.clientY !== undefined ? { clientY: event.clientY } : {}),\n });\n points.set(gestureId, [{ x: event.x ?? 0, y: event.y ?? 0, ...stylusOf(event) }]);\n }\n if (event.kind === 'multitouch' && event.spread !== undefined) {\n startSpreads.set(gestureId, event.spread);\n }\n if (event.kind === 'multitouch' && event.angle !== undefined) {\n turns.set(gestureId, { last: event.angle, total: 0 });\n }\n },\n sample(gestureId, event) {\n points.get(gestureId)?.push({ x: event.x, y: event.y, ...stylusOf(event) });\n },\n turn(gestureId, event) {\n const turn = turns.get(gestureId);\n if (!turn || event.angle === undefined) return;\n // The shorter way round: an angle crossing 180 has not turned a full circle.\n const step = event.angle - turn.last;\n turn.total += step - 360 * Math.round(step / 360);\n turn.last = event.angle;\n },\n of(gestureId) {\n if (gestureId === undefined) return {};\n const origin = origins.get(gestureId);\n const trail = points.get(gestureId);\n const startSpread = startSpreads.get(gestureId);\n const turn = turns.get(gestureId);\n const roleKeys = roles.get(gestureId);\n return {\n ...(roleKeys !== undefined ? { roleKeys } : {}),\n ...(origin !== undefined ? { origin } : {}),\n ...(trail !== undefined ? { points: trail } : {}),\n ...(startSpread !== undefined ? { startSpread } : {}),\n ...(turn !== undefined ? { rotation: turn.total } : {}),\n };\n },\n drop(gestureId) {\n origins.delete(gestureId);\n points.delete(gestureId);\n startSpreads.delete(gestureId);\n turns.delete(gestureId);\n roles.delete(gestureId);\n },\n clear() {\n origins.clear();\n points.clear();\n startSpreads.clear();\n turns.clear();\n roles.clear();\n },\n };\n}\n","/** The ongoing handles a dispatcher has in flight, keyed by gesture id. */\nimport { resolveCursor, type CursorSpec } from '@weasel-js/cursor';\nimport { actionCursor, type Action } from '../actions/action';\nimport type { OngoingHandle } from '../actions/invoker';\n\nconst EMPTY_ENGAGED: ReadonlySet<string> = new Set();\n\nexport interface InFlightGestures {\n /** Live: it changes as gestures open and end. */\n readonly handles: ReadonlyMap<string, OngoingHandle>;\n /**\n * Put `handle` in flight. `ownerId` is the entry whose binding opened it,\n * `null` for an ambient action or a UI-driven handle; `action` is whose\n * handle it is, where a cursor may be read from it.\n */\n open(gestureId: string, handle: OngoingHandle, ownerId: string | null, action?: Action): void;\n /** Take a gesture out of flight, returning its handle so the caller can end it. */\n take(gestureId: string): OngoingHandle | undefined;\n /** Take every gesture out of flight. */\n takeAll(): Array<[string, OngoingHandle]>;\n /** The ids of the entries that own a gesture in flight: the matcher's `engagedChannels`. */\n engagedOwners(): ReadonlySet<string>;\n /** What the gesture begun last currently is, where its handle or action says. See\n * `OngoingHandle.cursor` and `Action.activeCursor`. */\n cursor(): CursorSpec | null;\n /** The gesture begun last. */\n latest(): { kind: string | null; id: string | null };\n}\n\nexport function createInFlightGestures(): InFlightGestures {\n const handles = new Map<string, OngoingHandle>();\n const owners = new Map<string, string | null>();\n const actions = new Map<string, Action>();\n\n const forget = (gestureId: string): void => {\n handles.delete(gestureId);\n owners.delete(gestureId);\n actions.delete(gestureId);\n };\n\n return {\n handles,\n open(gestureId, handle, ownerId, action) {\n handles.set(gestureId, handle);\n owners.set(gestureId, ownerId);\n if (action) actions.set(gestureId, action);\n },\n take(gestureId) {\n const handle = handles.get(gestureId);\n forget(gestureId);\n return handle;\n },\n takeAll() {\n const all = [...handles];\n handles.clear();\n owners.clear();\n actions.clear();\n return all;\n },\n engagedOwners() {\n if (owners.size === 0) return EMPTY_ENGAGED;\n const out = new Set<string>();\n for (const owner of owners.values()) {\n if (owner != null) out.add(owner);\n }\n return out;\n },\n cursor() {\n // Latest start wins, matching `latest` — with a mouse and a pen in\n // flight together the cursor belongs to the gesture the user just\n // began, not the one they began first. Map iteration is insertion order\n // and each gestureId is set exactly once, so the last entry is the newest.\n let cursor: CursorSpec | null = null;\n for (const [id, handle] of handles) {\n const action = actions.get(id);\n const spec = handle.cursor?.() ?? action?.activeCursor ?? actionCursor(action);\n // The spec, not its CSS form: a painted glyph resolves to 'none', which\n // would tell the pump to hide the cursor and paint nothing.\n if (spec !== undefined && resolveCursor(spec)) cursor = spec;\n }\n return cursor;\n },\n latest() {\n let lastId: string | null = null;\n let lastHandle: OngoingHandle | null = null;\n for (const [id, handle] of handles) {\n lastId = id;\n lastHandle = handle;\n }\n if (lastHandle === null) return { kind: null, id: null };\n return { kind: lastHandle.kind ?? null, id: lastId };\n },\n };\n}\n\n/** Whether a handle carries no gesture-processing callbacks or preview data:\n * the invoker decided at runtime not to engage. */\nexport function isEmptyOngoingHandle(h: OngoingHandle): boolean {\n return !h.onMove && !h.onEnd && !h.overlay && !h.previewIds && !h.previewPose;\n}\n","/** Builds the `InvocationCtx` an action's invoker is handed for one event. */\nimport type { ActionDeps, AffordanceHit, InvocationCtx, Point2 } from '../actions/invoker';\nimport { resolveRoles } from '../actions/modifierRoles';\nimport type { GestureFacts } from './gestureFacts';\nimport type { InputEvent } from './matcher';\n\n/** A context for an invocation no pointer event drives, where world and\n * screen coordinates mean nothing: a UI-driven handle, or a cancel-all. */\nexport function uiInvocationCtx(deps: ActionDeps, params?: Record<string, unknown>): InvocationCtx {\n return {\n world: { x: 0, y: 0 },\n modifiers: { alt: false, ctrl: false, meta: false, shift: false },\n deps,\n ...(params !== undefined ? { params } : {}),\n };\n}\n\n// The pointer in client pixels, where the event carries it. Not every kind\n// does, which is why `ctx.screen` is optional.\nfunction clientPoint(ev: InputEvent): Point2 | undefined {\n const cx = (ev as { clientX?: number }).clientX;\n const cy = (ev as { clientY?: number }).clientY;\n return cx !== undefined && cy !== undefined ? { x: cx, y: cy } : undefined;\n}\n\nfunction pressDrag(\n event: InputEvent & { kind: 'pointerdown' | 'click' | 'doubleclick' | 'contextmenu' },\n): Pick<InvocationCtx, 'world' | 'drag'> {\n // A click's own world point is `x`/`y` — the release — with the press\n // as the fallback for a consumer that wired neither.\n const sx = event.x ?? (event.kind === 'click' ? event.pressX : undefined) ?? 0;\n const sy = event.y ?? (event.kind === 'click' ? event.pressY : undefined) ?? 0;\n const affordance = event.kind === 'pointerdown' ? (event.affordance as AffordanceHit | undefined) : undefined;\n return {\n world: { x: sx, y: sy },\n drag: {\n start: { x: sx, y: sy },\n current: { x: sx, y: sy },\n delta: { x: 0, y: 0 },\n ...(affordance !== undefined ? { affordance } : {}),\n },\n };\n}\n\nfunction pumpDrag(\n event: InputEvent & { kind: 'pointermove' | 'pointerup' },\n facts: GestureFacts,\n): Pick<InvocationCtx, 'world' | 'drag'> {\n const cx = event.x;\n const cy = event.y;\n const origin = facts.origin;\n const ox = origin?.x ?? cx;\n const oy = origin?.y ?? cy;\n // Live accumulator during the drag — copying it on every move would be\n // quadratic — but a snapshot on the last event, because `onEnd` is where\n // an action is entitled to keep the trail, and the dispatcher clears the\n // accumulator the moment it returns.\n const live = facts.points;\n const points = live && event.kind === 'pointerup' ? [...live] : live;\n // Screen-space delta — populated when both the event and origin carry\n // client coords. View-mutating drag actions must read this rather than\n // the world `delta` (world deltas are self-referential mid-pan).\n const eventClientX = event.clientX;\n const eventClientY = event.clientY;\n const hasClient =\n eventClientX !== undefined && eventClientY !== undefined\n && origin?.clientX !== undefined && origin?.clientY !== undefined;\n return {\n world: { x: cx, y: cy },\n drag: {\n start: { x: ox, y: oy },\n current: { x: cx, y: cy },\n delta: { x: cx - ox, y: cy - oy },\n ...(hasClient\n ? { screenDelta: { x: eventClientX! - origin!.clientX!, y: eventClientY! - origin!.clientY! } }\n : {}),\n ...(points !== undefined ? { points } : {}),\n },\n };\n}\n\nfunction multiTouchOf(\n event: InputEvent & { kind: 'multitouch' },\n facts: GestureFacts,\n): NonNullable<InvocationCtx['multiTouch']> {\n const centroid = event.centroid ?? { x: 0, y: 0 };\n const spread = event.spread ?? 1;\n const { startSpread } = facts;\n return {\n centroid,\n spread,\n rotation: facts.rotation ?? 0,\n // Pinch geometry, on a move of a running gesture.\n ...(startSpread !== undefined && event.spread !== undefined\n ? { pinch: { startSpread, currentSpread: spread, centroid } }\n : {}),\n };\n}\n\n/**\n * The context for `event`. `viewId` is the view the input landed in, left\n * off when `undefined`; `facts` are what the dispatcher remembers of the\n * gesture the event belongs to.\n */\nexport function buildInvocationCtx(\n event: InputEvent,\n deps: ActionDeps,\n viewId: string | null | undefined,\n facts: GestureFacts = {},\n): InvocationCtx {\n const base: InvocationCtx = {\n world: { x: 0, y: 0 },\n modifiers: { alt: event.altKey, ctrl: event.ctrlKey, meta: event.metaKey, shift: event.shiftKey },\n deps,\n ...(viewId !== undefined ? { viewId } : {}),\n };\n const screen = clientPoint(event);\n if (screen) base.screen = screen;\n // `'mod'` was resolved when the gesture began, so the platform is moot here.\n if (facts.roleKeys) base.roles = resolveRoles(facts.roleKeys, base.modifiers, false);\n\n if (event.kind === 'key') {\n base.key = { key: event.key, repeat: event.repeat ?? false };\n } else if (event.kind === 'key-held') {\n base.key = { key: event.key, repeat: false };\n } else if (event.kind === 'wheel') {\n base.wheel = { deltaX: event.deltaX, deltaY: event.deltaY, deltaZ: 0 };\n } else if (event.kind === 'pinch') {\n base.pinch = { scale: event.scale, rotation: event.rotation };\n } else if (\n event.kind === 'pointerdown'\n || event.kind === 'click'\n || event.kind === 'doubleclick'\n || event.kind === 'contextmenu'\n ) {\n Object.assign(base, pressDrag(event));\n } else if (event.kind === 'pointermove' || event.kind === 'pointerup') {\n Object.assign(base, pumpDrag(event, facts));\n } else if (event.kind === 'multitouch') {\n base.multiTouch = multiTouchOf(event, facts);\n } else if (event.kind === 'carry') {\n base.world = { x: event.x, y: event.y };\n base.carry = { type: event.type, value: event.value };\n }\n return base;\n}\n","/**\n * Running a gesture's ongoing handle: starting it for the candidate the walk\n * chose, feeding it the events that continue it, and ending it.\n */\nimport type { Action } from '../actions/action';\nimport type { ActionDeps, InvocationCtx, OngoingHandle } from '../actions/invoker';\nimport { resolveParams } from '../actions/invoker';\nimport { platformRoleKeys, roleKeysOf } from '../actions/modifierRoles';\nimport type { GestureFactsStore } from './gestureFacts';\nimport { gestureIdFor, isMultiTouchGestureId } from './gestureIds';\nimport { isEmptyOngoingHandle, type InFlightGestures } from './inFlightGestures';\nimport { immediateParams } from './inputFacts';\nimport { buildInvocationCtx, uiInvocationCtx } from './invocationCtx';\nimport type { InputEvent, MatchResult } from './matcher';\nimport type { AttemptResult } from './walk';\n\n/** What one dispatcher's gestures run against. */\nexport interface GestureRun {\n inFlight: InFlightGestures;\n facts: GestureFactsStore;\n /** The view the input being handled landed in, so a pump of an in-flight\n * gesture reports the view it is pinned to. */\n viewId(): string | null | undefined;\n /** Whether `'mod'` is Cmd, for the input being handled. */\n isMac(): boolean;\n}\n\ntype Reason = 'commit' | 'cancel';\ntype Outcome = 'handled' | 'unhandled';\n\nconst ctxFor = (run: GestureRun, event: InputEvent, deps: ActionDeps, gestureId: string): InvocationCtx =>\n buildInvocationCtx(event, deps, run.viewId(), run.facts.of(gestureId));\n\nfunction runOnEnd(gestureId: string, handle: OngoingHandle, endCtx: InvocationCtx, reason: Reason): void {\n try {\n handle.onEnd?.(endCtx, reason);\n } catch (err) {\n console.error(`weasel dispatcher: gesture \"${gestureId}\" threw on onEnd`, err);\n }\n}\n\n/** End one in-flight gesture. It is out of flight before its `onEnd` runs,\n * so an `onEnd` that throws, or that reads the dispatcher, sees it gone. */\nfunction endGesture(run: GestureRun, gestureId: string, event: InputEvent, reason: Reason): boolean {\n if (!run.inFlight.handles.has(gestureId)) return false;\n const endCtx = ctxFor(run, event, {}, gestureId);\n const handle = run.inFlight.take(gestureId)!;\n run.facts.drop(gestureId);\n runOnEnd(gestureId, handle, endCtx, reason);\n return true;\n}\n\nfunction endMultiTouch(run: GestureRun, event: InputEvent, reason: Reason, except?: string): boolean {\n let ended = false;\n for (const id of [...run.inFlight.handles.keys()]) {\n if (isMultiTouchGestureId(id) && id !== except) ended = endGesture(run, id, event, reason) || ended;\n }\n return ended;\n}\n\n/** End every gesture in flight, with a context that carries no event. */\nexport function endAllGestures(run: GestureRun, reason: Reason): void {\n const stubCtx = uiInvocationCtx({});\n const ending = run.inFlight.takeAll();\n run.facts.clear();\n for (const [gestureId, handle] of ending) runOnEnd(gestureId, handle, stubCtx, reason);\n}\n\n/**\n * Feed `event` to the gesture it continues. `undefined` when it continues\n * none and may start one.\n */\nexport function pumpGesture(run: GestureRun, event: InputEvent): Outcome | undefined {\n const { inFlight } = run;\n const ended = (reason: Reason): Outcome =>\n (endGesture(run, gestureIdFor(event), event, reason) ? 'handled' : 'unhandled');\n\n if (event.kind === 'key-held' && event.phase === 'up') return ended('commit');\n\n // A key-held DOWN for an already-engaged key is a no-op. Autorepeat\n // keydowns would otherwise fire `start()` again — each start pushes an\n // offhand hotkey, only one keyup ever fires onEnd, so the stack would leak.\n if (event.kind === 'key-held' && event.phase === 'down') {\n return inFlight.handles.has(gestureIdFor(event)) ? 'handled' : undefined;\n }\n\n if (event.kind === 'pointermove') {\n const gestureId = gestureIdFor(event);\n const handle = inFlight.handles.get(gestureId);\n if (!handle) return 'unhandled';\n run.facts.sample(gestureId, event);\n if (!handle.onMove) return 'unhandled';\n handle.onMove(ctxFor(run, event, {}, gestureId));\n return 'handled';\n }\n\n // A wheel continues no gesture of its own, but one in flight may claim it.\n // The newest first, as with the cursor.\n if (event.kind === 'wheel') {\n for (const [gestureId, handle] of [...inFlight.handles].reverse()) {\n if (handle.onWheel?.(ctxFor(run, event, {}, gestureId)) === true) return 'handled';\n }\n return undefined;\n }\n\n if (event.kind === 'carry') return pumpCarry(run, event);\n\n if (event.kind === 'pointerup') return ended('commit');\n if (event.kind === 'pointercancel') return ended('cancel');\n\n // The id carries the finger count the gesture opened with, which the hand\n // has just left, so a multitouch gesture ends by prefix.\n if (event.kind === 'multitouch' && event.end !== undefined) {\n return endMultiTouch(run, event, event.end) ? 'handled' : 'unhandled';\n }\n\n if (event.kind === 'multitouch' && event.centroid !== undefined) {\n const gestureId = gestureIdFor(event);\n const handle = inFlight.handles.get(gestureId);\n if (handle?.onMove) {\n run.facts.turn(gestureId, event);\n handle.onMove(ctxFor(run, event, {}, gestureId));\n return 'handled';\n }\n // A hand is doing one multitouch gesture at a time, but the gesture id\n // carries the finger count — so a finger landing mid-gesture names a\n // different one, and the handle the hand has left is canceled here. (A\n // finger lifting arrives as an `end` event, above.)\n endMultiTouch(run, event, 'cancel', gestureId);\n // With no handle in flight, the first multitouch event can start one.\n }\n return undefined;\n}\n\n/** A carry's moves, release and leave go to the handle it started. A move or\n * a release with none in flight may still be taken by the walk. */\nfunction pumpCarry(run: GestureRun, event: InputEvent & { kind: 'carry' }): Outcome | undefined {\n if (event.stage === 'enter') return undefined;\n const gestureId = gestureIdFor(event);\n const handle = run.inFlight.handles.get(gestureId);\n if (!handle) return event.stage === 'leave' ? 'unhandled' : undefined;\n if (event.stage === 'move') {\n handle.onMove?.(ctxFor(run, event, {}, gestureId));\n return 'handled';\n }\n return endGesture(run, gestureId, event, event.stage === 'drop' ? 'commit' : 'cancel') ? 'handled' : 'unhandled';\n}\n\n/** Whether a carry's stage is one an action of this timing runs at: an\n * ongoing action starts as the carry comes over or moves onto its target,\n * an immediate one fires on the release. */\nfunction carryStageFits(event: InputEvent, timing: 'immediate' | 'ongoing'): boolean {\n if (event.kind !== 'carry') return true;\n return timing === 'immediate' ? event.stage === 'drop' : event.stage === 'enter' || event.stage === 'move';\n}\n\n/** Run the candidate the walk chose. */\nexport function invokeAction(\n run: GestureRun,\n event: InputEvent,\n match: MatchResult,\n action: Action,\n deps: ActionDeps,\n): AttemptResult {\n if (action.invoker && !carryStageFits(event, action.invoker.timing)) return 'empty-handle';\n\n if (action.invoker?.timing === 'immediate') {\n try {\n const params = immediateParams(event, resolveParams(match.binding.opts?.params));\n action.invoker.run(deps, params);\n } catch (err) {\n console.error(`weasel dispatcher: action \"${action.id}\" invoker threw`, err);\n }\n return 'fired';\n }\n\n if (action.invoker?.timing === 'ongoing') {\n // A `pointerDown` binding fires at press time, on the same\n // `pointer-<id>` gesture id the drag will use. Letting an ongoing\n // action open its handle here would make the drag's own dispatch find\n // a handle already in flight and silently no-op.\n if (event.kind === 'hover' || (event.kind === 'pointerdown' && event.stage === 'press')) {\n const spec = event.kind === 'hover' ? 'hover spec, which has no press to own' : 'pointerDown spec, which fires at press time';\n console.error(\n `weasel dispatcher: action \"${action.id}\" has an ongoing invoker but is bound to a `\n + `${spec}. Bind it to a drag spec, or give the action an immediate invoker.`,\n );\n return 'misbound';\n }\n const gestureId = gestureIdFor(event);\n const roleKeys = roleKeysOf(action.modifierRoles, match.binding.opts?.roles);\n run.facts.begin(gestureId, event, roleKeys && platformRoleKeys(roleKeys, run.isMac()));\n const handle = action.invoker.start(ctxFor(run, event, deps, gestureId), match.binding.opts);\n // Empty handle = \"matched at the binding level but decided at runtime\n // not to handle this gesture\" (missing dep, wrong affordance, wrong\n // selection kind, etc.). The widely-used early-return-empty pattern\n // depends on the dispatcher falling through to the next match —\n // otherwise the binding silently swallows the gesture.\n if (isEmptyOngoingHandle(handle)) {\n // A later match, still on the same event, starts from a fresh slate.\n run.facts.drop(gestureId);\n return 'empty-handle';\n }\n run.inFlight.open(gestureId, handle, match.ownerId, action);\n return 'fired';\n }\n\n // No invoker — action is registered but has nothing to do for this\n // matched binding. Treat as handled (the binding consumed the gesture\n // and the no-op is intentional) to keep dispatch deterministic.\n return 'fired';\n}\n","/**\n * Ongoing handles a UI control drives instead of a gesture: a slider scrubbing\n * a value opens one, updates it, and ends it. They sit in flight beside the\n * gestures', so an overlay or a cancel-all treats both alike.\n */\nimport type { Action } from '../actions/action';\nimport type { ActionDeps, OngoingHandle } from '../actions/invoker';\nimport type { UiOngoingControl } from './dispatcherApi';\nimport { isEmptyOngoingHandle, type InFlightGestures } from './inFlightGestures';\nimport { uiInvocationCtx } from './invocationCtx';\n\nexport interface UiOngoing {\n begin(actionId: string, deps: ActionDeps, params?: Record<string, unknown>): UiOngoingControl | null;\n /** Forget which action each handle belongs to, once every handle has been taken out of flight. */\n clear(): void;\n}\n\nexport function createUiOngoing(\n inFlight: InFlightGestures,\n notify: () => void,\n getAction: ((id: string) => Action | undefined) | undefined,\n): UiOngoing {\n let seq = 0;\n /** actionId → gestureId of that action's handle in flight, so a second\n * `begin` for the action commits the first. */\n const byAction = new Map<string, string>();\n\n function commitPrior(actionId: string, deps: ActionDeps): void {\n const prevGestureId = byAction.get(actionId);\n if (prevGestureId === undefined) return;\n const prevHandle = inFlight.handles.get(prevGestureId);\n if (prevHandle?.onEnd) {\n try { prevHandle.onEnd(uiInvocationCtx(deps), 'commit'); }\n catch (e) { console.error(`weasel dispatcher: prior UI handle for \"${actionId}\" threw on auto-commit`, e); }\n }\n inFlight.take(prevGestureId);\n byAction.delete(actionId);\n }\n\n function control(actionId: string, gestureId: string, handle: OngoingHandle, deps: ActionDeps): UiOngoingControl {\n let ended = false;\n // The dispatcher can end this handle without the control knowing —\n // `cancelAll` on tool switch, Escape, or unmount. Absence from the\n // in-flight handles is that signal; without it a later `end()` would\n // run `onEnd` a second time and commit over an already-canceled gesture.\n const live = (): boolean => !ended && inFlight.handles.get(gestureId) === handle;\n return {\n gestureId,\n get active() { return live(); },\n update(nextParams) {\n if (!live()) return;\n if (!handle.onMove) return;\n try { handle.onMove(uiInvocationCtx(deps, nextParams)); }\n catch (e) { console.error(`weasel dispatcher: action \"${actionId}\" threw on onMove`, e); }\n notify();\n },\n end(reason) {\n if (!live()) { ended = true; return; }\n ended = true;\n if (handle.onEnd) {\n try { handle.onEnd(uiInvocationCtx(deps), reason); }\n catch (e) { console.error(`weasel dispatcher: action \"${actionId}\" threw on onEnd`, e); }\n }\n inFlight.take(gestureId);\n if (byAction.get(actionId) === gestureId) byAction.delete(actionId);\n notify();\n },\n };\n }\n\n return {\n begin(actionId, deps, params) {\n if (!getAction) {\n console.warn('weasel dispatcher: beginUiOngoing called but no getAction was provided to createDispatcher');\n return null;\n }\n const action = getAction(actionId);\n if (!action || !action.invoker || action.invoker.timing !== 'ongoing') {\n return null;\n }\n commitPrior(actionId, deps);\n\n const gestureId = `ui-${actionId}-${++seq}`;\n let handle: OngoingHandle;\n try {\n // Params go through both `ctx.params` (the UI-driven channel) and\n // `BindingOpts.params` (the gesture-driven channel).\n handle = action.invoker.start(uiInvocationCtx(deps, params), { params });\n } catch (e) {\n console.error(`weasel dispatcher: action \"${actionId}\" threw on start`, e);\n return null;\n }\n if (isEmptyOngoingHandle(handle)) return null;\n\n inFlight.open(gestureId, handle, null);\n byAction.set(actionId, gestureId);\n notify();\n return control(actionId, gestureId, handle, deps);\n },\n clear: () => { byAction.clear(); },\n };\n}\n","/**\n * The walk: one computation behind dispatch, prediction, and the record.\n * `rank` orders an input's candidates; `walk` asks each in turn, and either\n * runs the first that passes or names it as the predicted winner.\n */\nimport type { Action, ActionSource } from '../actions/action';\nimport { actionBindings, type GestureBinding } from '../actions/binding';\nimport { NO_OVERRIDES } from '../actions/bindingOverrides';\nimport { buildDepsFromRequires } from '../actions/buildDeps';\nimport type { ActionDeps } from '../actions/invoker';\nimport { assembleEntries, scopeBindings } from '../../contributions/assemble';\nimport type { DispatcherContext, ResolvedCandidate } from './dispatcherApi';\nimport type { WalkStep } from './dispatchRecord';\nimport { carriedBy, worldPointOf } from './inputFacts';\nimport type { BindingScope, InputEvent, MatchResult, ScopedBinding } from './matcher';\nimport { matchSortedWithBarred, specificity } from './matcher';\nimport {\n describeEligible, isEligible, liveForKeys, liveInView, preferContextual, preferViewScoped, ruleCtxOf,\n type Ranking, type Walked,\n} from './ranking';\n\n/** What running a candidate came to: `'fired'` ends the walk, `'empty-handle'`\n * falls through to the next candidate, `'misbound'` ends it unhandled. */\nexport type AttemptResult = 'fired' | 'empty-handle' | 'misbound';\nexport type Attempt = (match: MatchResult, action: Action, deps: ActionDeps) => AttemptResult;\n\n/** Every registered entry's bindings, tiered by what the entry declares about\n * its own eligibility, then the actions registry's. */\nfunction assembleScopedBindings(ctx: DispatcherContext): ScopedBinding[] {\n // `allowedCapabilities` is absent for a consumer with no mode system, who\n // supplies no `getRuleCtx`, and then every entry is permitted.\n const allowedCapabilities = ctx.getRuleCtx?.()?.allowedCapabilities;\n const openKeymap = ctx.keymapPass === 'none' ? null : ctx.keymaps?.innermost()?.id ?? null;\n const { ordered, state } = assembleEntries(ctx.entriesById.values(), {\n focusedId: ctx.activeToolId,\n hotkeyStack: ctx.hotkeyStack,\n ...(allowedCapabilities ? { allowedCapabilities } : {}),\n ...(openKeymap ? { openKeymap } : {}),\n });\n const view = ctx.viewId ?? null;\n const live = (b: GestureBinding): boolean => liveInView(b, view) && liveForKeys(b, ctx.keyReach);\n const overrides = ctx.bindingOverrides?.() ?? NO_OVERRIDES;\n const result: ScopedBinding[] = scopeBindings(ordered, state, overrides)\n .filter((sb) => live(sb.binding));\n if (ctx.keymapPass === 'only') return result.filter((sb) => sb.ownerId === openKeymap);\n\n // Actions have no owning tool — `'&'`-channel phase atoms on their\n // bindings won't match.\n for (const action of ctx.actions.list()) {\n const targetScope: BindingScope = action.scope === 'hotkey' ? 'hotkey' : 'ambient';\n // The registry has already laid binding overrides over an action's own.\n for (const binding of actionBindings(action)) {\n if (live(binding)) result.push({ binding, scope: targetScope, ownerId: null });\n }\n }\n\n return result;\n}\n\n/** Whether any live binding's spec passes `test`. Asks no `enabled`, and needs\n * no event, so nothing is hit-tested to answer it. */\nexport function anyBinding(ctx: DispatcherContext, test: (spec: GestureBinding['spec']) => boolean): boolean {\n return assembleScopedBindings(ctx).some((sb) => test(sb.binding.spec));\n}\n\nfunction buildActionMap(registry: ActionSource): Map<string, Action> {\n const map = new Map<string, Action>();\n for (const action of registry.list()) {\n map.set(action.id, action);\n }\n return map;\n}\n\n/**\n * Match, filter, and order `event`'s candidates. `engaged` is the ids of the\n * entries that own a gesture in flight, which the matcher's phase atoms read.\n */\nexport function rank(\n event: InputEvent,\n ctx: DispatcherContext,\n engaged: ReadonlySet<string>,\n collectBarred: boolean,\n): Ranking {\n const view = ctx.viewId ?? null;\n const outcome = matchSortedWithBarred(\n event, assembleScopedBindings(ctx), ctx.isMac, engaged, { collectBarred },\n );\n const sorted = preferViewScoped(outcome.matches, view);\n const actionMap = buildActionMap(ctx.actions);\n const ruleCtx = ruleCtxOf(ctx);\n // Asked from the ranking, the filter and the record; a rule runs once per input.\n const held = new Map<Action, boolean>();\n const holds = (a: Action): boolean => {\n if (ruleCtx === undefined) return true;\n let h = held.get(a);\n if (h === undefined) held.set(a, h = isEligible(a, ruleCtx));\n return h;\n };\n // Ranking the ineligible alongside the rest leaves the survivors in the\n // order ranking them alone would: `preferContextual` only reorders within\n // a run of ties, and every tie's members sit together.\n const ordered = ruleCtx\n ? preferContextual(sorted, (id) => actionMap.get(id), holds, view)\n : sorted;\n return {\n ordered,\n barred: outcome.barred,\n ...(outcome.claimOwner !== undefined ? { claimOwner: outcome.claimOwner } : {}),\n actionMap,\n ruleCtx,\n eligible: (m) => {\n const a = actionMap.get(m.binding.actionId);\n return a === undefined || holds(a);\n },\n };\n}\n\n/**\n * Walk the ranked survivors, asking each action's `enabled()` in turn. With\n * `attempt`, the first that passes is run and the walk ends unless it bails;\n * without, it is the predicted winner. Each action is asked at most once.\n */\nexport function walk(\n r: Ranking,\n event: InputEvent,\n ctx: DispatcherContext,\n attempt: Attempt | null,\n evaluateShadowed: boolean,\n): Walked {\n const steps: Walked['steps'] = [];\n const tried = new Set<string>();\n let stop: Walked['stop'] = 'exhausted';\n let winner: Walked['winner'] = null;\n for (const match of r.ordered) {\n if (!r.eligible(match)) continue;\n const push = (step: WalkStep): void => { steps.push({ match, step }); };\n const actionId = match.binding.actionId;\n if (tried.has(actionId)) { push({ kind: 'duplicate' }); continue; }\n if (stop !== 'exhausted' && !evaluateShadowed) { push({ kind: 'not-asked' }); continue; }\n tried.add(actionId);\n const action = r.actionMap.get(actionId);\n if (!action) {\n if (attempt) {\n console.warn(\n `weasel dispatcher: binding resolved actionId \"${actionId}\" which has `\n + `no registered action. Skipping. (misconfiguration)`,\n );\n }\n push({ kind: 'no-such-action' });\n continue;\n }\n // Deps are built before the gate so predicates can read them; the\n // winner's invoke reuses the same bag. Shared with\n // `ActionsRegistry.trigger`, including the dev undeclared-read guard.\n const deps = buildDepsFromRequires(action, ctx.depRegistry);\n const enabled = action.enabled ? action.enabled(deps, worldPointOf(event), carriedBy(event)) : true;\n if (enabled !== true) { push({ kind: 'declined', reason: String(enabled) }); continue; }\n if (stop !== 'exhausted') { push({ kind: 'outranked' }); continue; }\n if (!attempt) {\n push({ kind: 'would-fire' });\n stop = 'fired';\n winner = { match, action };\n continue;\n }\n const result = attempt(match, action, deps);\n if (result === 'empty-handle') { push({ kind: 'empty-handle' }); continue; }\n push({ kind: result === 'fired' ? 'fired' : 'misbound' });\n stop = result;\n winner = { match, action };\n }\n return { steps, stop, winner };\n}\n\n/** Every ranked candidate of a predicting walk, with why it would or would not fire. */\nexport function verdictsOf(r: Ranking, walked: Walked, evaluateShadowed: boolean): ResolvedCandidate[] {\n const stepOf = new Map(walked.steps.map((s) => [s.match, s.step]));\n // Verdict per action id, so a second binding for an action already judged\n // higher up inherits that verdict — the walk asks each action once.\n const verdictByAction = new Map<string, ResolvedCandidate['verdict']>();\n let fired = false;\n const out: ResolvedCandidate[] = [];\n for (const match of r.ordered) {\n const actionId = match.binding.actionId;\n const action = r.actionMap.get(actionId);\n // A binding pointing at an unregistered action can never fire.\n if (!action) continue;\n\n let verdict = verdictByAction.get(actionId);\n if (verdict === undefined) {\n if (!r.eligible(match)) {\n verdict = fired && !evaluateShadowed\n ? { kind: 'shadowed' }\n : { kind: 'ineligible', reason: describeEligible(action.eligible!) };\n } else {\n const step = stepOf.get(match);\n if (step?.kind === 'would-fire') {\n verdict = { kind: 'would-fire' };\n fired = true;\n } else if (step?.kind === 'declined') {\n verdict = { kind: 'disabled', reason: step.reason };\n } else {\n verdict = { kind: 'shadowed' };\n }\n }\n verdictByAction.set(actionId, verdict);\n } else if (verdict.kind === 'would-fire') {\n // The action already won on an earlier binding; this one never runs.\n verdict = { kind: 'shadowed' };\n }\n\n out.push({\n actionId,\n action,\n binding: match.binding,\n scope: match.scope,\n ownerId: match.ownerId,\n specificity: specificity(match.binding.spec),\n verdict,\n });\n }\n return out;\n}\n","/**\n * Prediction without invocation: what an input would do, asked of the same\n * ranking and walk a real dispatch takes. `engaged` is the ids of the entries\n * that own a gesture in flight.\n */\nimport type { GestureBinding } from '../actions/binding';\nimport { resolveParams } from '../actions/invoker';\nimport { buildDispatchRecord } from './buildDispatchRecord';\nimport type { DispatcherContext, ResolveAllOptions, ResolveOnlyResult, ResolvedCandidate } from './dispatcherApi';\nimport type { DispatchRecord } from './dispatchRecord';\nimport type { InputEvent } from './matcher';\nimport { rank, verdictsOf, walk } from './walk';\n\nexport function resolveAll(\n event: InputEvent,\n ctx: DispatcherContext,\n engaged: ReadonlySet<string>,\n opts?: ResolveAllOptions,\n): ResolvedCandidate[] {\n const evaluateShadowed = opts?.evaluateShadowed ?? false;\n const r = rank(event, ctx, engaged, false);\n if (r.ordered.length === 0) return [];\n return verdictsOf(r, walk(r, event, ctx, null, evaluateShadowed), evaluateShadowed);\n}\n\nexport function resolveOnly(\n event: InputEvent,\n ctx: DispatcherContext,\n engaged: ReadonlySet<string>,\n): ResolveOnlyResult | null {\n const r = rank(event, ctx, engaged, false);\n const { winner } = walk(r, event, ctx, null, false);\n if (!winner) return null;\n return {\n actionId: winner.action.id,\n action: winner.action,\n scope: winner.match.scope,\n ownerId: winner.match.ownerId,\n ...paramsOf(winner.match.binding),\n };\n}\n\nfunction paramsOf(binding: GestureBinding): { params?: Record<string, unknown> } {\n const params = resolveParams(binding.opts?.params);\n return params ? { params } : {};\n}\n\nexport function explain(\n event: InputEvent,\n ctx: DispatcherContext,\n engaged: ReadonlySet<string>,\n opts?: ResolveAllOptions,\n): DispatchRecord {\n const r = rank(event, ctx, engaged, true);\n const walked = walk(r, event, ctx, null, opts?.evaluateShadowed ?? false);\n return buildDispatchRecord(r, walked, event, ctx, true, walked.winner ? 'handled' : 'unhandled');\n}\n","/**\n * How an input that starts no gesture of its own is routed while a keymap is\n * open: the innermost keymap's bindings alone first, then — depending on what\n * the input is and what the keymap's `unbound` rule says — nothing, or every\n * binding but the keymap's.\n */\nimport type { InputEvent } from './matcher';\nimport type { DispatcherContext } from './dispatcherApi';\nimport { capabilitiesAllowed, type CapabilityTag } from '@weasel-js/modes';\nimport { liveScope } from '../../contributions/eligibility';\n\ntype Outcome = 'handled' | 'unhandled';\n\n/** What the router asks of the dispatcher. */\nexport interface KeymapPasses {\n /** Run `ctx` with `keymapPass` set to `pass`. */\n run(pass: 'only' | 'none', event: InputEvent): Outcome;\n /** Whether any binding of the innermost keymap matches `event`, without running one. */\n binds(event: InputEvent): boolean;\n}\n\nconst MODIFIER_KEYS: ReadonlySet<string> = new Set(['Shift', 'Control', 'Alt', 'Meta', 'AltGraph', 'CapsLock']);\n\n/** Pointer input the recognizer has resolved a press into: the next stroke. */\nconst STROKES: ReadonlySet<InputEvent['kind']> = new Set([\n 'click', 'doubleclick', 'longpress', 'contextmenu', 'multitouch', 'multitouchtap',\n] as const);\n\nconst isPlainEscape = (e: InputEvent): boolean =>\n e.kind === 'key' && e.key === 'Escape' && !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey;\n\n/** What a press may yet become, and a keymap may bind, once the recognizer settles it. */\nconst SETTLES_INTO: readonly InputEvent['kind'][] = ['click', 'doubleclick', 'longpress', 'contextmenu'];\n\n/** Whether the keymap `id` names is still installed and allowed by the active mode. */\nfunction stillLive(id: string, ctx: DispatcherContext): boolean {\n const entry = ctx.entriesById.get(id);\n if (!entry) return false;\n const allowed = ctx.getRuleCtx?.()?.allowedCapabilities;\n const allows = allowed ? (tags: readonly CapabilityTag[]) => capabilitiesAllowed(allowed, tags) : undefined;\n return liveScope(id, entry.eligibility, { focusedId: null, openKeymap: id, ...(allows ? { allows } : {}) }) !== null;\n}\n\n/** Route `event` through the open keymaps, or `undefined` when none is open. */\nexport function routeThroughKeymap(\n event: InputEvent,\n ctx: DispatcherContext,\n passes: KeymapPasses,\n): Outcome | undefined {\n const stack = ctx.keymaps;\n const open = stack?.innermost();\n if (!stack || !open || event.kind === 'hover') return undefined;\n const isKey = event.kind === 'key' || event.kind === 'key-held';\n // A key this surface hears only because the pointer is over it belongs to whoever holds the keys.\n if (isKey && ctx.keyReach && !ctx.keyReach.held) return undefined;\n if (!stillLive(open.id, ctx)) {\n stack.closeAll();\n return undefined;\n }\n\n // The other half of a keystroke the keymap already ruled on.\n const verdict = stack.verdict();\n if (verdict === 'taken') return 'unhandled';\n if (verdict === 'cascaded') return passes.run('none', event);\n\n if (isPlainEscape(event)) {\n stack.closeInnermost();\n return 'handled';\n }\n\n if (passes.run('only', event) === 'handled') {\n stack.inputSeen();\n return 'handled';\n }\n\n if (isKey) {\n // A keymap that binds only the held form takes the keystroke on its twin.\n if (event.kind === 'key' && passes.binds({ ...event, kind: 'key-held', phase: 'down' })) return 'unhandled';\n // A bare modifier, a Ctrl or Cmd chord, and Tab go on as usual and close nothing:\n // a keymap is no reason to lose copy, paste or focus.\n if (MODIFIER_KEYS.has(event.key) || event.ctrlKey || event.metaKey || event.key === 'Tab') {\n return passes.run('none', event);\n }\n const entry = ctx.entriesById.get(open.id)?.eligibility.keymap;\n const own = typeof entry === 'object' ? entry.unbound : undefined;\n if ((own ?? ctx.leaderUnbound ?? 'modal') === 'modal') {\n stack.swallowed();\n return 'handled';\n }\n stack.cascaded();\n return passes.run('none', event);\n }\n\n // A press the keymap may yet take as a click is kept from the drag a tool would start on it.\n if (event.kind === 'pointerdown' && SETTLES_INTO.some((kind) => passes.binds({ ...event, kind } as InputEvent))) {\n return 'unhandled';\n }\n\n const outcome = passes.run('none', event);\n const stroke = STROKES.has(event.kind) || (event.kind === 'pointerdown' && outcome === 'handled');\n // A click the keymap passes on may be the first of a double click it binds.\n const firstOfDouble = event.kind === 'click' && passes.binds({ ...event, kind: 'doubleclick' } as InputEvent);\n if (stroke && !firstOfDouble) stack.inputSeen();\n return outcome;\n}\n","/**\n * Dispatcher orchestrator — pure module, no React, no DOM.\n *\n * ## Precedence and fall-through\n * An exclusive affordance claim first bars every binding that does not\n * consult the affordance. The rest are ranked, best first, by:\n * 1. bindings naming the routed view ahead of every other\n * (`preferViewScoped`);\n * 2. scope tier: hotkey > active > ambient;\n * 3. specificity within a tier (`specificity()` in `matcher.ts`);\n * 4. an action gated by an `eligible` rule that holds now ahead of one with\n * no rule (`preferContextual`) — Escape while editing a path exits the\n * edit rather than resetting the tool;\n * 5. registration order.\n * Candidates whose `eligible` rule is false are dropped first. The dispatcher\n * walks the rest and fires the first action whose `enabled()` returns\n * `true`. If every candidate's `enabled()` returns a disabled reason, the\n * event is unhandled.\n *\n * ## Action-lookup miss behavior\n * When the walk reaches a binding whose `actionId` has no entry in\n * `ctx.actions.list()`, the dispatcher emits `console.warn` and returns\n * `'unhandled'`, so the gesture falls through as if unmatched.\n */\n\nimport { createEmitter } from '@weasel-js/registry';\nimport type { Action } from '../actions/action';\nimport type { InputEvent } from './matcher';\nimport { buildDispatchRecord } from './buildDispatchRecord';\nimport { createGestureFacts } from './gestureFacts';\nimport { endAllGestures, invokeAction, pumpGesture, type GestureRun } from './gestureRun';\nimport { createInFlightGestures } from './inFlightGestures';\nimport { createUiOngoing } from './uiOngoing';\nimport { explain, resolveAll, resolveOnly } from './predict';\nimport { rank, walk, type Attempt } from './walk';\nimport { routeThroughKeymap } from './keymapRoute';\n\nimport type { Dispatcher, DispatcherContext } from './dispatcherApi';\n\nexport type {\n Dispatcher, DispatcherContext, KeyReach, ResolveAllOptions, ResolveOnlyResult, ResolvedCandidate, UiOngoingControl,\n} from './dispatcherApi';\nexport { createDispatchTrace, createTraceRing } from './dispatchTrace';\nexport type { DispatchTrace, ModeSwitchLogEntry, TraceLogEntry, TraceRing } from './dispatchTrace';\nexport { multiTouchGestureId, pointerGestureId } from './gestureIds';\nexport { filterEligible, preferContextual } from './ranking';\n\n/** Build a dispatcher. `getAction` overrides how action ids are resolved;\n * by default the `DispatcherContext`'s registry is used. */\nexport function createDispatcher(opts?: {\n getAction?: (id: string) => Action | undefined;\n}): Dispatcher {\n const inFlight = createInFlightGestures();\n const facts = createGestureFacts();\n\n /** Subscribers fired after every state mutation. Layers that read from\n * `getInFlightHandles()` use this to know when to re-render. */\n const changed = createEmitter();\n /** Bumped before the callbacks run, so a subscriber that re-reads\n * `getVersion()` synchronously inside its callback already sees the new\n * value (what `useSyncExternalStore` does). */\n let version = 0;\n function notify(): void {\n version++;\n changed.emit();\n }\n\n const uiOngoing = createUiOngoing(inFlight, notify, opts?.getAction);\n\n // The view the input being handled landed in. Set per `handleInput`, so a\n // pump of an in-flight gesture reports the view it is pinned to.\n let routedView: string | null | undefined;\n let routedIsMac = false;\n\n const run: GestureRun = { inFlight, facts, viewId: () => routedView, isMac: () => routedIsMac };\n const invoking = (event: InputEvent): Attempt =>\n (match, action, deps) => invokeAction(run, event, match, action, deps);\n\n function handleInput(event: InputEvent, ctx: DispatcherContext): 'handled' | 'unhandled' {\n routedView = ctx.viewId;\n routedIsMac = ctx.isMac;\n const pumped = pumpGesture(run, event);\n if (pumped !== undefined) return pumped;\n\n if (event.kind === 'hover') return hover(event, ctx);\n\n return routeThroughKeymap(event, ctx, {\n run: (pass, ev) => route(ev, { ...ctx, keymapPass: pass }),\n binds: (ev) => rank(ev, { ...ctx, keymapPass: 'only' }, inFlight.engagedOwners(), false).ordered.length > 0,\n }) ?? route(event, ctx);\n }\n\n /** Rank and walk an input no gesture in flight took. */\n function route(event: InputEvent, ctx: DispatcherContext): 'handled' | 'unhandled' {\n const trace = ctx.trace?.recording() ? ctx.trace : null;\n const r = rank(event, ctx, inFlight.engagedOwners(), trace !== null);\n const walked = walk(r, event, ctx, invoking(event), false);\n const outcome: 'handled' | 'unhandled' = walked.stop === 'fired' ? 'handled' : 'unhandled';\n trace?.push(buildDispatchRecord(r, walked, event, ctx, false, outcome));\n return outcome;\n }\n\n /** A hover claims nothing, so the walk goes on past each binding it fires.\n * Untraced: one arrives per mouse event. */\n function hover(event: InputEvent, ctx: DispatcherContext): 'handled' | 'unhandled' {\n let fired = false;\n const invoke = invoking(event);\n walk(rank(event, ctx, inFlight.engagedOwners(), false), event, ctx, (match, action, deps) => {\n if (invoke(match, action, deps) === 'fired') fired = true;\n return 'empty-handle';\n }, false);\n return fired ? 'handled' : 'unhandled';\n }\n\n function cancelAll(reason: 'commit' | 'cancel'): void {\n uiOngoing.clear();\n endAllGestures(run, reason);\n }\n\n // Wrap handleInput + cancelAll to notify once per invocation that found or\n // left a gesture in flight. Done at the boundary (not inside the match\n // loop) so a start, a pump, and an end each fire exactly one notify. An\n // event with nothing in flight on either side changed nothing a subscriber\n // reads, and hover sends one per mouse move.\n const handleInputWithNotify: typeof handleInput = (event, ctx) => {\n const before = inFlight.handles.size;\n try {\n return handleInput(event, ctx);\n } finally {\n if (before > 0 || inFlight.handles.size > 0) notify();\n }\n };\n const cancelAllWithNotify: typeof cancelAll = (reason) => {\n const before = inFlight.handles.size;\n try {\n cancelAll(reason);\n } finally {\n if (before > 0) notify();\n }\n };\n\n return {\n handleInput: handleInputWithNotify,\n resolveOnly: (event, ctx) => resolveOnly(event, ctx, inFlight.engagedOwners()),\n resolveAll: (event, ctx, resolveOpts) => resolveAll(event, ctx, inFlight.engagedOwners(), resolveOpts),\n explain: (event, ctx, explainOpts) => explain(event, ctx, inFlight.engagedOwners(), explainOpts),\n cancelAll: cancelAllWithNotify,\n inFlight: () => inFlight.handles,\n inFlightCursor: inFlight.cursor,\n getInFlightHandles: () => inFlight.handles.values(),\n subscribe: changed.subscribe,\n getVersion: () => version,\n getActiveAction: inFlight.latest,\n beginUiOngoing: uiOngoing.begin,\n };\n}\n","/**\n * The long-press the gesture dispatcher is timing, as observable state: where\n * the press landed, when the hold started, how far through it is, and whether\n * any binding would fire on it. Feedback — a filling ring, a haptic — reads\n * this; nothing here decides what the feedback looks like.\n */\nimport { createEmitter } from '@weasel-js/registry';\nimport { LONG_PRESS_MS } from '@weasel-js/gestures';\n\n/** A press being held toward a long-press. */\nexport interface PendingLongPress {\n pointerId: number;\n /** Long-press is synthesized for these two only; a mouse never arms one. */\n pointerType: 'touch' | 'pen';\n /** Where the press landed, in client coordinates. */\n client: { x: number; y: number };\n /** The same point in CSS pixels from the canvas element's top-left — what a\n * `space: 'screen'` layer draws in. */\n local: { x: number; y: number };\n /** The same point in the routed view's world coordinates. */\n world: { x: number; y: number };\n /** The view the press routed to; `null` is the root view. */\n viewId: string | null;\n /** `performance.now()` when the hold started. */\n startedAt: number;\n /** How long the hold must last before the long-press fires, in ms. */\n duration: number;\n /**\n * Whether holding to the end would fire anything — a `longPress` binding,\n * or a `contextMenu` binding through the fallback. Resolved at press time.\n * Feedback shows only when this is true: a press that will do nothing must\n * not promise that it will.\n */\n armed: boolean;\n}\n\n/** Read side of the pending long-press. Published as the `longPress` dep. */\nexport interface LongPressState {\n /** The press being held, or `null` when none is. Cleared when the\n * long-press fires, and when movement, release, cancel or a second\n * pointer abandons it. */\n get(): PendingLongPress | null;\n /** How far through the hold the pending press is, 0→1, at `now`\n * (`performance.now()` by default). 0 when nothing is pending. */\n progress(now?: number): number;\n /** Called whenever {@link get} changes. Progress is derived from the\n * clock, so it does not notify — a loop drawing it asks for frames. */\n subscribe(fn: () => void): () => void;\n}\n\n/** The dispatcher's writable half of {@link LongPressState}. */\nexport interface LongPressStore extends LongPressState {\n set(next: PendingLongPress | null): void;\n}\n\nexport { LONG_PRESS_MS };\n\n/** How long a handled long-press vibrates for, in ms. */\nexport const LONG_PRESS_HAPTIC_MS = 15;\n\n/** How `useGestureDispatcher` times, publishes and signals a long-press. */\nexport interface LongPressOptions {\n /** Hold time in ms. Default {@link LONG_PRESS_MS}. */\n duration?: number;\n /**\n * Where the press being held is published: position, start time, progress,\n * and whether any binding would fire on it. `<SceneCanvas>` passes one and\n * republishes it as the `longPress` dep, which its default press ring\n * reads. Omit it and nothing is published.\n */\n state?: LongPressStore;\n /**\n * Default true. A long-press some binding handled pulses `navigator.vibrate`\n * briefly, for touch and pen pointers, where the API exists.\n */\n haptics?: boolean;\n}\n\nconst nowMs = (): number =>\n typeof performance !== 'undefined' ? performance.now() : Date.now();\n\n/** A store holding the press currently being held, or none. Pass it as `LongPressOptions.state`. */\nexport function createLongPressStore(): LongPressStore {\n let current: PendingLongPress | null = null;\n const changed = createEmitter();\n return {\n get: () => current,\n progress: (now = nowMs()) => {\n if (!current) return 0;\n if (!(current.duration > 0)) return 1;\n const t = (now - current.startedAt) / current.duration;\n return t <= 0 ? 0 : t >= 1 ? 1 : t;\n },\n subscribe: changed.subscribe,\n set: (next) => {\n if (next === current) return;\n current = next;\n changed.emit();\n },\n };\n}\n","/**\n * The DOM half of a drag: one pointer, held down, from press to release.\n *\n * Every pointerdown-to-pointerup lifecycle in the kit used to answer capture,\n * pointer identity, teardown and lost-pointer recovery for itself, and each\n * answered them differently. This is the one place those are decided; anything\n * above it — thresholds, coordinate spaces, what the drag *means* — belongs to\n * its caller.\n */\n\n/** The DOM event that says capture went away mid-gesture. */\nconst LOST_CAPTURE_EVENT = 'lostpointercapture';\n\n/**\n * Does the press report button state at all?\n *\n * Synthesized events routinely carry `buttons: 0`, or nothing. Reading a\n * missed release out of those would end every such drag on its first move, so\n * a press that reports no buttons disarms {@link isMissedRelease} entirely.\n */\nfunction reportsButtons(down: { buttons?: number }): boolean {\n return !!down.buttons;\n}\n\n/**\n * A move with nothing held is the release the document never saw — the pointer\n * came up over another window, a native drag, or an element that swallowed it.\n * Only ask this when {@link reportsButtons} was true for the press.\n */\nfunction isMissedRelease(move: { buttons?: number }): boolean {\n return move.buttons === 0;\n}\n\n/** Why a session ended without the pointer being released. */\nexport type PointerSessionCancelReason =\n /** The browser cancelled the pointer (touch interrupted, palm rejection). */\n | 'pointercancel'\n /** The origin left the document mid-gesture, taking capture with it. */\n | 'lostcapture'\n /** `cancel()` — an unmount, a window blur, Escape, a consumer's own rule. */\n | 'aborted'\n /** A new press arrived on this pointer, so the tracked one had ended. */\n | 'superseded';\n\n/** What {@link openPointerSession} reports. Exactly one of `onEnd` / `onCancel` fires when the session ends. */\nexport interface PointerSessionCallbacks {\n /** Every move belonging to this pointer, while it is still held. */\n onMove?: (e: PointerEvent) => void;\n /** The pointer was released. Fires once, before teardown completes. */\n onEnd?: (e: PointerEvent) => void;\n /** The session ended without a release. Fires once. */\n onCancel?: (reason: PointerSessionCancelReason) => void;\n}\n\n/** Options for {@link openPointerSession}. */\nexport interface PointerSessionOptions {\n /** Ask the origin element to capture the pointer. Default `true`. Capture\n * keeps hover and click off everything the drag passes over; the session\n * does not depend on it to keep receiving events. */\n capture?: boolean;\n}\n\n/** A live drag opened by {@link openPointerSession}. */\nexport interface PointerSession {\n /** The pointer this session follows, taken from the press. */\n readonly pointerId: number;\n /** False once the session has ended, by any route. */\n readonly active: boolean;\n /** End the session now, reporting `'aborted'`. Idempotent. */\n cancel: () => void;\n}\n\n/**\n * Open a session for the pointer that `down` belongs to.\n *\n * Listens on the origin's document rather than on the element: a captured\n * element that is removed mid-drag stops receiving events, and every listener\n * hung on it goes with it. Three recovery rules close the gaps a plain\n * pointerup/pointercancel pair leaves — losing capture cancels only once the\n * origin has left the document, a move reporting no held button is read as\n * the release that never arrived, and a fresh press on the same pointer says\n * the tracked one had already ended.\n */\nexport function openPointerSession(\n origin: Element,\n down: PointerEvent | React.PointerEvent,\n cb: PointerSessionCallbacks,\n opts: PointerSessionOptions = {},\n): PointerSession {\n const pointerId = down.pointerId;\n const doc = origin.ownerDocument ?? document;\n const buttonsReported = reportsButtons(down);\n let active = true;\n\n const teardown = () => {\n active = false;\n doc.removeEventListener('pointermove', onMove, true);\n doc.removeEventListener('pointerup', onUp, true);\n doc.removeEventListener('pointercancel', onPointerCancel, true);\n doc.removeEventListener('pointerdown', onRepress, true);\n origin.removeEventListener(LOST_CAPTURE_EVENT, onLostCapture);\n if (opts.capture !== false) {\n try { origin.releasePointerCapture?.(pointerId); } catch { /* already gone */ }\n }\n };\n\n const mine = (e: PointerEvent) => e.pointerId === pointerId;\n\n const end = (e: PointerEvent) => {\n if (!active) return;\n teardown();\n cb.onEnd?.(e);\n };\n\n const abort = (reason: PointerSessionCancelReason) => {\n if (!active) return;\n teardown();\n cb.onCancel?.(reason);\n };\n\n function onMove(e: PointerEvent) {\n if (!active || !mine(e)) return;\n if (buttonsReported && isMissedRelease(e)) { end(e); return; }\n cb.onMove?.(e);\n }\n function onUp(e: PointerEvent) {\n if (mine(e)) end(e);\n }\n function onPointerCancel(e: PointerEvent) {\n if (mine(e)) abort('pointercancel');\n }\n // A press on a pointer we still believe is held: the release landed\n // somewhere that never told us, and where it ended is unknown — so this\n // cancels rather than ending at the new press's coordinates.\n function onRepress(e: PointerEvent) {\n if (mine(e)) abort('superseded');\n }\n // Losing capture only ends the gesture when the origin is gone, because\n // then nothing more is coming. While it is still in the document the\n // session keeps tracking: it listens there, not on the origin, so it needs\n // capture for retargeting and not for delivery. Chrome releases capture\n // implicitly a beat *before* it delivers `pointerup`, so cancelling here\n // unconditionally threw away releases that had already been dispatched.\n function onLostCapture(e: Event) {\n if ((e as PointerEvent).pointerId !== pointerId) return;\n if (!origin.isConnected) abort('lostcapture');\n }\n\n if (opts.capture !== false) {\n // Best-effort: a detached element throws, and jsdom's implementation\n // records the call and does nothing. Neither is a reason to fail the drag.\n try { origin.setPointerCapture?.(pointerId); } catch { /* uncaptured is fine */ }\n }\n // Capture phase, so a consumer's own stopPropagation cannot strand a session.\n doc.addEventListener('pointermove', onMove, true);\n doc.addEventListener('pointerup', onUp, true);\n doc.addEventListener('pointercancel', onPointerCancel, true);\n doc.addEventListener('pointerdown', onRepress, true);\n origin.addEventListener(LOST_CAPTURE_EVENT, onLostCapture);\n\n return {\n pointerId,\n get active() { return active; },\n cancel: () => abort('aborted'),\n };\n}\n","/**\n * A press that begins on one element and is carried over another: the in-app\n * sibling of an OS drag. The source opens the carry; every dispatcher with a\n * `carry` channel registers its element as a surface, and the one under the\n * pointer dispatches the carry as `carry` events through its bindings.\n */\nimport {\n openPointerSession,\n type PointerSessionCancelReason,\n} from '../pointerSession';\n\n/** What a carry brings. `type` is what a `carry` spec's `types` globs filter. */\nexport interface CarryPayload {\n type: string;\n value: unknown;\n}\n\n/** The pointer facts a surface reads off each step of a carry. */\nexport interface CarryPointer {\n clientX: number;\n clientY: number;\n altKey: boolean;\n ctrlKey: boolean;\n metaKey: boolean;\n shiftKey: boolean;\n}\n\n/** What a carry did on a surface: came over it, moved on it, was released on\n * it, or left it — off it, or canceled while over it. */\nexport type CarryStage = 'enter' | 'move' | 'drop' | 'leave';\n\n/** An element a carry can be released on. */\nexport interface CarrySurface {\n element: Element;\n receive(\n stage: CarryStage,\n payload: CarryPayload,\n at: CarryPointer,\n pointerId: number,\n ): 'handled' | 'unhandled';\n}\n\n/** What {@link startCarry} reports to its source. Exactly one of `onEnd` /\n * `onCancel` fires. */\nexport interface CarryCallbacks {\n /** Every move of the carrying pointer. */\n onMove?: (e: PointerEvent) => void;\n /** The pointer was released. `taken` is whether a binding on the surface\n * under it took the carry. */\n onEnd?: (result: { taken: boolean; event: PointerEvent }) => void;\n /** The carry ended without a release. Any surface it was over has had its leave. */\n onCancel?: (reason: PointerSessionCancelReason) => void;\n}\n\n/** A live carry, opened by {@link startCarry}. */\nexport interface Carry {\n readonly pointerId: number;\n readonly active: boolean;\n /** End the carry now, as a cancel. Idempotent. */\n cancel(): void;\n}\n\nconst surfaces = new Set<CarrySurface>();\n\n/** Register `surface`; the returned function removes it. */\nexport function addCarrySurface(surface: CarrySurface): () => void {\n surfaces.add(surface);\n return () => {\n surfaces.delete(surface);\n };\n}\n\nfunction contains(r: DOMRect, x: number, y: number): boolean {\n return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom;\n}\n\n/** The innermost surface under the point that nothing else on the page covers. */\nfunction surfaceAt(doc: Document, x: number, y: number): CarrySurface | null {\n const hit = typeof doc.elementFromPoint === 'function' ? doc.elementFromPoint(x, y) : null;\n let best: CarrySurface | null = null;\n for (const s of surfaces) {\n if (!contains(s.element.getBoundingClientRect(), x, y)) continue;\n if (hit && !s.element.contains(hit)) continue;\n if (best && s.element.contains(best.element)) continue;\n best = s;\n }\n return best;\n}\n\n/**\n * Carry `payload` from the press `down` on `origin` until the pointer is\n * released or the press is canceled. While it moves, the surface under it\n * hears the carry come over, move, and leave; a release over one is a drop\n * there. The press is captured to `origin` as any drag is, so nothing the\n * pointer passes over sees it as a press of its own.\n */\nexport function startCarry(\n origin: Element,\n down: PointerEvent | React.PointerEvent,\n payload: CarryPayload,\n cb: CarryCallbacks = {},\n): Carry {\n const doc = origin.ownerDocument ?? document;\n const pointerId = down.pointerId;\n let over: CarrySurface | null = null;\n\n const leave = (at: CarryPointer): void => {\n const was = over;\n over = null;\n if (was && surfaces.has(was)) was.receive('leave', payload, at, pointerId);\n };\n\n const step = (at: CarryPointer): void => {\n const next = surfaceAt(doc, at.clientX, at.clientY);\n if (next === over) {\n over?.receive('move', payload, at, pointerId);\n return;\n }\n leave(at);\n over = next;\n next?.receive('enter', payload, at, pointerId);\n };\n\n let last: CarryPointer = down;\n const session = openPointerSession(origin, down, {\n onMove: (e) => {\n last = e;\n step(e);\n cb.onMove?.(e);\n },\n onEnd: (e) => {\n step(e);\n const on = over;\n over = null;\n const taken = on !== null && surfaces.has(on) && on.receive('drop', payload, e, pointerId) === 'handled';\n cb.onEnd?.({ taken, event: e });\n },\n onCancel: (reason) => {\n leave(last);\n cb.onCancel?.(reason);\n },\n });\n\n return {\n pointerId,\n get active() {\n return session.active;\n },\n cancel: () => session.cancel(),\n };\n}\n","/**\n * The keymaps open on one surface, innermost last. A level opened by a held\n * leader stays open until that leader comes up; any other closes on the next\n * input. Closes made during one raw input apply when it ends, so the `key` and\n * `key-held` forms of a keystroke both see the keymap they arrived to.\n */\nimport { createEmitter } from '@weasel-js/registry';\nimport type { GestureBinding } from '../interactions/actions/binding';\n\n/** What a key no open keymap binds does: `'modal'` swallows it and leaves the\n * keymap open; `'cascade'` closes the keymap and dispatches it as if none were. */\nexport type KeymapUnbound = 'modal' | 'cascade';\n\n/** What holds a level opened with `{ hold: true }` open: no key releases it, so it closes on Escape. */\nexport const KEYMAP_HOLD = 'hold';\n\n/** One open level of a {@link KeymapStack}. */\nexport interface OpenKeymap {\n readonly id: string;\n readonly label: string;\n /** The keymap's bindings as declared, for a hint to list. */\n readonly bindings: readonly GestureBinding[];\n /** The gesture id of the leader holding this level open, while it is held,\n * or {@link KEYMAP_HOLD}. */\n readonly heldBy?: string;\n /** Whether input arrived while the leader was held, so its release closes the level. */\n readonly usedWhileHeld: boolean;\n}\n\n/** What the keymaps made of the raw input in progress: `'taken'` when one of\n * them handled it, `'cascaded'` when it went on past them, `null` before either. */\nexport type KeymapVerdict = 'taken' | 'cascaded' | null;\n\n/** The keymaps open on one surface, innermost last; a canvas's `keymaps` dep. */\nexport interface KeymapStack {\n /** Every open level, outermost first. */\n open(): readonly OpenKeymap[];\n innermost(): OpenKeymap | null;\n /** Open a level. `heldBy` names what holds it open; `bindings` are what a hint lists. */\n push(id: string, label: string, opts?: { heldBy?: string; bindings?: readonly GestureBinding[] }): void;\n /** Mark the levels the last raw input opened as held by `heldBy`: the key\n * that opened them is still down. False when it opened none. */\n holdOpened(heldBy: string): boolean;\n /** The leader `heldBy` came up: close its level, those above it and the\n * tapped ones beneath it if input arrived meanwhile, else leave it open\n * for one more input. */\n release(heldBy: string): void;\n /** Close the innermost level: Escape. */\n closeInnermost(): void;\n /** One of the keymaps took this input, or a pointer gesture went past them.\n * Marks held levels used and closes once-levels down to the innermost held one. */\n inputSeen(): void;\n /** A key no keymap binds was swallowed: held levels count it as input, and nothing closes. */\n swallowed(): void;\n /** This input went on past the keymaps: as `inputSeen`, remembered as a cascade. */\n cascaded(): void;\n /** What the keymaps made of the input in progress. */\n verdict(): KeymapVerdict;\n closeAll(): void;\n /** Run `fn` as one raw input: closes made inside apply when it returns. Nests. */\n batch<T>(fn: () => T): T;\n subscribe(listener: () => void): () => void;\n getVersion(): number;\n}\n\ninterface Level {\n id: string;\n label: string;\n bindings: readonly GestureBinding[];\n heldBy?: string;\n usedWhileHeld: boolean;\n openedIn: number;\n}\n\n/** An empty {@link KeymapStack}. `useGestureDispatcher` makes one per surface. */\nexport function createKeymapStack(): KeymapStack {\n let levels: Level[] = [];\n let version = 0;\n const changed = createEmitter();\n let depth = 0;\n let serial = 0;\n let pending: (() => void)[] = [];\n let verdict: KeymapVerdict = null;\n let snapshot: readonly OpenKeymap[] = [];\n\n const notify = (): void => {\n snapshot = levels.map(({ openedIn: _, ...rest }) => Object.freeze({ ...rest }));\n version++;\n changed.emit();\n };\n const later = (op: () => void): void => {\n if (depth > 0) pending.push(op);\n else op();\n };\n\n const settle = (): void => {\n const before = levels;\n // Levels opened by this very input are exempt: the leader that opened one\n // is part of the input, not the input it was opened for.\n const opened = (l: Level) => l.openedIn === serial && depth > 0;\n if (levels.some(opened)) return;\n for (const l of levels) if (l.heldBy !== undefined) l.usedWhileHeld = true;\n while (levels.length > 0 && levels.at(-1)!.heldBy === undefined) levels = levels.slice(0, -1);\n if (levels !== before) notify();\n };\n\n return {\n open: () => snapshot,\n innermost: () => snapshot.at(-1) ?? null,\n push: (id, label, opts) => {\n const heldBy = opts?.heldBy;\n const bindings = opts?.bindings ?? [];\n // Opening a keymap that is already open starts it over rather than stacking a copy.\n const open = levels.findIndex((l) => l.id === id);\n if (open !== -1) levels = levels.slice(0, open);\n levels = [...levels, { id, label, bindings, ...(heldBy !== undefined ? { heldBy } : {}), usedWhileHeld: false, openedIn: serial }];\n if (depth > 0) verdict = 'taken';\n notify();\n },\n holdOpened: (heldBy) => {\n let held = false;\n levels = levels.map((l) => {\n if (l.openedIn !== serial || l.heldBy !== undefined) return l;\n held = true;\n return { ...l, heldBy };\n });\n if (held) notify();\n return held;\n },\n release: (heldBy) => {\n const i = levels.findIndex((l) => l.heldBy === heldBy);\n if (i === -1) return;\n const level = levels[i]!;\n if (level.usedWhileHeld) {\n // The input it was held for was the next input of the tapped levels beneath it too.\n levels = levels.slice(0, i);\n while (levels.length > 0 && levels.at(-1)!.heldBy === undefined) levels = levels.slice(0, -1);\n } else levels = levels.map((l) => (l === level ? { ...l, heldBy: undefined } : l)).map(dropUndefinedHeld);\n notify();\n },\n closeInnermost: () => {\n if (depth > 0) verdict = 'taken';\n later(() => {\n if (levels.length === 0) return;\n levels = levels.slice(0, -1);\n notify();\n });\n },\n inputSeen: () => {\n if (depth > 0) verdict ??= 'taken';\n later(settle);\n },\n cascaded: () => {\n if (depth > 0) verdict = 'cascaded';\n later(settle);\n },\n swallowed: () => {\n for (const l of levels) if (l.heldBy !== undefined) l.usedWhileHeld = true;\n },\n verdict: () => verdict,\n closeAll: () => {\n pending = [];\n if (levels.length === 0) return;\n levels = [];\n notify();\n },\n batch: (fn) => {\n if (depth === 0) { serial++; verdict = null; }\n depth++;\n try {\n return fn();\n } finally {\n depth--;\n if (depth === 0) {\n const ops = pending;\n pending = [];\n // Applied as part of this input, so a level it opened is still exempt.\n depth = 1;\n try { for (const op of ops) op(); } finally { depth = 0; }\n verdict = null;\n }\n }\n },\n subscribe: changed.subscribe,\n getVersion: () => version,\n };\n}\n\nfunction dropUndefinedHeld(l: Level): Level {\n if (l.heldBy !== undefined) return l;\n const { heldBy: _, ...rest } = l;\n return rest;\n}\n","/**\n * A keymap and the leader that opens it, from one definition. The keymap is an\n * entry whose bindings are live only while it is open; the leader is an\n * action on the hotkey tier, so it outranks what the active tool binds to the\n * same key, and it opens the keymap mid-gesture as well as between them.\n */\nimport type { GestureSpec } from '@weasel-js/gestures';\nimport { ActionDisabledReason, type Action } from '../interactions/actions/action';\nimport type { BoundGesture, GestureBinding } from '../interactions/actions/binding';\nimport type { Contribution, OverlayPosition } from '../contributions/types';\nimport { KEYMAP_HOLD, type KeymapUnbound } from './keymapStack';\n\n/** What {@link keymapContribution} builds a keymap and its leader from. */\nexport interface KeymapDef<TOverlay = never> {\n /** The keymap entry's id. Its leader action is `keymap.<id>`. */\n id: string;\n /** What the hint and a shortcut chip call it: `Loupe ▸ 2`. */\n label: string;\n /** The keystroke, or keystrokes, that open it. A `key-held` spec is read as\n * its `key` form: holding the key is what holds the keymap open. */\n leader: GestureSpec | readonly GestureSpec[];\n /** The keymap's own bindings. Escape is not one: it always closes the keymap. */\n bindings: readonly GestureBinding[];\n /** Actions the bindings name that are not registered elsewhere. */\n actions?: readonly Action[];\n /** Overrides the `gestures.keymapUnbound` kit setting for this keymap. */\n unbound?: KeymapUnbound;\n /** Drawn while the keymap is open. */\n overlay?: TOverlay | TOverlay[];\n overlayPosition?: OverlayPosition;\n}\n\n/** The leader action's id for keymap `id`. */\nexport const keymapLeaderId = (id: string): string => `keymap.${id}`;\n\n/** The binding id of a keymap's leader — what a binding override rebinds it by.\n * A second leader key is `<id>#1`, and so on. */\nexport const keymapLeaderBindingId = (id: string, index = 0): string =>\n index === 0 ? `${keymapLeaderId(id)}.leader` : `${keymapLeaderId(id)}.leader#${index}`;\n\n/** The leader keystrokes of `def` as its leader action binds them, each with its binding id. */\nexport function leaderBindings(def: Pick<KeymapDef, 'id' | 'leader'>): BoundGesture[] {\n return [def.leader].flat().map((spec, i) => ({\n spec: spec.kind === 'key-held' ? { ...spec, kind: 'key' } : spec,\n opts: { id: keymapLeaderBindingId(def.id, i) },\n }));\n}\n\nconst isPlainEscape = (spec: GestureSpec): boolean =>\n spec.kind === 'key' && [spec.key].flat().includes('Escape') && Object.values(spec.mods ?? {}).every((m) => m !== true);\n\n/** `[keymap entry, leader entry]`. Triggered without a key, the leader opens\n * its keymap tapped; `trigger('keymap.<id>', { hold: true })` holds it open\n * until Escape. Install both, with `<SceneCanvas ambient>`\n * or `useTools`'s `ambient`; the leader entry carries the actions. */\nexport function keymapContribution<TOverlay = never>(def: KeymapDef<TOverlay>): Contribution<TOverlay>[] {\n if (def.bindings.some((b) => isPlainEscape(b.spec))) {\n throw new Error(`keymap \"${def.id}\" binds Escape, which always closes a keymap`);\n }\n const open: Action = {\n id: keymapLeaderId(def.id),\n label: `Open ${def.label} keys`,\n scope: 'hotkey',\n defaultBinding: leaderBindings(def),\n requires: ['keymaps'],\n enabled: (deps) => (deps?.keymaps ? true : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'immediate',\n run: (deps, params) => {\n deps.keymaps?.push(def.id, def.label, { bindings: def.bindings, ...(params?.hold === true ? { heldBy: KEYMAP_HOLD } : {}) });\n },\n },\n };\n return [\n {\n id: def.id,\n eligibility: { keymap: def.unbound ? { unbound: def.unbound } : true },\n bindings: [...def.bindings],\n presentation: { label: def.label },\n ...(def.overlay !== undefined ? { overlay: def.overlay } : {}),\n ...(def.overlayPosition ? { overlayPosition: def.overlayPosition } : {}),\n },\n {\n id: `${def.id}.leader`,\n eligibility: { always: true },\n actions: [open, ...(def.actions ?? [])],\n },\n ];\n}\n","/**\n * What a hint, a menu or a binding list shows for a keymap: its rows, Escape\n * first, and each key's path through the leaders that reach it.\n */\nimport { formatShortcut, type GestureSpec } from '@weasel-js/gestures';\nimport type { MenuShortcut } from '@weasel-js/menu';\nimport type { Action } from '../interactions/actions/action';\nimport { actionBindings, type GestureBinding } from '../interactions/actions/binding';\nimport { keySpecShortcut, paramsMatch } from '../interactions/actions/actionShortcuts';\nimport { resolveParams } from '../interactions/actions/invoker';\nimport { NO_OVERRIDES, overriddenBindings, type ResolvedBindingOverrides } from '../interactions/actions/bindingOverrides';\nimport { keymapLeaderId, leaderBindings, type KeymapDef } from './keymapContribution';\nimport type { OpenKeymap } from './keymapStack';\n\n/** One row of a keymap's hint: a key chip, or a pointer gesture in words, and what it does. */\nexport interface KeymapRow {\n shortcut?: MenuShortcut;\n gesture?: string;\n label: string;\n}\n\n/** An open keymap as a hint shows it: {@link describeKeymap}'s result. */\nexport interface KeymapDescription {\n id: string;\n label: string;\n /** Whether a held leader is keeping it open. */\n held: boolean;\n rows: readonly KeymapRow[];\n}\n\nconst ESCAPE: KeymapRow = { shortcut: { key: 'Escape', mod: false, alt: false, shift: false }, label: 'Close' };\n\nconst GESTURE_WORDS: Partial<Record<GestureSpec['kind'], string>> = {\n click: 'click', doubleClick: 'double-click', drag: 'drag', longPress: 'long-press',\n contextMenu: 'right-click', wheel: 'scroll', pinch: 'pinch', pointerDown: 'press',\n};\n\nconst MOD_WORDS: readonly [keyof NonNullable<GestureSpec['mods']>, string][] = [\n ['mod', 'Mod'], ['ctrl', 'Ctrl'], ['meta', 'Meta'], ['alt', 'Alt'], ['shift', 'Shift'],\n];\n\n/** A pointer gesture in words, modifiers first: `Shift-click`. */\nfunction gestureWords(spec: GestureSpec): string | undefined {\n if (spec.kind === 'key-held') {\n const chip = keySpecShortcut(spec);\n return chip ? `Hold ${formatShortcut(chip)}` : undefined;\n }\n const word = GESTURE_WORDS[spec.kind];\n if (!word) return undefined;\n const mods = MOD_WORDS.filter(([m]) => spec.mods?.[m] === true).map(([, w]) => w);\n const text = [...mods, word].join('-');\n return text[0]!.toUpperCase() + text.slice(1);\n}\n\n/** The rows a hint lists for an open keymap, under the overrides in force. */\nexport function describeKeymap(\n level: OpenKeymap,\n actions: readonly Action[],\n overrides: ResolvedBindingOverrides = NO_OVERRIDES,\n): KeymapDescription {\n const byId = new Map(actions.map((a) => [a.id, a]));\n // A binding that picks a variant by its params is listed by the variant's label: Flip Horizontal.\n const labelOf = (b: GestureBinding): string => {\n const action = byId.get(b.actionId);\n const params = resolveParams(b.opts?.params);\n const variant = params && action?.variants?.find((v) => paramsMatch(params, v.params));\n return variant ? variant.label : action?.label ?? b.actionId;\n };\n const rows: KeymapRow[] = [ESCAPE];\n for (const b of overriddenBindings(level.bindings, level.id, overrides)) {\n const label = labelOf(b);\n const shortcut = b.spec.kind === 'key' ? keySpecShortcut(b.spec) : undefined;\n if (shortcut) rows.push({ shortcut, label });\n else {\n const gesture = gestureWords(b.spec);\n if (gesture) rows.push({ gesture, label });\n }\n }\n return { id: level.id, label: level.label, held: level.heldBy !== undefined, rows };\n}\n\n/**\n * Every key in `def` as a menu chip, by action id, each carrying the path\n * through its leader (`Loupe ▸ 2`), under `overrides`. A keymap with no key\n * leader gives its keys no path.\n */\nexport function keymapShortcuts(\n def: KeymapDef,\n overrides: ResolvedBindingOverrides = NO_OVERRIDES,\n): ReadonlyMap<string, readonly MenuShortcut[]> {\n const leaderChip = overriddenBindings(actionBindings({ id: keymapLeaderId(def.id), defaultBinding: leaderBindings(def) }), null, overrides)\n .map((b) => keySpecShortcut(b.spec))\n .find((c) => c !== undefined);\n const out = new Map<string, MenuShortcut[]>();\n for (const b of overriddenBindings(def.bindings, def.id, overrides)) {\n if (b.spec.kind !== 'key') continue;\n const chip = keySpecShortcut(b.spec);\n if (!chip) continue;\n const withPath: MenuShortcut = leaderChip ? { ...chip, leader: [{ label: def.label, shortcut: leaderChip }] } : chip;\n out.set(b.actionId, [...(out.get(b.actionId) ?? []), withPath]);\n }\n return out;\n}\n","// src/tools/types.ts\nimport type { ModifierState } from '../vocabulary';\nimport type { Contribution } from '../contributions/types';\nimport type { CursorSpec } from '@weasel-js/cursor';\nimport type { KernelOverlay } from '../index';\n\n/**\n * A tool's activation key, as `ToolDef.keybinding` declares it. Captures\n * only the fields meaningful to a tool-select key —\n * dispatcher-internal fields (`skipInEditable`, `enabled`,\n * `preventDefault`) live on `KeyBinding` in keyHelpers.ts and are\n * not part of the configurable surface.\n */\nexport interface ToolKeybinding {\n /** Key or list of keys to match (case-insensitive against `event.key`). */\n key: string | readonly string[];\n /** Require Cmd (mac) / Ctrl (others). Default `false`. */\n mod?: boolean;\n /** Require Alt. Default `false`. */\n alt?: boolean;\n /**\n * Shift policy. `undefined`/`false` forbids shift, `true` requires\n * shift, `'optional'` allows either.\n */\n shift?: boolean | 'optional';\n}\n\n/** Modifier-key snapshot at event dispatch time. */\nexport type ToolModifiers = ModifierState;\n\n/**\n * The focus-declaring case of a `Contribution`: a mode the user switches\n * into, plus the hooks that only make sense for one (activate/deactivate,\n * `cursor`). Everything else — bindings, actions, overlay, presentation — is\n * inherited.\n */\nexport interface Tool<TOverlay = KernelOverlay> extends Contribution<TOverlay> {\n /** The key that activates this tool. `useKeybindings` appends a binding\n * entry for it to the consolidated `tool.activate` action (with\n * `opts.params.toolId` set so the invoker knows which tool to switch to).\n * A tool with none has no activation key. */\n keybinding?: ToolKeybinding;\n cursor?: CursorSpec | (() => CursorSpec);\n /** The tool became live: it took the active slot, or its `hotkey` went\n * down, while it held neither. A lifecycle moment has no pointer, hit or\n * modifier state to report; a callback needing the selection or the scene\n * closes over it, as the tool's actions do. */\n onActivate?: () => void;\n /** The tool stopped being live in both slots, or its canvas unmounted. */\n onDeactivate?: () => void;\n}\n\n/** Whether `entry` is a tool: a contribution that can hold focus, chosen from\n * a palette or held on a key. Only a tool's focus hooks (`cursor`,\n * `onActivate`, `onDeactivate`) ever run. */\nexport function isTool<TOverlay>(entry: Contribution<TOverlay>): entry is Tool<TOverlay> {\n return !!(entry.eligibility?.focus || entry.eligibility?.offhand);\n}\n\n/** Internal — which slot a tool occupies in the dispatch order. */\nexport type ToolSlot = 'hotkey' | 'active' | 'ambient';\n\n/** A tool drawing any overlay type — the element type for registries and\n * dispatchers that never read the overlay. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyTool = Tool<any>;\n","import type { ParsedModifiers } from '../routeGrammar';\nimport { VALID_MOD_NAMES } from '../routeGrammar';\nimport { PREDICATE_TARGET, type RegistryEntry } from './registry';\n\n/** The two ways `mod` resolves: to `meta` on a Mac, to `ctrl` elsewhere. */\nexport type Platform = 'mac' | 'other';\nexport const PLATFORMS: readonly Platform[] = ['mac', 'other'];\n\n/** `mods` with `mod` replaced by the key it stands for on `platform`. As in\n * `matchModifiers`, a spec naming `mod` has its own `meta` and `ctrl` ignored. */\nfunction resolveMod(mods: ParsedModifiers, platform: Platform): ParsedModifiers {\n if (mods.mod === undefined) return mods;\n const { mod, meta: _meta, ctrl: _ctrl, ...rest } = mods;\n return { ...rest, [platform === 'mac' ? 'meta' : 'ctrl']: mod };\n}\n\n/** Whether every entry fires the same action of the same owner with equal\n * params, so that which of them wins a tie changes nothing. */\nexport function sameOutcome(entries: readonly RegistryEntry[]): boolean {\n const first = entries[0];\n return entries.every((e) =>\n e.ownerId === first.ownerId && e.actionId === first.actionId && sameParams(e.params, first.params));\n}\n\nfunction sameParams(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keys = Object.keys(a);\n return keys.length === Object.keys(b).length\n && keys.every((k) => sameParams((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]));\n}\n\n/** One key per way an entry can win a press: each modifier state its spec\n * accepts, with how many modifiers it requires. Two specs tie only where\n * they share a state and that count, since the matcher ranks a required\n * modifier above an optional one. `mod` is read as the key it resolves to on\n * `platform`, so it meets a `ctrl` or `meta` spelled out beside it. */\nexport function modifierTieKeys(entry: RegistryEntry, platform: Platform): string[] {\n const mods = resolveMod(entry.modifiers, platform);\n const optional = VALID_MOD_NAMES.filter((k) => mods[k] === 'optional');\n const required = VALID_MOD_NAMES.filter((k) => mods[k] === 'required');\n const keys: string[] = [];\n for (let bits = 0; bits < 1 << optional.length; bits++) {\n const held = [...required, ...optional.filter((_, i) => (bits & (1 << i)) !== 0)].sort();\n keys.push(`${held.join('+')}:${required.length}`);\n }\n return keys;\n}\n\n/** Whether two bindings' `views` let them tie in some view. A binding is live\n * only in the views it names, and there it outranks one that names none\n * (`preferViewScoped`), so a scoped and an unscoped binding never tie; two\n * scoped ones tie where their views overlap. */\nexport function viewsTie(\n a: readonly (string | null)[] | undefined,\n b: readonly (string | null)[] | undefined,\n): boolean {\n if (a === undefined || b === undefined) return a === b;\n return a.some((v) => b.includes(v));\n}\n\n/** Every arg value an entry buckets under, lowercased — `matchKey` is\n * case-insensitive, so `'h'` and `'H'` are one arg. */\nexport function argKeysOf(entry: RegistryEntry): readonly string[] {\n const alts = entry.argAlternatives;\n if (alts && alts.length > 0) return [...new Set(alts.map((a) => a.toLowerCase()))];\n return [(entry.arg ?? '').toLowerCase()];\n}\n\n/** Bucket key for an entry's target slot. Predicate targets all render as\n * the same grammar token, so they're keyed by the predicate's identity —\n * two different functions are two different targets. */\nexport function targetKey(entry: RegistryEntry): string {\n if (entry.target !== PREDICATE_TARGET) return entry.target ?? '';\n const spec = entry.spec as { target?: unknown };\n const pred = spec.target;\n if (typeof pred !== 'object' || pred === null) return PREDICATE_TARGET;\n return `${PREDICATE_TARGET}#${objectId(pred)}`;\n}\n\nconst OBJECT_IDS = new WeakMap<object, number>();\nlet nextObjectId = 0;\n\n/** A stable number for an object, so a bucket key can name it by identity. */\nexport function objectId(obj: object): number {\n let id = OBJECT_IDS.get(obj);\n if (id === undefined) {\n id = nextObjectId++;\n OBJECT_IDS.set(obj, id);\n }\n return id;\n}\n","import type { Contribution } from '../../../contributions/types';\nimport type { Action } from '../../../interactions/actions/action';\nimport { actionBindings } from '../../../interactions/actions/binding';\nimport { overriddenBindings, type ResolvedBindingOverrides } from '../../../interactions/actions/bindingOverrides';\nimport type { ParsedModifiers } from '../routeGrammar';\nimport { canonicalModifiers, formatRoute } from '../routeGrammar';\nimport { activeModeOf, DEFAULT_MODES, type ActiveMode } from '@weasel-js/modes';\nimport { ALWAYS, ruleCanHoldIn, rulesExclusive, type Rule } from '../../../eligibility';\nimport { buildRouteRegistry, type RegistryEntry, type GestureName } from './registry';\nimport { argKeysOf, modifierTieKeys, objectId, PLATFORMS, sameOutcome, targetKey, viewsTie, type Platform } from './conflictKeys';\n\n/** Two or more bindings declare the same exact (phase, gesture, arg, target,\n * modifiers) tuple, so slot order alone picks one. */\nexport interface Conflict {\n phase: 'initial' | 'engaged' | 'any';\n gesture: GestureName;\n arg: string | undefined;\n target: string | undefined;\n modifiers: ParsedModifiers;\n /** The ids of every entry that declared the same tuple. At least 2 by\n * construction, in input order. */\n ownerIds: string[];\n}\n\n/** Detect exact-tuple overlaps across a tool registration set.\n *\n * Intentionally NOT flagged:\n * - Broad vs. narrow targets (e.g. an untargeted `click` alongside\n * `click` on `empty`) — the dispatcher's specificity ordering resolves\n * those cleanly, and the broad one is usually the intended fallback.\n * - Modifier requirements no one press satisfies at equal rank: Shift\n * required against Alt required fire on different inputs, and Shift\n * required outranks Shift optional. An optional modifier against a\n * forbidden one is flagged, since both take the bare press.\n * - Two `{ kindOf }` predicate targets, unless they are the same function.\n * Predicates bucket by identity, so two separately written but\n * equivalent ones go unflagged.\n * - Two actions whose `eligible` rules can never hold together — each\n * mode's own Escape exit, say. See {@link rulesExclusive}.\n * - Two bindings whose `opts.views` keep them from being live and equally\n * ranked in any one view.\n * - Two bindings of one action with equal params that tie on one platform\n * only: `mod` against `ctrl`, which are one key off a Mac and two on it.\n * The same pair tying on both platforms is a plain duplicate and is flagged.\n *\n * A binding whose action declines via `enabled()` so a lower-priority one\n * takes the gesture is flagged all the same, since seeing that intent would\n * mean evaluating the action, unless it says so with `opts.yields`. A pair\n * whose earlier binding yields is not a conflict; one whose later binding\n * yields still is, as the earlier one decides alone.\n *\n * Two bindings on the same tool can share a tuple, so a conflict may name\n * one tool twice.\n *\n * Feeding this a whole tool *registry* over-reports, because registry tools\n * take turns in the active slot and can't collide with each other — see\n * `findScopedConflicts`.\n */\nexport function findConflicts(entries: readonly Contribution<unknown>[]): Conflict[] {\n return findConflictsKeyed(entries).map((k) => k.conflict);\n}\n\n/**\n * The same detector, keeping each conflict's bucket key. `Conflict.target`\n * renders every predicate as one token, so two distinct predicate collisions\n * look alike once rendered; `findScopedConflicts` dedupes on the key instead.\n */\nfunction findConflictsKeyed(\n entries: readonly Contribution<unknown>[],\n rules?: ReadonlyMap<string, Rule>,\n modes: readonly ActiveMode[] = KIT_MODES,\n): { key: string; conflict: Conflict }[] {\n const rows = buildRouteRegistry(entries);\n const groups = new Map<string, { base: string; platform: Platform; members: RegistryEntry[] }>();\n for (const entry of rows) {\n // One bucket per arg the binding answers to, not one per display token:\n // `key: ['h','H']` and `key: 'H'` really do collide, as do two `drop` specs\n // whose MIME sets overlap without being equal. Modifiers bucket the same\n // way, one per state the spec accepts, so an optional Shift meets a forbidden one.\n for (const arg of argKeysOf(entry)) {\n const base = `${entry.phase}|${entry.gesture}|${arg}|${targetKey(entry)}`;\n for (const platform of PLATFORMS) {\n for (const state of modifierTieKeys(entry, platform)) {\n const key = `${platform}|${base}|${state}`;\n const bucket = groups.get(key);\n if (bucket) { if (!bucket.members.includes(entry)) bucket.members.push(entry); }\n else groups.set(key, { base, platform, members: [entry] });\n }\n }\n }\n }\n // Only actions carry a rule, so a tool's or contribution's bindings count as eligible always.\n const ruleOf = (entry: RegistryEntry): Rule => rules?.get(entry.ownerId) ?? ALWAYS;\n const tie = (e: RegistryEntry, f: RegistryEntry): boolean =>\n viewsTie(e.views, f.views) && rulesCanHoldTogether(ruleOf(e), ruleOf(f), modes);\n const conflicts = new Map<string, { conflict: Conflict; bucket: RegistryEntry[]; platforms: Set<Platform> }>();\n for (const { base, platform, members } of groups.values()) {\n // Keep only members that could tie with another member. Members are in\n // declaration order, and a pair led by a binding that yields is ordered on purpose.\n const ties = (e: RegistryEntry, i: number, f: RegistryEntry, j: number): boolean =>\n i !== j && !(i < j ? e : f).yields && tie(e, f);\n const bucket = members.filter((e, i) => members.some((f, j) => ties(e, i, f, j)));\n if (bucket.length < 2) continue;\n const first = bucket[0];\n // Two specs that tie in one modifier state usually tie in several, and on\n // both platforms: one conflict per set of specs, each named by identity so\n // the key is the same in every pass `findScopedConflicts` makes over them.\n const key = `${base}|${bucket.map((e) => `${objectId(e.spec)}:${canonicalModifiers(e.modifiers)}`).join(';')}`;\n const found = conflicts.get(key);\n if (found) { found.platforms.add(platform); continue; }\n conflicts.set(key, {\n conflict: {\n phase: first.phase,\n gesture: first.gesture,\n arg: first.arg,\n target: first.target,\n modifiers: first.modifiers,\n ownerIds: bucket.map((e) => e.ownerId),\n },\n bucket,\n platforms: new Set([platform]),\n });\n }\n return [...conflicts]\n // Bindings that fire one thing and tie on one platform only are how an\n // action binds a key that `mod` covers there and not on the other.\n .filter(([, c]) => c.platforms.size === PLATFORMS.length || !sameOutcome(c.bucket))\n .map(([key, { conflict }]) => ({ key, conflict }));\n}\n\n/** The tool scopes as the dispatcher sees them. */\nexport interface ToolScopes {\n /** Tools eligible for the active slot, keyed by id or as a flat list. */\n registry: readonly Contribution<unknown>[] | Readonly<Record<string, Contribution<unknown>>>;\n /** Always-on entries. Every one of these is live at once. */\n ambient?: readonly Contribution<unknown>[];\n /** Registered actions. Their `defaultBinding`s assemble at ambient scope\n * (hotkey scope when `Action.scope` says so), alongside the tools above. */\n actions?: readonly Action[];\n /** Every mode the canvas can be in (`activeModeOf` builds one from a\n * definition). Two gated actions conflict only when some mode lets both\n * rules hold. Default: the kit's `DEFAULT_MODES`. */\n modes?: readonly ActiveMode[];\n /** Binding overrides in force, applied to the entries' bindings. Actions are\n * read as given: an `ActionsRegistry`'s `list()` has applied them already. */\n overrides?: ResolvedBindingOverrides;\n}\n\n/** Whether two rules can hold at once: never when {@link rulesExclusive}\n * proves it, and given the modes, only when one of them lets both hold. */\nfunction rulesCanHoldTogether(a: Rule, b: Rule, modes: readonly ActiveMode[]): boolean {\n if (rulesExclusive(a, b)) return false;\n return modes.some((m) => ruleCanHoldIn(a, m) && ruleCanHoldIn(b, m));\n}\n\nconst KIT_MODES: readonly ActiveMode[] = DEFAULT_MODES.map(activeModeOf);\n\n/** An action's `defaultBinding`s in the shape the route registry reads, so a\n * tool-vs-action collision buckets with the tool-vs-tool ones. */\nfunction actionAsEntry(action: Action): Contribution<unknown> {\n return { id: action.id, eligibility: {}, bindings: actionBindings(action) };\n}\n\nfunction eligibleRule(action: Action): Rule | undefined {\n const eligible = action.eligible;\n if (eligible === undefined) return undefined;\n return typeof eligible === 'function' ? eligible.rule : eligible;\n}\n\n/**\n * Detect the same-tuple overlaps that are *reachable* — the ones where the\n * dispatcher really does fall back on declaration order.\n *\n * Scopes are walked in strict priority (hotkey > active > ambient), so a\n * cross-scope tie isn't a tie, and two registry tools sharing a tuple can\n * never both be in the active slot. What this reports:\n * - a single tool colliding with **itself**;\n * - two **ambient** tools, which are all live at once and ordered only by\n * registration;\n * - two **hotkey-capable** tools, which can stack.\n *\n * Registered actions join the ambient and hotkey groups. An ambient action\n * gated by an `eligible` rule outranks every ungated binding when its rule\n * holds, so it is compared only with other gated actions. Two actions whose\n * `eligible` rules can never hold together, in any of `scopes.modes`, don't\n * collide.\n */\nexport function findScopedConflicts(scopes: ToolScopes): Conflict[] {\n const overrides = scopes.overrides;\n const asBound = (e: Contribution<unknown>): Contribution<unknown> =>\n (overrides?.size && e.bindings ? { ...e, bindings: overriddenBindings(e.bindings, e.id, overrides) } : e);\n const registry = (Array.isArray(scopes.registry)\n ? (scopes.registry as readonly Contribution<unknown>[])\n : Object.values(scopes.registry as Readonly<Record<string, Contribution<unknown>>>)).map(asBound);\n const declaredAmbient = (scopes.ambient ?? []).map(asBound);\n const actions = scopes.actions ?? [];\n const rules = new Map<string, Rule>();\n for (const a of actions) {\n const rule = eligibleRule(a);\n if (rule) rules.set(a.id, rule);\n }\n const hotkeyActions = actions.filter((a) => a.scope === 'hotkey').map(actionAsEntry);\n const gatedActions: Contribution<unknown>[] = [];\n const ungated: Contribution<unknown>[] = [];\n for (const a of actions) {\n if (a.scope === 'hotkey') continue;\n (a.eligible !== undefined ? gatedActions : ungated).push(actionAsEntry(a));\n }\n const modes = scopes.modes ?? KIT_MODES;\n // A keymap is live only while it is the one open, so it can collide with nothing but itself.\n const isKeymap = (e: Contribution<unknown>): boolean => e.eligibility?.keymap !== undefined;\n const keymaps = declaredAmbient.filter(isKeymap);\n const ambient = [...declaredAmbient.filter((e) => !isKeymap(e)), ...ungated];\n\n const out: Conflict[] = [];\n const seen = new Set<string>();\n const add = (keyed: readonly { key: string; conflict: Conflict }[]): void => {\n for (const { key, conflict } of keyed) {\n const dedupeKey = `${key}|${conflict.ownerIds.join(',')}`;\n if (seen.has(dedupeKey)) continue;\n seen.add(dedupeKey);\n out.push(conflict);\n }\n };\n\n // Self-collisions: every entry, actions included. The group passes below\n // need more than one member, so a lone action is checked by nothing else.\n for (const tool of [...registry, ...ambient, ...keymaps, ...gatedActions, ...hotkeyActions]) {\n add(findConflictsKeyed([tool], rules, modes));\n }\n // Ambient tools and ungated ambient actions are all live together.\n if (ambient.length > 1) add(findConflictsKeyed(ambient, rules, modes));\n if (gatedActions.length > 1) add(findConflictsKeyed(gatedActions, rules, modes));\n // Hotkey-capable tools can stack on each other. An entry declares the\n // trigger as `eligibility.offhand`; a tool handed to `useTools` without\n // going through `defineTool` carries it only on its authored `def`.\n const hotkey = [\n ...registry.filter((t) => t.eligibility?.offhand !== undefined\n || (t as { def?: { hotkey?: unknown } }).def?.hotkey !== undefined),\n ...hotkeyActions,\n ];\n if (hotkey.length > 1) add(findConflictsKeyed(hotkey, rules, modes));\n\n return out;\n}\n\n/**\n * Render a conflict as one line of text, in the route grammar the binding was\n * written in — except the phase slot: a single phase prints as a bare\n * `'&'`-channel atom, and `'any'` prints as `*:*`.\n */\nexport function formatConflict(conflict: Conflict): string {\n const route = formatRoute({\n phases: [conflict.phase === 'any'\n ? { channel: '*', phase: '*' }\n : { channel: '&', phase: conflict.phase }],\n gesture: conflict.gesture,\n arg: conflict.arg,\n target: conflict.target,\n modifiers: conflict.modifiers,\n });\n return `${route} — declared by ${conflict.ownerIds.join(', ')}`;\n}\n\n/**\n * Detect reachable route conflicts in an assembled tool set and report each one.\n *\n * Call it once wherever a tool set is assembled, behind an `isDev()` guard.\n *\n * **Warn, never throw.** A conflict between a consumer's tool and a kit tool\n * is sometimes deliberate, since the loser can still take the gesture when\n * the winner declines through `enabled()`. A binding ordered that way on\n * purpose says so with `opts.yields`, and is not reported.\n *\n * @returns The conflicts found, so callers can dedupe repeat reports.\n */\nexport function reportRouteConflicts(\n scopes: ToolScopes,\n warn: (message: string) => void = (m) => console.warn(m),\n): Conflict[] {\n const conflicts = findScopedConflicts(scopes);\n for (const c of conflicts) {\n warn(\n `[weasel] route conflict: two bindings declare the same (phase, gesture, arg, target, modifiers) tuple `\n + `in the same scope, so declaration order alone decides which one fires.\\n ${formatConflict(c)}`,\n );\n }\n return conflicts;\n}\n","/**\n * Pure keyboard-binding helpers shared between the tool dispatcher\n * (`useKeybindings`), the gesture dispatcher (`useGestureDispatcher`), and\n * individual Tool declarations.\n *\n * Extracted from the deleted singular `useKeybinding` hook so the remaining\n * consumers don't depend on its disappearance.\n *\n * @packageDocumentation\n */\n\nexport { activatesFocusedControl, focusedControlOwnsKey, isEditableTarget } from '@weasel-js/gestures';\n\n/**\n * A key plus a modifier policy, as {@link matchesKeyBinding} tests it against a\n * `KeyboardEvent`. Every modifier left unset is forbidden, so `{ key: 'a' }`\n * does not fire on Cmd+A. The matcher ignores `skipInEditable`, `enabled` and\n * `preventDefault`; those are for whatever attaches the listener. Tools\n * declaring an activation key use `ToolKeybinding` instead.\n */\nexport interface KeyBinding {\n /**\n * Key or list of keys to match. Compared case-insensitively against\n * `event.key`, so `'a'` matches both `'a'` and `'A'`.\n */\n key: string | readonly string[];\n /**\n * Require Cmd (mac) or Ctrl (others). When `true`, exactly one of\n * `metaKey`/`ctrlKey` must be held. Default `false` (both forbidden).\n */\n mod?: boolean;\n /** Require Alt. Default `false` (forbidden). */\n alt?: boolean;\n /**\n * Shift policy. `undefined`/`false` forbids shift, `true` requires\n * shift, `'optional'` allows either. Default `undefined`.\n */\n shift?: boolean | 'optional';\n /** Skip when focus is in an editable element. Default `true`. */\n skipInEditable?: boolean;\n /** When `false`, the listener is not attached. Default `true`. */\n enabled?: boolean;\n /** Call `preventDefault` before the handler. Default `true`. */\n preventDefault?: boolean;\n}\n\nfunction keyMatches(eventKey: string, spec: string | readonly string[]): boolean {\n const want = typeof spec === 'string' ? [spec] : spec;\n const ek = eventKey.toLowerCase();\n return want.some((k) => k.toLowerCase() === ek);\n}\n\n/**\n * Pure matcher for `KeyBinding` against a `KeyboardEvent`. Only checks key +\n * modifier policy — does NOT apply the editable-target skip or\n * `preventDefault`. Shared by the tool dispatcher (`useKeybindings`) and the\n * gesture dispatcher so the rules can't drift.\n */\nexport function matchesKeyBinding(e: KeyboardEvent, b: KeyBinding): boolean {\n if (!keyMatches(e.key, b.key)) return false;\n\n const wantsMod = b.mod === true;\n const hasMod = e.metaKey || e.ctrlKey;\n if (wantsMod !== hasMod) return false;\n\n const wantsAlt = b.alt === true;\n if (wantsAlt !== e.altKey) return false;\n\n const shift = b.shift;\n if (shift === undefined || shift === false) {\n if (e.shiftKey) return false;\n } else if (shift === true) {\n if (!e.shiftKey) return false;\n }\n return true;\n}\n\n/** Which history step `e` asks for: Mod+Z undoes, Shift+Mod+Z and Mod+Y redo. `null` for anything else. Takes a\n * React keyboard event as readily as a DOM one. */\nexport function historyKey(\n e: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'shiftKey' | 'altKey'>,\n): 'undo' | 'redo' | null {\n const ev = e as KeyboardEvent;\n if (matchesKeyBinding(ev, { key: 'z', mod: true })) return 'undo';\n if (matchesKeyBinding(ev, { key: 'z', mod: true, shift: true }) || matchesKeyBinding(ev, { key: 'y', mod: true }))\n return 'redo';\n return null;\n}\n","/**\n * IngestItem materialization — turns a live `DataTransfer` (drop) or\n * clipboard `DataTransfer` (paste) into fully-owned `IngestItem[]`.\n *\n * `DataTransfer` items are only readable while the originating DOM event is\n * on the stack, so BOTH functions must be called synchronously from the event\n * handler. `itemsFromDataTransfer` kicks off every `getAsString` read\n * immediately and resolves once all strings are collected;\n * `itemsFromClipboardData` is fully synchronous (`getData` + `files`).\n *\n * MIME strings are normalized to bare lowercase `type/subtype` (parameters\n * like `;charset=utf-8` stripped) — downstream exact matching (binding\n * `types`, content-handler `match`) assumes the bare form.\n *\n * Output shape: **files first (source order), then strings (item order)**.\n * For paste (`itemsFromClipboardData`) string flavors are emitted in\n * `INGEST_STRING_MIMES` order: text/plain, text/html, text/uri-list, then\n * the admitted ones in the order they were first admitted.\n */\nimport { UNKNOWN_MIME, type IngestItem } from '@weasel-js/gestures';\n\nexport type { IngestItem };\n\n/** The string flavors the kit always keeps. Any other is dropped at\n * materialization unless {@link admitIngestMime} has admitted it. */\nexport const INGEST_STRING_MIMES: ReadonlySet<string> = new Set([\n 'text/plain',\n 'text/html',\n 'text/uri-list',\n]);\n\nconst FALLBACK_MIME = 'application/octet-stream';\n\n/** Normalize a raw MIME to bare lowercase `type/subtype`. */\nfunction normalizeMime(raw: string): string {\n const bare = raw.split(';')[0].trim().toLowerCase();\n return bare || FALLBACK_MIME;\n}\n\nconst admitted = new Map<string, number>();\n\n/**\n * Keep string flavors of `mime` on drops, drags and pastes as well as the\n * {@link INGEST_STRING_MIMES}, so content from the app's own UI can travel\n * under a type of its own. Returns a release; the flavor is kept while any\n * admission of it is unreleased. Core admits each exact MIME a registered\n * content handler names.\n */\nexport function admitIngestMime(mime: string): () => void {\n const key = normalizeMime(mime);\n admitted.set(key, (admitted.get(key) ?? 0) + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const n = (admitted.get(key) ?? 1) - 1;\n if (n > 0) admitted.set(key, n);\n else admitted.delete(key);\n };\n}\n\nconst keepsString = (mime: string): boolean => INGEST_STRING_MIMES.has(mime) || admitted.has(mime);\n\n/** Wrap raw `File`s (file picker, `CanvasExtensionApi.ingest`) as\n * `IngestItem`s, normalizing each MIME the same way the drop/paste paths\n * do. Synchronous — `File` objects are already fully owned. */\nexport function itemsFromFiles(files: File[]): IngestItem[] {\n return files.map((file) => ({ kind: 'file', mime: normalizeMime(file.type), file }));\n}\n\n/** Materialize a drop's `DataTransfer`. MUST be called during the `drop`\n * event dispatch (see module doc). */\nexport function itemsFromDataTransfer(dt: DataTransfer): Promise<IngestItem[]> {\n const files: IngestItem[] = [];\n const strings: IngestItem[] = [];\n const reads: Promise<void>[] = [];\n\n for (const item of Array.from(dt.items ?? [])) {\n if (item.kind === 'file') {\n const file = item.getAsFile();\n if (file) files.push({ kind: 'file', mime: normalizeMime(file.type), file });\n } else if (item.kind === 'string') {\n const mime = normalizeMime(item.type);\n if (keepsString(mime)) {\n const slot = strings.length;\n strings.push(null as never);\n reads.push(\n new Promise((resolve) => {\n item.getAsString((text) => {\n strings[slot] = { kind: 'string', mime, text };\n resolve();\n });\n }),\n );\n }\n }\n }\n\n // Some sources populate `files` without `items` (older engines, jsdom).\n if (files.length === 0 && reads.length === 0) {\n for (const file of Array.from(dt.files ?? [])) {\n files.push({ kind: 'file', mime: normalizeMime(file.type), file });\n }\n }\n\n return Promise.all(reads).then(() => [...files, ...strings]);\n}\n\n/**\n * What a drag still in flight says it carries: one item per flavor, MIME\n * only. A browser withholds contents until the drop, so nothing may read\n * `file` or `text` off these; they exist to ask which bindings would match.\n * A file the browser does not name yet (Firefox reports\n * `application/x-moz-file`, others only a `Files` type) is `UNKNOWN_MIME`.\n */\nexport function itemTypesFromDataTransfer(dt: DataTransfer): readonly IngestItem[] {\n const mimes: string[] = [];\n for (const item of Array.from(dt.items ?? [])) {\n const mime = item.type ? normalizeMime(item.type) : '';\n if (item.kind === 'file') mimes.push(mime && mime !== 'application/x-moz-file' ? mime : UNKNOWN_MIME);\n else if (keepsString(mime)) mimes.push(mime);\n }\n if (mimes.length === 0 && Array.from(dt.types ?? []).includes('Files')) mimes.push(UNKNOWN_MIME);\n return mimes.map((mime) => ({ mime })) as unknown as IngestItem[];\n}\n\n/** Materialize a paste's `clipboardData`. Fully synchronous. */\nexport function itemsFromClipboardData(cd: DataTransfer): IngestItem[] {\n const out: IngestItem[] = [];\n for (const file of Array.from(cd.files ?? [])) {\n out.push({ kind: 'file', mime: normalizeMime(file.type), file });\n }\n for (const mime of new Set([...INGEST_STRING_MIMES, ...admitted.keys()])) {\n const text = cd.getData(mime);\n if (text) out.push({ kind: 'string', mime, text });\n }\n return out;\n}\n","/**\n * Convert client coords to element CSS-pixel coords (relative to the element's\n * top-left). Apps drawing in CSS-pixel space feed the result directly into\n * world math when pan/zoom is identity. With pan/zoom, compose this with\n * your inverse-viewport transform.\n */\nexport function clientToCanvas(\n canvas: HTMLElement,\n clientX: number,\n clientY: number,\n): [number, number] {\n const rect = canvas.getBoundingClientRect();\n return [clientX - rect.left, clientY - rect.top];\n}\n\n/**\n * Rect-taking variant of `clientToCanvas` for call sites that already hold a\n * `DOMRect` (or any `{ left, top }` object) and don't have a canvas element\n * in scope.\n */\nexport function clientToCanvasRect(\n rect: { left: number; top: number },\n clientX: number,\n clientY: number,\n): [number, number] {\n return [clientX - rect.left, clientY - rect.top];\n}\n","/**\n * Namespaced, opt-in console tracing for the kit.\n *\n * Enable in the browser:\n *\n * localStorage.setItem('weasel.debug', '*') // all namespaces\n * localStorage.setItem('weasel.debug', 'tools,dispatch') // specific ones\n * localStorage.setItem('weasel.debug', '1') // legacy \"all\"\n *\n * Each call site picks a stable namespace string. Off by default; the flag\n * is read once and cached per page session — reload to pick up a change.\n *\n * The one definition: `@weasel-js/core` and `@weasel-js/ui` pass these on, so\n * every package reads the flag from one cache.\n *\n * Known kit namespaces:\n * - tools — active-tool + hotkey transitions (useTools)\n * - dispatch — gesture start / end / cancel (dispatcher)\n * - drag-rect — useDragRect lifecycle\n * - drag-radial — useDragRadial lifecycle\n * - scene — restored-op replay gaps (history persistence)\n * - scene-canvas — SceneCanvas mount / unmount; adapter paste-translation warnings\n * - history — applyOps push, no-op suppression, serialize/restore\n * - clipboard — OS clipboard write/read failures, malformed payloads\n */\n\nconst KEYS = ['weasel.debug', 'weaseldraw.debug'] as const;\n\ninterface Cached {\n all: boolean;\n set: Set<string>;\n}\n\nlet cached: Cached | null = null;\n\nfunction read(): Cached {\n const empty: Cached = { all: false, set: new Set() };\n if (typeof localStorage === 'undefined') return empty;\n try {\n for (const k of KEYS) {\n const v = localStorage.getItem(k);\n if (v == null || v === '') continue;\n if (v === '1' || v === 'true' || v === '*') return { all: true, set: new Set() };\n return { all: false, set: new Set(v.split(/[\\s,]+/).filter(Boolean)) };\n }\n return empty;\n } catch {\n return empty;\n }\n}\n\nfunction get(): Cached {\n if (cached === null) cached = read();\n return cached;\n}\n\n/** True when `namespace` (or `*`) is enabled. Pass no argument to test\n * whether *any* namespace is on (legacy global-flag semantics). */\nexport function isDebugEnabled(namespace?: string): boolean {\n const c = get();\n if (c.all) return true;\n if (namespace === undefined) return c.set.size > 0;\n return c.set.has(namespace);\n}\n\n/** Conditional `console.debug` — no-op unless `namespace` (or `*`) is enabled.\n * Each call is prefixed with `[namespace]` so the source is searchable. */\nexport function dlog(namespace: string, ...args: unknown[]): void {\n if (!isDebugEnabled(namespace)) return;\n // eslint-disable-next-line no-console\n console.debug(`[${namespace}]`, ...args);\n}\n\n/** Conditional `console.warn` — like `dlog` but at warn level. Use for\n * diagnostics that indicate something worth surfacing during debugging\n * (e.g. no-op op batches suppressed). */\nexport function dwarn(namespace: string, ...args: unknown[]): void {\n if (!isDebugEnabled(namespace)) return;\n console.warn(`[${namespace}]`, ...args);\n}\n","import type { MenuDef, MenuHit, MenuWhen, OwnedMenuDef } from './types';\n\nconst oneOf = <T>(want: T | readonly T[] | undefined, got: T | undefined) =>\n want === undefined || (Array.isArray(want) ? (want as readonly T[]).includes(got as T) : want === got);\n\nfunction matches(when: MenuWhen, hit: MenuHit): boolean {\n return oneOf(when.bodyTarget, hit.bodyTarget) && oneOf(when.bodyKind, hit.bodyKind);\n}\n\n/** The menus live now: ambient defs, then the active tool's. Defs that share\n * an id become one menu: each contribution's children in turn, with a\n * separator between contributions. Children stay at their own keys, so the\n * paths their values are read at do not move; a key a previous contribution\n * took gets `~n` appended. The first def of an id supplies the schema's\n * name and the def's `when`. */\nexport function mergeMenuDefs(defs: readonly OwnedMenuDef[], activeTool: string | null): MenuDef[] {\n const live = [\n ...defs.filter((d) => d.owner === null),\n ...defs.filter((d) => d.owner !== null && d.owner === activeTool),\n ];\n const byId = new Map<string, { def: MenuDef; parts: number }>();\n for (const { def } of live) {\n const prev = byId.get(def.id);\n if (!prev) {\n byId.set(def.id, { def: { ...def, menu: { ...def.menu, children: { ...def.menu.children } } }, parts: 1 });\n continue;\n }\n const n = prev.parts++;\n const children = prev.def.menu.children;\n children[`~sep${n}`] = { kind: 'separator', name: '', description: '', default: undefined };\n for (const [k, node] of Object.entries(def.menu.children)) {\n children[Object.hasOwn(children, k) ? `${k}~${n}` : k] = node;\n }\n if (!prev.def.when && def.when) prev.def.when = def.when;\n }\n return [...byId.values()].map((m) => m.def);\n}\n\n/** The first def whose `when` matches `hit`. */\nexport function pickMenu(defs: readonly MenuDef[], hit: MenuHit): MenuDef | undefined {\n return defs.find((d) => d.when !== undefined && matches(d.when, hit));\n}\n","import type { MenuEntry } from '@weasel-js/menu';\nimport {\n isPrefLeaf, PREF_SCOPE, prefAliasedLeaf, prefAliasTarget, prefConditionHolds, prefDisplayBounds, prefLeafAt,\n prefNumberAt, prefScopeIn, prefScopeUnder, prefUnitAccepts, prefValueAtPath, resolvePrefUnit,\n type PrefConditionJudge, type PrefOwner,\n type PrefAction, type PrefBoolean, type PrefColor, type PrefConditionReader, type PrefEnum, type PrefGroup,\n type PrefGroupAs, type PrefLeaf, type PrefNumber, type PrefString,\n} from '@weasel-js/prefs';\nimport type { Action } from '../interactions/actions/action';\nimport type { ActionDeps } from '../interactions/actions/invoker';\nimport { actionItems, type ActionItem } from '../interactions/actions/actionItems';\nimport { actionShortcuts } from '../interactions/actions/actionShortcuts';\nimport { evaluateActive, evaluateEnabled } from '../interactions/actions/actionEnabled';\nimport { actionSettingsParams, readActionSettings } from '../interactions/actions/actionSettings';\nimport { endlessAllows } from '@weasel-js/quantity';\nimport { isDev } from '@weasel-js/react';\nimport type { MenuDef } from './types';\nimport type { Point } from '@weasel-js/geom';\n\n/** What resolving reads: the registered actions, each one's deps, how to run\n * one, and the values behind the schema's value leaves. */\nexport interface MenuSources {\n actions(): readonly Action[];\n depsFor(action: Action): ActionDeps | undefined;\n trigger(id: string, params?: Record<string, unknown>): boolean;\n /** The value at a leaf's dotted path. Booleans, enums, and numbers are left\n * out of a menu without both this and `onChange`, colors and strings without\n * this, and `showIf`/`enableIf` are checked only with it. */\n values?(path: string): unknown;\n onChange?(path: string, value: unknown): void;\n /** The schema an `alias` leaf's `of` is read in. Default: the menu's own. */\n over?: PrefGroup;\n}\n\ntype Ctx = {\n src: MenuSources;\n byId: Map<string, Action>;\n root: PrefGroup;\n read?: PrefConditionReader;\n at?: Point;\n params?: Record<string, unknown>;\n};\n\nconst SUBMENU_AS: ReadonlySet<PrefGroupAs> = new Set(['menu', 'page', 'tab', 'panel']);\nconst noop = () => {};\nconst withAccess = (access?: string): { access?: string } => (access ? { access } : {});\nconst sep = (key: string): MenuEntry => ({ kind: 'separator', key });\n\nfunction itemOf(ctx: Ctx, it: ActionItem, key: string, label: string, off: boolean, access?: string): MenuEntry {\n const deps = ctx.src.depsFor(it.action);\n const point = ctx.at ? { worldX: ctx.at.x, worldY: ctx.at.y } : {};\n if (it.action.settings) return settingsOf(ctx, it, key, label, off || !evaluateEnabled(it.action, deps, ctx.at).enabled, access);\n return {\n kind: 'item',\n key,\n label,\n ...withAccess(access),\n icon: it.icon,\n shortcut: actionShortcuts(it.action, it.params)[0],\n disabled: off || !evaluateEnabled(it.action, deps, ctx.at).enabled,\n checked: evaluateActive(it.action, deps),\n run: () => { ctx.src.trigger(it.action.id, { ...ctx.params, ...it.params, ...point }); },\n };\n}\n\n/** An action carrying settings as a submenu of its form's rows, read when the\n * menu resolves; each change triggers the action with the params it makes. */\nfunction settingsOf(ctx: Ctx, it: ActionItem, key: string, label: string, off: boolean, access?: string): MenuEntry {\n const settings = it.action.settings!;\n const state = off ? null : readActionSettings(it.action, ctx.src.depsFor(it.action));\n const mixed = new Set(state?.mixed ?? []);\n const values = (path: string): unknown => (mixed.has(path) ? undefined : prefValueAtPath(state?.values, path));\n const onChange = (path: string, value: unknown): void => {\n const params = actionSettingsParams(settings, path, value);\n if (params) ctx.src.trigger(it.action.id, { ...ctx.params, ...it.params, ...params });\n };\n const form: Ctx = {\n ...ctx,\n src: { ...ctx.src, values, onChange, over: settings.schema },\n root: settings.schema,\n read: (path, from) => (from === 'item' ? undefined : values(path)),\n };\n const entries = state ? tidy(groupRows(form, settings.schema, '', ROOT)) : [];\n return {\n kind: 'submenu',\n key,\n label,\n ...(it.icon ? { icon: it.icon } : {}),\n ...withAccess(access),\n ...(entries.length === 0 ? { disabled: true } : {}),\n entries,\n };\n}\n\n/** The items a registry key names: an action's (one per variant), or the one\n * variant `id:variant` picks. */\nfunction itemsNamed(ctx: Ctx, name: string): ActionItem[] {\n const action = ctx.byId.get(name);\n if (action) return actionItems(action);\n const colon = name.indexOf(':');\n const owner = colon > 0 ? ctx.byId.get(name.slice(0, colon)) : undefined;\n return owner ? actionItems(owner).filter((it) => it.key === name) : [];\n}\n\nfunction actionRows(ctx: Ctx, leaf: PrefAction, key: string, off: boolean): MenuEntry[] {\n const own = leaf.label || leaf.name;\n if (leaf.action === undefined) {\n // A menu holds no code, so it can be saved as data: a leaf with only `run` is a dead row.\n if (!own) return [];\n if (isDev()) console.warn(`weasel: menu row \"${key}\" names no registered action, so it does nothing`);\n return [{ kind: 'item', key, label: own, disabled: true, run: noop }];\n }\n const items = itemsNamed(ctx, leaf.action);\n if (items.length === 1) return [itemOf(ctx, items[0]!, key, own || items[0]!.label, off, leaf.access)];\n return items.map((it) => itemOf(ctx, it, `${key}/${it.key}`, it.label, off));\n}\n\nfunction siblingsOf(ctx: Ctx, path: string): Record<string, unknown> | undefined {\n const dot = path.lastIndexOf('.');\n const parent = dot < 0 ? undefined : ctx.src.values!(path.slice(0, dot));\n return parent && typeof parent === 'object' ? parent as Record<string, unknown> : undefined;\n}\n\nfunction booleanRows(ctx: Ctx, leaf: PrefBoolean, key: string, path: string, off: boolean): MenuEntry[] {\n const { values, onChange } = ctx.src;\n if (!values || !onChange) return [];\n const stored = values(path);\n const on = leaf.encoding ? leaf.encoding.read(stored, siblingsOf(ctx, path)) : stored === true;\n const write = (v: boolean) => (leaf.encoding ? leaf.encoding.write(v, siblingsOf(ctx, path)) : v);\n return [{\n kind: 'item', key, label: leaf.name, ...withAccess(leaf.access), checked: on,\n disabled: off || leaf.readout === true,\n run: leaf.readout ? noop : () => onChange(path, write(!on)),\n }];\n}\n\nfunction enumRows(ctx: Ctx, leaf: PrefEnum, key: string, path: string, off: boolean): MenuEntry[] {\n const { values, onChange } = ctx.src;\n if (!values || !onChange) return [];\n const stored = values(path);\n const current = leaf.encoding ? leaf.encoding.read(stored, siblingsOf(ctx, path)) : stored;\n if (leaf.readout) {\n const shown = leaf.options.find((o) => o.value === current)?.label ?? '—';\n return [{ kind: 'item', key, label: `${leaf.name}: ${shown}`, disabled: true, run: noop }];\n }\n const write = (v: string) => (leaf.encoding ? leaf.encoding.write(v, siblingsOf(ctx, path)) : v);\n return [\n sep(`${key}/<`),\n ...leaf.options.map((o): MenuEntry => ({\n kind: 'item', key: `${key}/${o.value}`, label: o.label, checked: o.value === current,\n disabled: off || o.disabled === true, run: () => onChange(path, write(o.value)),\n })),\n sep(`${key}/>`),\n ];\n}\n\n/** A number row, in the units the leaf shows: its value, bounds, and step convert from the stored unit, and\n * what is set converts back. An infinity is a value only where an `endless` end stands for it. */\nfunction numberRows(ctx: Ctx, given: PrefNumber, key: string, path: string, off: boolean): MenuEntry[] {\n const { values, onChange } = ctx.src;\n if (!values || !onChange) return [];\n const leaf = prefNumberAt(given, values);\n const unit = leaf.unit && resolvePrefUnit(leaf.unit);\n const stored = values(path);\n const { min, max, step, endless } = prefDisplayBounds(leaf);\n const disabled = off || leaf.readout === true;\n return [{\n kind: 'number', key, label: leaf.name, ...withAccess(leaf.access),\n ...(leaf.icon ? { icon: leaf.icon } : {}),\n ...(disabled ? { disabled } : {}),\n value: typeof stored === 'number' && (Number.isFinite(stored) || endlessAllows(leaf.endless, stored))\n ? (unit ? unit.toDisplay(stored) : stored)\n : undefined,\n ...(min === undefined ? {} : { min }),\n ...(max === undefined ? {} : { max }),\n step,\n ...(unit?.suffix === undefined ? {} : { suffix: unit.suffix }),\n ...(leaf.display ? { display: leaf.display } : {}),\n ...(endless ? { endless } : {}),\n ...(leaf.infinity === undefined ? {} : { infinity: leaf.infinity }),\n ...(unit ? { accepts: prefUnitAccepts(unit) } : {}),\n set: (shown) => onChange(path, unit ? unit.fromDisplay(shown) : shown),\n }];\n}\n\nconst textAt = (ctx: Ctx, path: string): string | undefined => {\n const v = ctx.src.values?.(path);\n return typeof v === 'string' && v !== '' ? v : undefined;\n};\n\n/** A color row: read-only, whether or not the leaf is a readout. */\nfunction colorRows(ctx: Ctx, leaf: PrefColor, key: string, path: string, off: boolean): MenuEntry[] {\n if (!ctx.src.values) return [];\n return [{ kind: 'color', key, label: leaf.name, ...withAccess(leaf.access), ...(off ? { disabled: true } : {}), value: textAt(ctx, path) }];\n}\n\n/** A string row is edited in place; a readout, or one nothing writes, reads as its name and value, as an enum readout does. */\nfunction stringRows(ctx: Ctx, leaf: PrefString, key: string, path: string, off: boolean): MenuEntry[] {\n const { values, onChange } = ctx.src;\n if (!values) return [];\n if (leaf.readout || !onChange) {\n return [{ kind: 'item', key, label: `${leaf.name}: ${textAt(ctx, path) ?? '—'}`, ...withAccess(leaf.access), disabled: true, run: noop }];\n }\n const stored = values(path);\n return [{\n kind: 'text', key, label: leaf.name, ...withAccess(leaf.access),\n ...(leaf.icon ? { icon: leaf.icon } : {}),\n ...(off ? { disabled: true } : {}),\n value: typeof stored === 'string' ? stored : undefined,\n set: (text) => onChange(path, text),\n }];\n}\n\n/** `key` names the row; `path` is where its value lives, which differs from\n * `key` only for a leaf reached through an alias. */\nfunction leafRows(ctx: Ctx, leaf: PrefLeaf, key: string, path: string, off: boolean): MenuEntry[] {\n switch (leaf.kind) {\n case 'action': return actionRows(ctx, leaf as PrefAction, key, off);\n case 'actions': {\n const group = (leaf as { group: string }).group;\n return ctx.src.actions()\n .filter((a) => a.group === group)\n .flatMap((a) => actionItems(a).map((it) => itemOf(ctx, it, `${key}/${it.key}`, it.label, off)));\n }\n case 'boolean': return booleanRows(ctx, leaf as PrefBoolean, key, path, off);\n case 'enum': return enumRows(ctx, leaf as PrefEnum, key, path, off);\n case 'number': return numberRows(ctx, leaf as PrefNumber, key, path, off);\n case 'color': return colorRows(ctx, leaf as PrefColor, key, path, off);\n case 'string': return stringRows(ctx, leaf as PrefString, key, path, off);\n case 'separator': return [sep(key)];\n case 'label':\n return [{ kind: 'item', key, label: leaf.name, ...withAccess(leaf.access), disabled: true, run: noop }];\n case 'alias': {\n const alias = leaf as Parameters<typeof prefAliasTarget>[0];\n const target = prefAliasTarget(alias, (p) => prefLeafAt(ctx.src.over ?? ctx.root, p));\n return target ? leafRows(ctx, prefAliasedLeaf(alias, target.leaf), key, target.path, off) : [];\n }\n default: return [];\n }\n}\n\nconst ROOT: PrefOwner = { node: {}, scope: PREF_SCOPE, above: PREF_SCOPE };\n\nfunction groupRows(ctx: Ctx, group: PrefGroup, prefix: string, owner: PrefOwner): MenuEntry[] {\n const { read } = ctx;\n const holds: PrefConditionJudge = (condition) => read === undefined || prefConditionHolds(condition, read);\n const out: MenuEntry[] = [];\n for (const [k, node] of Object.entries(group.children)) {\n const path = prefix ? `${prefix}.${k}` : k;\n const sits = isPrefLeaf(node) ? prefScopeIn(owner, path, holds) : owner.scope;\n const scope = prefScopeUnder(sits, node, holds);\n if (!scope.shown) continue;\n const disabled = !scope.enabled;\n const inner: PrefOwner = { node, scope, above: sits };\n if (isPrefLeaf(node)) {\n out.push(...leafRows(ctx, node, path, path, disabled));\n } else if (node.as !== undefined && SUBMENU_AS.has(node.as)) {\n const entries = tidy(groupRows(ctx, node, path, inner));\n if (entries.length) {\n out.push({ kind: 'submenu', key: path, label: node.name, ...(node.icon ? { icon: node.icon } : {}), ...withAccess(node.access), entries });\n }\n } else {\n out.push(sep(`${path}/<`), ...groupRows(ctx, node, path, inner), sep(`${path}/>`));\n }\n }\n return out;\n}\n\n/** Drop leading, trailing, and doubled separators. */\nfunction tidy(entries: MenuEntry[]): MenuEntry[] {\n const out: MenuEntry[] = [];\n for (const e of entries) {\n if (e.kind === 'separator' && (!out.length || out[out.length - 1]!.kind === 'separator')) continue;\n out.push(e);\n }\n if (out[out.length - 1]?.kind === 'separator') out.pop();\n return out;\n}\n\n/**\n * Draw a prefs schema as menu entries. Action leaves become items from the\n * registry (one per variant for a parametric action), an `actions` leaf one\n * item per action in its group, a boolean a checked item, an enum radio\n * rows, and a number and a string a row edited in place (all through `src.values`/`src.onChange`);\n * a color shows as a swatch, read-only, and so does a string as a disabled row when it is a readout\n * or nothing writes it. A group drawn `as` a\n * `menu`, `page`, `tab`, or `panel` is a submenu, and any other group's rows\n * sit inline between separators. Paint, field, compound, and app-defined leaves are left out.\n * `at` is the world point the menu was opened at and reaches `enabled` and\n * every action's params; `params` go to every action, under its own.\n */\nexport function resolveSchemaMenu(\n schema: PrefGroup,\n src: MenuSources,\n at?: Point,\n params?: Record<string, unknown>,\n): MenuEntry[] {\n const values = src.values;\n const ctx: Ctx = {\n src,\n byId: new Map(src.actions().map((a) => [a.id, a])),\n root: schema,\n read: values ? (path, from) => (from === 'item' ? undefined : values(path)) : undefined,\n at,\n params,\n };\n return tidy(groupRows(ctx, schema, '', ROOT));\n}\n\n/** Turn a declared menu into model entries; see {@link resolveSchemaMenu}. */\nexport function resolveMenu(\n def: MenuDef,\n src: MenuSources,\n at?: Point,\n params?: Record<string, unknown>,\n): MenuEntry[] {\n return resolveSchemaMenu(def.menu, src, at, params);\n}\n","import type { MenuEntry, MenuSide, Rect } from '@weasel-js/menu';\nimport { mergeMenuDefs, pickMenu } from './pickMenu';\nimport { resolveMenu, type MenuSources } from './resolveMenu';\nimport type { MenuDef, MenuHit, OwnedMenuDef } from './types';\nimport type { Point } from '@weasel-js/geom';\n\n/** Ask to open a menu: by id (chrome) or by what was hit (canvas). */\nexport interface MenuOpenRequest {\n menu?: string;\n hit?: MenuHit;\n /** Viewport point the menu is placed at, unless `under` is set. */\n client: Point;\n /** Viewport rect of the button the menu hangs from: placed below it, or above when below does not fit. */\n under?: Rect;\n /** With `under`: the side of the button it opens on when it fits there, flipping to the opposite side when it does not.\n * Default below. The canvas HUD menu host places below only and ignores it. */\n side?: MenuSide;\n /** World point, passed to `enabled` and to every item. */\n world?: Point;\n params?: Record<string, unknown>;\n source?: 'pointer' | 'keyboard';\n}\n\n/** The menu on screen. `seq` changes on every open, so a renderer remounts. */\nexport interface OpenMenu {\n seq: number;\n entries: readonly MenuEntry[];\n client: Point;\n under?: Rect;\n /** `MenuOpenRequest.side`, carried to the renderer. */\n side?: MenuSide;\n world?: Point;\n source: 'pointer' | 'keyboard';\n}\n\n/** Holds the declared menus and the one open menu. */\nexport interface MenuHost {\n /** Declare a menu; `owner` is a tool id, or `null` for always. Returns a release. */\n define(def: MenuDef, owner?: string | null): () => void;\n /** Pick, resolve and show. False when nothing matched or nothing resolved. */\n open(req: MenuOpenRequest): boolean;\n /** Whether `open(req)` would show anything. Changes no state and notifies no one. */\n has(req: MenuOpenRequest): boolean;\n close(): void;\n current(): OpenMenu | null;\n subscribe(fn: () => void): () => void;\n}\n\n/** Creates the host that decides which context menu is open, from the menus registered to it. */\nexport function createMenuHost(src: MenuSources & { activeTool(): string | null }): MenuHost {\n const defs: OwnedMenuDef[] = [];\n const listeners = new Set<() => void>();\n let open: OpenMenu | null = null;\n let seq = 0;\n const emit = () => { for (const fn of listeners) fn(); };\n\n const close = () => {\n if (!open) return;\n open = null;\n emit();\n };\n\n const resolve = (req: MenuOpenRequest): readonly MenuEntry[] => {\n const live = mergeMenuDefs(defs, src.activeTool());\n const def = req.menu !== undefined\n ? live.find((d) => d.id === req.menu)\n : req.hit ? pickMenu(live, req.hit) : undefined;\n return def ? resolveMenu(def, src, req.world, req.params) : [];\n };\n\n return {\n define(def, owner = null) {\n const entry = { def, owner };\n defs.push(entry);\n return () => {\n const i = defs.indexOf(entry);\n if (i >= 0) defs.splice(i, 1);\n };\n },\n open(req) {\n const entries = resolve(req);\n if (!entries.length) {\n close();\n return false;\n }\n open = {\n seq: ++seq, entries, client: req.client, world: req.world,\n ...(req.under ? { under: req.under } : {}),\n ...(req.side ? { side: req.side } : {}),\n source: req.source ?? 'pointer',\n };\n emit();\n return true;\n },\n has: (req) => resolve(req).length > 0,\n close,\n current: () => open,\n subscribe(fn) {\n listeners.add(fn);\n return () => { listeners.delete(fn); };\n },\n };\n}\n"]}