@weasel-js/routing 1.10.1 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/interactions/actions/activeToolContext.tsx","../src/interactions/actions/depRegistry.tsx","../src/tools/useToolLifecycle.ts","../src/interactions/dispatcher/dispatchCore.ts","../src/interactions/dispatcher/dispatcherWatch.ts","../src/interactions/dispatcher/underPointer.ts","../src/interactions/dispatcher/channels/contextMenu.ts","../src/interactions/dispatcher/channels/hoverCursor.ts","../src/interactions/dispatcher/channels/ingest.ts","../src/interactions/dispatcher/channels/keyboard.ts","../src/interactions/dispatcher/channels/listeners.ts","../src/interactions/dispatcher/channels/pointer.ts","../src/interactions/dispatcher/channels/webkitPinch.ts","../src/interactions/dispatcher/channels/wheel.ts","../src/interactions/dispatcher/attachInput.ts","../src/interactions/dispatcher/useGestureDispatcher.tsx","../src/interactions/actions/ActionsProvider.tsx","../src/interactions/actions/inputScope.tsx","../src/interactions/actions/useOngoingAction.ts","../src/ambient/PointerContext.tsx","../src/ambient/SelectionContext.tsx","../src/contributions/useContributions.ts","../src/tools/useTools.ts"],"names":["createContext","useState","jsx","useContext","useLatest","useEffect","useRef","useCallback","useMemo","useSyncExternalStore","Fragment","useStableByContent","sameList"],"mappings":";;;;;;;;;AA+CO,IAAM,QAAA,GAAN,cAAuB,SAAA,CAAoB;AAAA,EACxC,KAAA;AAAA,EACA,KAAA,GAAkF,IAAA;AAAA,EAE1F,WAAA,CAAY,MAAA,EAAyB,QAAA,EAAmB,IAAA,EAAe,aAAA,EAA8B;AACnG,IAAA,KAAA,CAAM,QAAQ,QAAQ,CAAA;AAGtB,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA,GACT,EAAE,MAAA,EAAQ,iBAAiB,MAAA,EAAQ,KAAA,EAAM,CAAE,KAAA,EAAO,MAAA,IAAU,IAAA,EAAM,WAAA,EAAa,I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AU;AAAA,EAChB,CAAA,EAAG,CAAC,GAAA,EAAK,SAAS,CAAC,CAAA;AAGnB,EAAA,MAAM,GAAA,GAAMA,WAAAA;AAAA,IACV,CAAC,EAAA,KACC,EAAA,IAAM,OAAA,CAAQ,QAAA,IACX,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,EAAA,KAAO,EAAE,CAAA;AAAA,IAC5C,CAAC,OAAO;AAAA,GACV;AAIA,EAAA,MAAM,SAAS,aAAA,CAAc,OAAA;AAC7B,EAAA,MAAM,oBAAoB,aAAA,CAAc,QAAA;AACxC,EAAA,OAAOC,OAAAA;AAAA,IACL,OAAO;AAAA,MACL,MAAA;AAAA,MACA,SAAA;AAAA,MACA,aAAA;AAAA,MACA,YAAA;AAAA,MACA,eAAA;AAAA,MACA,SAAS,OAAA,CAAQ,OAAA;AAAA,MACjB,UAAU,OAAA,CAAQ,QAAA;AAAA,MAClB,GAAA;AAAA,MACA;AAAA,KACF,CAAA;AAAA,IACA,CAAC,QAAQ,SAAA,EAAW,aAAA,EAAe,cAAc,eAAA,EAAiB,GAAA,EAAK,mBAAmB,OAAO;AAAA,GACnG;AACF","file":"react.js","sourcesContent":["/**\n * ActiveToolContext — the currently active tool id and a hotkey stack (tools\n * held active temporarily, e.g. space-for-hand).\n *\n * The state hangs on the same scope tree as the actions and dep registries:\n * every canvas's input scope owns a tool of its own unless it joins a yoke,\n * and a provider above reads and writes the tool of the scope last used.\n */\n\nimport {\n createContext,\n useContext,\n useMemo,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { ScopeNode } from './scopeNode';\n\n/** Which tool is active, plus the stack of tools temporarily held active by a\n * hotkey (space-for-hand and the like). The dispatcher reads this to decide\n * whose bindings are in scope. */\nexport interface ActiveToolContextValue {\n /** The focused tool's id, or `null` when no tool holds the active slot —\n * a canvas can run on ambient bindings alone. */\n active: string | null;\n hotkeyStack: string[];\n setActive(id: string | null): void;\n pushHotkey(id: string): void;\n /**\n * Disengage a hotkey-held tool. With `id`, removes that tool's own entry\n * wherever it now sits — holds do not have to come up in the order they went\n * down, and popping the top would disengage a tool whose key is still held.\n * With no id, pops the top.\n */\n popHotkey(id?: string): void;\n}\n\ninterface ToolState {\n active: string | null;\n hotkeyStack: string[];\n}\n\n/**\n * One node of the tool tree. A node that `owns` a tool holds its state; one\n * that does not — a scope inside a yoke — reads and writes its yoke's.\n */\nexport class ToolNode extends ScopeNode<ToolNode> {\n private state: ToolState | null;\n private value: { from: ToolNode; state: ToolState; out: ActiveToolContextValue } | null = null;\n\n constructor(parent: ToolNode | null, descends: boolean, owns: boolean, initialActive: string | null) {\n super(parent, descends);\n // A new scope starts on the tool in effect around it, so a tool a\n // consumer seeded above a canvas before it mounted is not lost.\n this.state = owns\n ? { active: initialActive ?? parent?.owner().state?.active ?? null, hotkeyStack: [] }\n : null;\n }\n\n /** The node whose tool a read here resolves to. */\n owner(): ToolNode {\n for (const n of this.start().chain()) if (n.state) return n;\n return this;\n }\n\n private update(next: (s: ToolState) => ToolState): void {\n const owner = this.owner();\n if (!owner.state) return;\n const updated = next(owner.state);\n if (updated === owner.state) return;\n owner.state = updated;\n owner.changed();\n }\n\n /** A stable value per owner and state, for `useSyncExternalStore`. */\n snapshot(): ActiveToolContextValue {\n const from = this.owner();\n const state = from.state ?? { active: null, hotkeyStack: [] };\n const cached = this.value;\n if (cached && cached.from === from && cached.state === state) return cached.out;\n const out: ActiveToolContextValue = {\n active: state.active,\n hotkeyStack: state.hotkeyStack,\n setActive: (id) => this.update((s) => (s.active === id ? s : { ...s, active: id })),\n pushHotkey: (id) => this.update((s) => ({ ...s, hotkeyStack: [...s.hotkeyStack, id] })),\n popHotkey: (id) =>\n this.update((s) => {\n const stack = s.hotkeyStack;\n if (stack.length === 0) return s;\n if (id === undefined) return { ...s, hotkeyStack: stack.slice(0, -1) };\n const i = stack.lastIndexOf(id);\n return i === -1 ? s : { ...s, hotkeyStack: [...stack.slice(0, i), ...stack.slice(i + 1)] };\n }),\n };\n this.value = { from, state, out };\n return out;\n }\n\n subscribe = (listener: () => void): (() => void) => this.tree.listeners.subscribe(listener);\n}\n\nconst ActiveToolContext = createContext<ToolNode | null>(null);\n\n/** @internal The context `<InputScope>` and `<Yoke>` provide a tool node through. */\nexport const ActiveToolNodeContext = ActiveToolContext;\n\n/** Props for `<ActiveToolContextProvider>`. */\nexport interface ActiveToolContextProviderProps {\n children: ReactNode;\n /** Seeds the active slot, and wins over the first `useTools` call's\n * `active`. Omitted, the slot starts empty and that call seeds it. */\n initialActive?: string | null;\n}\n\n/** Provides root active-tool state. Every canvas below has a tool of its own;\n * reads and writes here reach the one last used. */\nexport function ActiveToolContextProvider({\n children,\n initialActive = null,\n}: ActiveToolContextProviderProps) {\n const [node] = useState(() => new ToolNode(null, true, true, initialActive));\n return <ActiveToolContext.Provider value={node}>{children}</ActiveToolContext.Provider>;\n}\n\nfunction useNodeValue(node: ToolNode | null): ActiveToolContextValue | null {\n const subscribe = useMemo(() => node?.subscribe ?? NO_SUBSCRIBE, [node]);\n return useSyncExternalStore(\n subscribe,\n () => node?.snapshot() ?? null,\n () => node?.snapshot() ?? null,\n );\n}\n\nconst NO_SUBSCRIBE = (): (() => void) => () => {};\n\n/** The active-tool state in scope. Throws outside a provider; use\n * `useOptionalActiveToolContext` where one is not guaranteed. */\nexport function useActiveToolContext(): ActiveToolContextValue {\n const value = useNodeValue(useContext(ActiveToolContext));\n if (value === null) {\n throw new Error(\n 'useActiveToolContext: no ActiveToolContextProvider in scope. Wrap your tree with <ActiveToolContextProvider> (typically inside <SceneCanvas>).',\n );\n }\n return value;\n}\n\n/**\n * Like `useActiveToolContext`, but returns `null` when no\n * `<ActiveToolContextProvider>` is in scope instead of throwing.\n */\nexport function useOptionalActiveToolContext(): ActiveToolContextValue | null {\n return useNodeValue(useContext(ActiveToolContext));\n}\n\n/**\n * Mounts an `<ActiveToolContextProvider>` only when no parent provider is in\n * scope; otherwise renders children unwrapped.\n */\nexport function ActiveToolContextProviderIfRoot({\n children,\n}: {\n children: ReactNode;\n}) {\n const parent = useContext(ActiveToolContext);\n if (parent !== null) return <>{children}</>;\n return <ActiveToolContextProvider>{children}</ActiveToolContextProvider>;\n}\n","/** The React seam over the dep registry in `./depNode`: its provider and hooks. */\nimport {\n createContext, useContext, useEffect, useState,\n type ReactNode,\n} from 'react';\nimport type { DepSchema, DepName } from '../../index';\nimport { createDepRegistry, type DepRegistry } from './depNode';\nimport { useLatest } from '@weasel-js/react';\n\nexport type { DepSchema, DepName, DepRegistry };\nexport { DepNode, depNodeOf, createDepRegistry } from './depNode';\n\n/** @internal The context `<InputScope>` provides a scope's dep registry through. */\nexport const DepRegistryContext = createContext<DepRegistry | null>(null);\n\n/** Provides the dep registry for a canvas. `<SceneCanvas>` mounts one; a\n * consumer registering its own dep sources must be inside it. */\nexport function DepRegistryProvider({ children }: { children: ReactNode }) {\n const [registry] = useState(createDepRegistry);\n return <DepRegistryContext.Provider value={registry}>{children}</DepRegistryContext.Provider>;\n}\n\n/** The dep registry in scope. Throws outside a `<DepRegistryProvider>`. */\nexport function useDepRegistry(): DepRegistry {\n const r = useContext(DepRegistryContext);\n if (r === null) {\n throw new Error('useDepRegistry: no DepRegistryProvider in scope. Wrap your tree with <DepRegistryProvider> (typically inside <SceneCanvas>).');\n }\n return r;\n}\n\n/**\n * Like `useDepRegistry`, but returns `null` when no `<DepRegistryProvider>` is\n * in scope instead of throwing. Used by `useStandardActions` to preserve its\n * silent-no-op contract when neither provider is present.\n */\nexport function useOptionalDepRegistry(): DepRegistry | null {\n return useContext(DepRegistryContext);\n}\n\n/** Register a live source for `name` for the lifetime of the calling\n * component. The `source` thunk is called at dispatch time and should\n * return the latest value. */\nexport function useDepSource<K extends DepName>(name: K, source: () => DepSchema[K]) {\n const registry = useDepRegistry();\n const sourceRef = useLatest(source);\n useEffect(() => {\n return registry.register(name, () => sourceRef.current());\n }, [name, registry, sourceRef]);\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { Contribution } from '../contributions/types';\nimport { isTool } from './types';\n\nexport interface ToolLifecycleOptions {\n entriesById: ReadonlyMap<string, Contribution<unknown>>;\n /** The active tool's id, and the tools held on a hotkey, as the input scope reports them. */\n active: string | null;\n hotkeyStack: readonly string[];\n /** The active tool changed away from a tool. Not called when an empty slot is first filled. */\n onSwitch?: () => void;\n}\n\n/**\n * Runs each tool's `onActivate` / `onDeactivate` around the time it is live:\n * holding the active slot, or sitting in the hotkey stack.\n *\n * `onSwitch` runs between the outgoing tools' `onDeactivate` and the incoming\n * tools' `onActivate`, so whatever it ends is over before the new tool hears\n * it is live.\n */\nexport function useToolLifecycle(opts: ToolLifecycleOptions): void {\n const { active, hotkeyStack } = opts;\n const liveRef = useRef<ReadonlySet<string>>(new Set());\n const prevActiveRef = useRef(active);\n const entriesRef = useLatest(opts.entriesById);\n const onSwitchRef = useLatest(opts.onSwitch);\n\n const fire = useCallback((id: string, hook: 'onActivate' | 'onDeactivate'): void => {\n const tool = entriesRef.current.get(id);\n if (!tool || !isTool(tool)) return;\n const fn = tool[hook];\n if (!fn) return;\n try {\n fn();\n } catch (err) {\n console.error(`weasel: tool \"${id}\".${hook} threw`, err);\n }\n }, [entriesRef]);\n\n useEffect(() => {\n const prev = liveRef.current;\n const next = new Set<string>(active === null ? hotkeyStack : [active, ...hotkeyStack]);\n liveRef.current = next;\n for (const id of prev) if (!next.has(id)) fire(id, 'onDeactivate');\n // An empty slot being seeded has no outgoing tool, so nothing to end.\n if (prevActiveRef.current !== null && prevActiveRef.current !== active) onSwitchRef.current?.();\n prevActiveRef.current = active;\n for (const id of next) if (!prev.has(id)) fire(id, 'onActivate');\n });\n\n useEffect(() => () => {\n const live = liveRef.current;\n liveRef.current = new Set();\n for (const id of live) fire(id, 'onDeactivate');\n }, [fire]);\n}\n","/**\n * The routing core every input channel of `useGestureDispatcher` shares: which\n * view an event belongs to, that view's dispatcher and context, and the one\n * `dispatch` every channel sends through.\n */\nimport type { DepName, DepSchema } from '../../index';\nimport { clientToCanvas } from '../../viewport/clientToCanvas';\nimport type { DepRegistry } from '../actions/depRegistry';\nimport type { ActionsRegistry } from '../actions/registry';\nimport type { Dispatcher, DispatcherContext } from './dispatcherApi';\nimport type { DispatcherViewTarget, UseGestureDispatcherOptions } from './gestureDispatcherOptions';\nimport type { InputEvent } from './matcher';\n\n/** What a channel reads and calls. Every member is a closure over the\n * hook's effect, so a channel may destructure it. */\nexport interface DispatchCore {\n readonly canvas: HTMLElement | null;\n /** The dispatch record for the routed view. */\n target(): DispatcherViewTarget;\n /** Route an event with coordinates. `pointerId` is `null` for input with\n * nothing to capture: wheel, hover, contextmenu, drop. */\n routeAt(pointerId: number | null, clientX: number, clientY: number): void;\n /** The routed view's id, and a way to put one back: an event that\n * dispatches later runs on the view it landed in. */\n routedView(): string | null;\n setRoutedView(id: string | null): void;\n dispatcherNow(): Dispatcher;\n ctxNow(): DispatcherContext;\n /** Client point to the routed view's world point. */\n toWorld(clientX: number, clientY: number): { x: number; y: number };\n /** Client point to CSS pixels from the canvas's top-left, the space `zoomAt`\n * anchors in and a `space: 'screen'` layer draws in. Unchanged with no canvas. */\n toCanvasLocal(clientX: number, clientY: number): { x: number; y: number };\n /** Dispatch on the routed view's dispatcher, or on `on` for an event that\n * belongs to the one an earlier event ran on. */\n dispatch(ev: InputEvent, on?: Dispatcher): 'handled' | 'unhandled';\n /** Whether a key or a paste that reached the page is this dispatcher's to\n * handle: its canvas was the last one pressed or scrolled in, or it has no\n * canvas and its input scope is the active one. */\n holdsKeys(): boolean;\n /** Make this canvas's input scope the active one. */\n activate(): void;\n /** Whether the hook's effect has been torn down. */\n disposed(): boolean;\n}\n\n/** The pointer channel's core: a pointer stays pinned to the view it went down in. */\nexport interface PointerDispatchCore extends DispatchCore {\n /** Route a pointerdown, pinning the pointer to the view it landed in. */\n routeDown(pointerId: number, clientX: number, clientY: number): void;\n /** Unpin a pointer whose release or cancel has been dispatched in full. */\n routeRelease(pointerId: number): void;\n}\n\n/** What a core reads. Each is a thunk over the hook's latest render, except\n * `canvas`, which is fixed for the life of a listener set. */\nexport interface DispatchCoreSources {\n canvas: HTMLElement | null;\n /** The record the hook's flat options describe: view zero. */\n root(): DispatcherViewTarget;\n views(): UseGestureDispatcherOptions['views'];\n /** The dispatcher context, less the parts that depend on the routed view. */\n context(): DispatcherContext;\n actions(): ActionsRegistry;\n /** Told of the dispatcher each event is about to run on. A view's appears\n * with no render of the hook, so this is where one is first seen. */\n uses(dispatcher: Dispatcher): void;\n disposed(): boolean;\n}\n\nexport function createDispatchCore(src: DispatchCoreSources): PointerDispatchCore {\n const { canvas } = src;\n // An id rather than a record: the record is rebuilt every render, so holding\n // one across events would dispatch through last render's lookups.\n let routedId: string | null = null;\n\n const target = (): DispatcherViewTarget => {\n if (routedId === null) return src.root();\n // A resolved id with no live record falls back to the root.\n return src.views()?.targets().find((t) => t.id === routedId) ?? src.root();\n };\n const dispatcherNow = (): Dispatcher => target().dispatcher;\n const routedDeps = withViewDeps(() => src.context().depRegistry, () => target().deps?.());\n const routedRuleCtx = (): ReturnType<NonNullable<DispatcherViewTarget['getRuleCtx']>> =>\n target().getRuleCtx?.();\n const ctxNow = (): DispatcherContext => ({\n ...src.context(), depRegistry: routedDeps, getRuleCtx: routedRuleCtx, viewId: target().id,\n });\n\n return {\n canvas,\n target,\n routeAt: (pointerId, clientX, clientY) => {\n routedId = src.views()?.resolver.at(pointerId, clientX, clientY).id ?? null;\n },\n routeDown: (pointerId, clientX, clientY) => {\n routedId = src.views()?.resolver.begin(pointerId, clientX, clientY).id ?? null;\n },\n routeRelease: (pointerId) => { src.views()?.resolver.end(pointerId); },\n routedView: () => routedId,\n setRoutedView: (id) => { routedId = id; },\n dispatcherNow,\n ctxNow,\n toWorld: (cx, cy) => {\n const fn = target().clientToWorld;\n return fn ? fn(cx, cy) : { x: cx, y: cy };\n },\n toCanvasLocal: (cx, cy) => {\n if (!canvas) return { x: cx, y: cy };\n const [x, y] = clientToCanvas(canvas, cx, cy);\n return { x, y };\n },\n dispatch: (ev, on) => {\n const d = on ?? dispatcherNow();\n src.uses(d);\n return d.handleInput(ev, ctxNow());\n },\n holdsKeys: () => (canvas ? src.actions().holdsKeys() : src.actions().isActive()),\n activate: () => src.actions().activate(),\n disposed: src.disposed,\n };\n}\n\n/**\n * `base` with the routed view's own deps in front of it. Both sides are read\n * through thunks, so the result is stable for the life of a listener set while\n * still answering for whichever view the current event landed in.\n */\nexport function withViewDeps(\n base: () => DepRegistry,\n overlay: () => Partial<DepSchema> | undefined,\n): DepRegistry {\n return {\n register: (name, source) => base().register(name, source),\n get: <K extends DepName>(name: K): DepSchema[K] | undefined => {\n const own = overlay()?.[name];\n if (own !== undefined) return own as DepSchema[K];\n return base().get(name);\n },\n };\n}\n","import type { Dispatcher } from './dispatcherApi';\n\n/** One subscription per live dispatcher. */\nexport interface DispatcherWatch {\n /** Subscribe to each of `live` not yet watched, and drop any no longer among them. */\n sync(live: readonly Dispatcher[]): void;\n stop(): void;\n}\n\n/** Calls `onChange` whenever a watched dispatcher notifies: an event or a\n * cancel that found or left a gesture in flight. */\nexport function dispatcherWatch(onChange: () => void): DispatcherWatch {\n const subscriptions = new Map<Dispatcher, () => void>();\n return {\n sync(live) {\n for (const d of live) {\n if (!subscriptions.has(d)) subscriptions.set(d, d.subscribe(onChange));\n }\n if (subscriptions.size === live.length) return;\n const keep = new Set(live);\n for (const [d, unsubscribe] of subscriptions) {\n if (keep.has(d)) continue;\n unsubscribe();\n subscriptions.delete(d);\n }\n },\n stop() {\n for (const unsubscribe of subscriptions.values()) unsubscribe();\n subscriptions.clear();\n },\n };\n}\n","import type { BodyKind, BodyTarget, EventModifiers } from '@weasel-js/gestures';\nimport type { AffordanceHit } from '../actions/invoker';\nimport type { DispatcherViewTarget } from './gestureDispatcherOptions';\n\n/** The modifiers held and what sits under the pointer, as a pointer event carries them. */\nexport type UnderPointer = EventModifiers & {\n affordance?: AffordanceHit;\n bodyTarget?: BodyTarget;\n bodyKind?: BodyKind;\n};\n\n/** Hit-test `view` at the world point `w`, for a pointer holding `mods`. */\nexport function underPointer(view: DispatcherViewTarget, mods: EventModifiers, w: { x: number; y: number }): UnderPointer {\n const affordance = view.affordanceAt?.(w) ?? undefined;\n const body = view.classifyTarget?.(w);\n return {\n altKey: mods.altKey, ctrlKey: mods.ctrlKey, metaKey: mods.metaKey, shiftKey: mods.shiftKey,\n ...(affordance !== undefined ? { affordance } : {}),\n ...(body?.body !== undefined ? { bodyTarget: body.body } : {}),\n ...(body?.kind !== undefined ? { bodyKind: body.kind } : {}),\n };\n}\n","/** The contextmenu channel: a right-click. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\n/**\n * `takeNativeHold` answers whether a touch or pen hold is in progress, firing\n * its long-press if that is still pending. A browser that sends `contextmenu`\n * for a hold (Android Chrome) is reporting the same hold the dispatcher times,\n * so the event stands for the long-press and never dispatches a second menu.\n */\nexport function contextMenuInput(core: DispatchCore, takeNativeHold: () => boolean): (e: MouseEvent) => void {\n const { routeAt, toWorld, target, dispatch } = core;\n\n const onContextMenu = (e: MouseEvent) => {\n // Suppress native menu so tools/actions own the right-click UX.\n e.preventDefault();\n if (takeNativeHold()) return;\n routeAt(null, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n // A secondary button never reaches `onPointerDown`, so unlike click and\n // long-press there is no press to replay the classification from.\n const ev: InputEvent = {\n kind: 'contextmenu',\n target: e.target,\n x: w.x,\n y: w.y,\n clientX: e.clientX,\n clientY: e.clientY,\n ...underPointer(target(), e, w),\n };\n dispatch(ev);\n };\n\n return onContextMenu;\n}\n","/**\n * The hover half of the pointer channel: a `hover` event for each move of an\n * unpressed pointer, and the cursor shown for what a press there would do.\n */\nimport { createCursorSink, resolveCursorTier, type CursorSink, type CursorSpec, type PaintedCursorState } from '@weasel-js/cursor';\nimport type { EventModifiers, HoverWhere } from '@weasel-js/gestures';\nimport type { DispatchCore } from '../dispatchCore';\nimport { DEV, publishLiveDispatch } from '../dispatchTrace';\nimport type { InputEvent } from '../matcher';\nimport { underPointer, type UnderPointer } from '../underPointer';\n\ntype Hover = EventModifiers & { clientX: number; clientY: number };\n\nconst whereOf = ({ affordance, bodyTarget, bodyKind }: UnderPointer): HoverWhere => ({\n ...(affordance !== undefined ? { affordance } : {}),\n ...(bodyTarget !== undefined ? { bodyTarget } : {}),\n ...(bodyKind !== undefined ? { bodyKind } : {}),\n});\n\nconst hoverOf = (e: Hover): Hover => ({\n clientX: e.clientX, clientY: e.clientY,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n});\n\nexport interface HoverCursorInput {\n /** A pointer moved, and its move has been dispatched. */\n moved(e: PointerEvent): void;\n /** A pointer was released: re-resolve where it let go. */\n released(e: PointerEvent): void;\n onLeave(): void;\n /** A modifier or hotkey changed, which re-routes the predicted drag with no pointer movement. */\n onKey(e: KeyboardEvent): void;\n clear(): void;\n}\n\n/**\n * Idle, the cursor is the first of: an affordance hit's `cursor`; the\n * `Action.cursor` of the action a drag from here would route to; that of the\n * action a click here would route to; no override. Mid-gesture it is the\n * in-flight action's `activeCursor`.\n */\nexport function hoverCursorInput(\n core: DispatchCore,\n paintedCursor: () => PaintedCursorState | undefined,\n /** Pointers down on the canvas with any button, `heldPointers`' count. */\n pointersHeld: () => number,\n /** The surface's own sink, which also holds its tool cursor. Without one\n * the override is written to the canvas and removed when it clears. */\n cursorSink: () => CursorSink | undefined = () => undefined,\n): HoverCursorInput {\n const { canvas, routeAt, toWorld, target, dispatch, dispatcherNow, ctxNow } = core;\n const ownSink = createCursorSink({ element: () => canvas, painted: paintedCursor });\n const override = {\n apply: (spec: CursorSpec | null): void =>\n (cursorSink() ?? ownSink).setOverride(spec === null ? null : resolveCursorTier(spec)),\n clear: (): void => (cursorSink() ?? ownSink).setOverride(null),\n };\n let last: Hover | null = null;\n /** What the last move found under the pointer, so its hover and its cursor hit-test once. */\n let facts: { at: Hover; where: UnderPointer } | null = null;\n\n const resolve = (): void => {\n if (!canvas || !last) return;\n if (pointersHeld() > 0 || dispatcherNow().inFlight().size > 0) {\n override.apply(dispatcherNow().inFlightCursor());\n return;\n }\n const h = last;\n // Only idle: mid-gesture the branch above returned, so a pinned pointer\n // is never unpinned by a hover refresh.\n routeAt(null, h.clientX, h.clientY);\n const w = toWorld(h.clientX, h.clientY);\n const where = facts?.at === h ? facts.where : underPointer(target(), h, w);\n if (where.affordance?.cursor) {\n override.apply(where.affordance.cursor);\n return;\n }\n const ctx = ctxNow();\n const d = dispatcherNow();\n const press: InputEvent = { kind: 'pointerdown', x: w.x, y: w.y, clientX: h.clientX, clientY: h.clientY, ...where };\n if (DEV) publishLiveDispatch(() => d.explain(press, ctx));\n const click: InputEvent = { kind: 'click', x: w.x, y: w.y, pressX: w.x, pressY: w.y, ...where };\n const cursor = d.resolveOnly(press, ctx)?.action.cursor ?? dispatcherNow().resolveOnly(click, ctx)?.action.cursor;\n override.apply(cursor ?? null);\n };\n\n const refresh = (): void => {\n resolve();\n // After the cursor is resolved, not before: on the move that first selects\n // a painted cursor, a position written ahead of the decision is discarded.\n // Guarded on `active()`, so a CSS cursor costs no layout read per move.\n const painted = paintedCursor();\n if (!painted?.active() || !canvas || !last) return;\n const local = core.toCanvasLocal(last.clientX, last.clientY);\n painted.setPointer(local.x, local.y);\n };\n // A tick later, so state the event changed (hotkey stack, active tool,\n // selection) has committed before the prediction reruns.\n const refreshSoon = (): void => {\n setTimeout(() => { if (!core.disposed()) refresh(); }, 0);\n };\n\n return {\n moved(e) {\n last = hoverOf(e);\n // A held pointer's moves are its drag's; an unpressed one's are a hover.\n if (pointersHeld() === 0) {\n const w = toWorld(e.clientX, e.clientY);\n const where = underPointer(target(), last, w);\n const from = facts ? { from: whereOf(facts.where) } : {};\n facts = { at: last, where };\n dispatch({ kind: 'hover', x: w.x, y: w.y, clientX: e.clientX, clientY: e.clientY, ...where, ...from });\n }\n refresh();\n },\n released(e) {\n last = hoverOf(e);\n refreshSoon();\n },\n onLeave() {\n if (facts) {\n const { at, where } = facts;\n const w = toWorld(at.clientX, at.clientY);\n dispatch({ kind: 'hover', off: true, x: w.x, y: w.y, clientX: at.clientX, clientY: at.clientY, ...where, from: whereOf(where) });\n }\n facts = null;\n last = null;\n if (DEV) publishLiveDispatch(null);\n paintedCursor()?.clearPointer();\n override.clear();\n },\n onKey(e) {\n if (!last) return;\n last = { ...last, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey };\n refreshSoon();\n },\n clear: override.clear,\n };\n}\n","/**\n * External-content ingestion: an OS drop on the canvas, a paste on window.\n * Items are materialized during the event, since a DataTransfer is only live\n * on the event stack; dispatch happens when materialization resolves.\n */\nimport { itemsFromClipboardData, itemsFromDataTransfer, itemTypesFromDataTransfer } from '../../../ingestion/ingestItems';\nimport { isEditableTarget } from '../../keyHelpers';\nimport type { DispatchCore } from '../dispatchCore';\n\n/** Toggled on the canvas while an OS drag hovers it; consumers style it. */\nexport const DROPOVER_CLASS = 'weasel-dropover';\n\nexport function ingestInput(core: DispatchCore): {\n onDragOver: (e: DragEvent) => void;\n onDragLeave: () => void;\n onDrop: (e: DragEvent) => void;\n onPaste: (e: ClipboardEvent) => void;\n} {\n const { canvas, routeAt, toWorld, dispatch } = core;\n\n // Attached to both dragover and dragenter: cancelling dragenter (WHATWG)\n // guarantees the element stays the active drop target and shows the copy\n // cursor on entry rather than waiting for the first dragover tick.\n const onDragOver = (e: DragEvent) => {\n const dt = e.dataTransfer;\n if (!dt) return;\n routeAt(null, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n const wanted = core.dispatcherNow().resolveOnly({\n kind: 'drop', items: itemTypesFromDataTransfer(dt),\n x: w.x, y: w.y, clientX: e.clientX, clientY: e.clientY,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n }, core.ctxNow()) !== null;\n canvas?.classList.toggle(DROPOVER_CLASS, wanted);\n // Left alone, a drag no binding would take stays the page's: no copy\n // cursor, and no `drop` event here to swallow.\n if (!wanted) return;\n e.preventDefault();\n dt.dropEffect = 'copy';\n };\n\n const onDragLeave = () => {\n canvas?.classList.remove(DROPOVER_CLASS);\n };\n\n // No stopPropagation: handled-ness is only known after the async\n // materialization microtask, so a conditional stop (wheel-style) is\n // impossible; an unconditional one would swallow drops the kit doesn't\n // dispatch. Callers that need exclusivity should gate on the action result.\n const onDrop = (e: DragEvent) => {\n canvas?.classList.remove(DROPOVER_CLASS);\n const dt = e.dataTransfer;\n if (!dt) return;\n e.preventDefault();\n routeAt(null, e.clientX, e.clientY);\n const dropView = core.routedView();\n const w = toWorld(e.clientX, e.clientY);\n // Real modifiers forwarded (Option-drag is a copy-drag on macOS); the\n // kit ingest binding declares all modifiers optional, so they can't\n // block the default route — but a consumer binding may key on them.\n const base = {\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n };\n void itemsFromDataTransfer(dt).then((items) => {\n if (core.disposed()) return;\n if (items.length === 0) return;\n // The routed view is whatever moved under the cursor since; the drop\n // runs on the one it landed in, dispatcher and context both.\n const routedNow = core.routedView();\n core.setRoutedView(dropView);\n try {\n dispatch({\n kind: 'drop', items,\n x: w.x, y: w.y, clientX: e.clientX, clientY: e.clientY,\n ...base,\n });\n } finally {\n core.setRoutedView(routedNow);\n }\n });\n };\n\n const onPaste = (e: ClipboardEvent) => {\n // Text-editing surfaces (inputs, the text-edit overlay) own their own\n // paste — never steal it for scene ingestion.\n if (e.defaultPrevented || isEditableTarget(e.target)) return;\n // Every dispatcher hears paste on window; only the one holding the keys acts.\n if (!core.holdsKeys()) return;\n const cd = e.clipboardData;\n if (!cd) return;\n const items = itemsFromClipboardData(cd);\n if (items.length === 0) return;\n // Wheel's shape: dispatch first, suppress the default only when a\n // binding claimed it. Clipboard items materialize synchronously, so\n // unlike `onDrop` the result is known while `preventDefault` is still\n // honored — and a paste no binding wanted stays the page's to handle.\n const result = dispatch({\n kind: 'paste', items,\n // ClipboardEvent carries no modifier state.\n altKey: false, ctrlKey: false, metaKey: false, shiftKey: false,\n });\n if (result === 'handled') e.preventDefault();\n };\n\n return { onDragOver, onDragLeave, onDrop, onPaste };\n}\n","/** The keyboard channel: window keydown and keyup as `key` and `key-held` input. */\nimport { focusedControlOwnsKey, isEditableTarget } from '../../keyHelpers';\nimport type { DispatchCore } from '../dispatchCore';\nimport type { Dispatcher } from '../dispatcherApi';\nimport type { InputEvent } from '../matcher';\n\n/**\n * True when AltGr typed the character `e` reports. A layout that types `[` with\n * AltGr reports Ctrl and Alt held with it, which are part of the keystroke\n * rather than a chord. A key that reports its own unshifted letter or digit\n * typed nothing through AltGr: Firefox on Windows reports AltGraph for a plain\n * Ctrl+Alt too, and that one is a chord.\n */\nfunction typedWithAltGraph(e: KeyboardEvent): boolean {\n if (!e.ctrlKey || !e.altKey || e.key.length !== 1 || !e.getModifierState?.('AltGraph')) return false;\n const base = /^(?:Key|Digit)(.)$/.exec(e.code)?.[1];\n return base === undefined || base.toLowerCase() !== e.key.toLowerCase();\n}\n\nexport function keyboardInput(core: DispatchCore): {\n onKeyDown: (e: KeyboardEvent) => void;\n onKeyUp: (e: KeyboardEvent) => void;\n /** End every held key, as a window that lost focus must: it never delivers the keyup. */\n releaseAll: () => void;\n} {\n const { dispatch, dispatcherNow } = core;\n\n // Held keys by physical key, mapped to the `key` they went down as (Shift\n // pressed mid-hold makes the keyup of an 'o' press report 'O') and the\n // dispatcher that took the down, which hover may have routed away from.\n const heldKeys = new Map<string, { key: string; code?: string; on: Dispatcher }>();\n const codeOf = (e: KeyboardEvent): { code?: string } => (e.code ? { code: e.code } : {});\n const physicalKey = (e: KeyboardEvent): string => e.code || e.key.toLowerCase();\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || isEditableTarget(e.target) || focusedControlOwnsKey(e)) return;\n // Every dispatcher hears keys on window; only the one holding them acts.\n if (!core.holdsKeys()) return;\n\n // Autorepeat for a key that's already engaged a key-held binding is\n // suppressed entirely — no dispatch (no trace flood) and the\n // browser default is blocked. Holding Space-for-hand otherwise\n // streamed an 'unhandled' immediate-`key` trace entry per repeat.\n // Autorepeat for a key that ISN'T held still dispatches normally,\n // so things like Cmd+= step-zoom keep auto-repeating.\n if (e.repeat && heldKeys.has(physicalKey(e))) {\n e.preventDefault();\n return;\n }\n\n if (press(e, { altKey: e.altKey, ctrlKey: e.ctrlKey })) return;\n // The chord as reported comes first, so a binding that names Ctrl+Alt keeps it.\n if (typedWithAltGraph(e)) press(e, { altKey: false, ctrlKey: false });\n };\n\n /** Dispatch `e` as both `key` and `key-held` with `mods` for its Alt and Ctrl. True when either was handled. */\n const press = (e: KeyboardEvent, mods: { altKey: boolean; ctrlKey: boolean }): boolean => {\n // Both forms dispatch unconditionally. The dispatcher\n // de-dupes naturally because each form uses a different gestureId and\n // different GestureSpec kind. The dispatcher returns 'unhandled' when no\n // binding matches the alternate form, so there's no double-fire risk.\n\n const keyEv: InputEvent = {\n kind: 'key',\n key: e.key,\n ...codeOf(e),\n ...mods,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n repeat: e.repeat,\n };\n const keyResult = dispatch(keyEv);\n\n // Always dispatch key-held DOWN, even on autorepeat. The dispatcher's\n // own defense returns 'handled' (no-op) when a handle is already in\n // flight for this gestureId, which both prevents start() re-invocation\n // and lets us preventDefault the repeat so the page doesn't react.\n const heldEv: InputEvent = {\n kind: 'key-held',\n key: e.key,\n ...codeOf(e),\n phase: 'down',\n ...mods,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n };\n const heldOn = dispatcherNow();\n const heldResult = dispatch(heldEv, heldOn);\n\n if (heldResult === 'handled') {\n heldKeys.set(physicalKey(e), { key: e.key, ...codeOf(e), on: heldOn });\n }\n\n const handled = keyResult === 'handled' || heldResult === 'handled';\n if (handled) e.preventDefault();\n return handled;\n };\n\n const onKeyUp = (e: KeyboardEvent) => {\n const physical = physicalKey(e);\n const down = heldKeys.get(physical);\n if (down === undefined) return;\n const ev: InputEvent = {\n kind: 'key-held',\n key: down.key,\n ...(down.code !== undefined ? { code: down.code } : {}),\n phase: 'up',\n altKey: e.altKey,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n };\n heldKeys.delete(physical);\n dispatch(ev, down.on);\n };\n\n const releaseAll = (): void => {\n const releasing = [...heldKeys.values()];\n heldKeys.clear();\n for (const { key, code, on } of releasing) {\n const ev: InputEvent = {\n kind: 'key-held',\n key,\n ...(code !== undefined ? { code } : {}),\n phase: 'up',\n altKey: false,\n ctrlKey: false,\n metaKey: false,\n shiftKey: false,\n };\n dispatch(ev, on);\n }\n };\n\n return { onKeyDown, onKeyUp, releaseAll };\n}\n","/** Listeners attached one by one and removed together. */\nexport interface ListenerSet {\n /** A missing target attaches nothing. */\n on<E extends Event>(\n target: EventTarget | null | undefined,\n type: string,\n listener: (e: E) => void,\n options?: boolean | AddEventListenerOptions,\n ): void;\n removeAll(): void;\n}\n\nexport function listenerSet(): ListenerSet {\n const removers: (() => void)[] = [];\n return {\n on(target, type, listener, options) {\n if (!target) return;\n target.addEventListener(type, listener as EventListener, options);\n removers.push(() => { target.removeEventListener(type, listener as EventListener, options); });\n },\n removeAll() {\n for (const remove of removers.splice(0)) remove();\n },\n };\n}\n","/**\n * The pointer channel: feeds each held pointer's events to the recognizer,\n * and does for it what needs a DOM — sessions, timers, haptics.\n */\nimport {\n createPointerRecognizer, isInControlWithin, longPressEvents, stylusOf,\n type ClickMemory, type HeldPress, type PointerSample, type RecognizerClock,\n} from '@weasel-js/gestures';\nimport { openPointerSession, type PointerSession } from '../../pointerSession';\nimport type { PointerDispatchCore } from '../dispatchCore';\nimport { multiTouchGestureId } from '../dispatcher';\nimport { LONG_PRESS_HAPTIC_MS, type LongPressOptions } from '../longPressState';\nimport { underPointer } from '../underPointer';\nimport type { HoverCursorInput } from './hoverCursor';\n\ntype WorldObserver = ((world: { x: number; y: number }) => void) | undefined;\n\n/** Read through thunks, so each answers for the hook's latest render. */\nexport interface PointerInputOptions {\n longPress(): LongPressOptions | undefined;\n onClick(): WorldObserver;\n onDoubleClick(): WorldObserver;\n /** Outlives this listener set: a re-bind between two clicks must not drop the double click. */\n clicks: ClickMemory;\n hover: Pick<HoverCursorInput, 'moved' | 'released'>;\n}\n\nexport interface PointerInput {\n onPointerDown(e: PointerEvent): void;\n /** The canvas's own `pointermove`, left with the unpressed half: a held\n * pointer's moves arrive through its session, which keeps seeing them once\n * the pointer has left the canvas. */\n onHoverMove(e: PointerEvent): void;\n onNativeDoubleClick(e: MouseEvent): void;\n /** Whether a touch or pen hold is in progress, firing its long-press if still pending. */\n takeNativeHold(): boolean;\n /** Cancel every held pointer, each through its session, which reports once. */\n cancelHeld(): void;\n /** Drop every held pointer and timer without dispatching. */\n dispose(): void;\n}\n\nconst sampleOf = (e: PointerEvent): PointerSample => ({\n pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, target: e.target,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n ...stylusOf(e),\n});\n\n/** Publishes the press being held, with whether holding it to the end would\n * fire anything: the two dispatches a long-press makes, predicted without invoking. */\nfunction holdPublisher(core: PointerDispatchCore, longPress: PointerInputOptions['longPress']) {\n return (pending: HeldPress | null): void => {\n const store = longPress()?.state;\n if (!store) return;\n if (!pending) {\n store.set(null);\n return;\n }\n const { press } = pending;\n const evs = longPressEvents(press);\n const d = core.dispatcherNow();\n store.set({\n pointerId: pending.pointerId,\n pointerType: pending.pointerType,\n client: { x: press.clientX, y: press.clientY },\n local: core.toCanvasLocal(press.clientX, press.clientY),\n world: { x: press.worldX, y: press.worldY },\n viewId: core.target().id,\n startedAt: pending.startedAt,\n duration: pending.duration,\n armed: d.resolveOnly(evs.longpress, core.ctxNow()) !== null\n || d.resolveOnly(evs.contextmenu, core.ctxNow()) !== null,\n });\n };\n}\n\n/**\n * The recognizer's clock. Its one timer is the long-press hold, armed inside\n * `press`, and other input routes elsewhere while that press is held: the hold\n * fires on the view its press went down in.\n */\nfunction holdClock(core: PointerDispatchCore): { clock: RecognizerClock; routeToPress(): void } {\n let holdView: { id: string | null } | null = null;\n return {\n clock: {\n now: () => performance.now(),\n setTimer: (fn, ms) => {\n const view = core.routedView();\n holdView = { id: view };\n return setTimeout(() => {\n holdView = null;\n core.setRoutedView(view);\n fn();\n }, ms);\n },\n clearTimer: (timer) => {\n holdView = null;\n clearTimeout(timer as ReturnType<typeof setTimeout>);\n },\n },\n routeToPress: () => { if (holdView) core.setRoutedView(holdView.id); },\n };\n}\n\nexport function pointerInput(core: PointerDispatchCore, opts: PointerInputOptions): PointerInput {\n const { canvas, routeAt, routeDown, routeRelease, toWorld, target } = core;\n const sessions = new Map<number, PointerSession>();\n // A double click this dispatcher acted on is spent: the browser's own\n // `dblclick` that follows is marked handled, so a container that opens or\n // toggles on double-click leaves it alone.\n let claimedDoubleClick = false;\n const hold = holdClock(core);\n\n const recognizer = createPointerRecognizer({\n sink: {\n dispatch: (ev) => core.dispatch(ev),\n multiTouchInFlight: (fingers) => core.dispatcherNow().inFlight().has(multiTouchGestureId(fingers)),\n },\n clock: hold.clock,\n toWorld,\n toSurface: (p) => core.toCanvasLocal(p.x, p.y),\n longPressMs: () => opts.longPress()?.duration,\n clicks: opts.clicks,\n observer: {\n click: (world) => { opts.onClick()?.(world); },\n doubleClick: (world) => { opts.onDoubleClick()?.(world); },\n holdChanged: holdPublisher(core, opts.longPress),\n longPress: () => {\n if (opts.longPress()?.haptics === false) return;\n if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') {\n navigator.vibrate(LONG_PRESS_HAPTIC_MS);\n }\n },\n },\n });\n\n const onMove = (e: PointerEvent): void => {\n routeAt(e.pointerId, e.clientX, e.clientY);\n recognizer.move(sampleOf(e));\n opts.hover.moved(e);\n };\n\n const onUp = (e: PointerEvent): void => {\n routeAt(e.pointerId, e.clientX, e.clientY);\n sessions.delete(e.pointerId);\n const { doubleClick } = recognizer.release(sampleOf(e));\n if (doubleClick) claimedDoubleClick = doubleClick === 'handled' || opts.onDoubleClick() !== undefined;\n // Everything this release synthesizes has been dispatched, so the pointer's view can be unpinned.\n routeRelease(e.pointerId);\n opts.hover.released(e);\n };\n\n // Every way a gesture ends without a release.\n const onCancel = (pointerId: number): void => {\n // On teardown every session is canceled at once, and `cancelAll` ends\n // those gestures: dispatching here would end them twice.\n if (core.disposed()) return;\n const at = recognizer.positionOf(pointerId);\n if (!at) return;\n sessions.delete(pointerId);\n routeAt(pointerId, at.x, at.y);\n recognizer.cancel(pointerId);\n routeRelease(pointerId);\n };\n\n return {\n onPointerDown(e) {\n claimedDoubleClick = false;\n // Only the primary button drives gesture dispatch; the others are left\n // for the consumer's own tools and the browser context menu. An absent\n // `button` (synthetic events) counts as primary.\n if ((e.button ?? 0) !== 0) return;\n if (!canvas) return;\n // A button or field laid over the canvas handles its own press: opening a\n // session here would capture the pointer and retarget its click.\n if (isInControlWithin(e.target, canvas)) return;\n routeDown(e.pointerId, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n const where = underPointer(target(), e, w);\n // The session owns the rest of this pointer: capture, the moves, the\n // release, and recovery from a release that never arrives. A press on a\n // pointer one is already open for cancels that stale gesture before this\n // handler runs: its `pointerdown` listener is on the document, in the\n // capture phase, ahead of this one on the canvas.\n sessions.set(e.pointerId, openPointerSession(canvas, e, {\n onMove, onEnd: onUp, onCancel: () => { onCancel(e.pointerId); },\n }));\n recognizer.press({ ...sampleOf(e), x: w.x, y: w.y, pointerType: e.pointerType, ...where });\n },\n onHoverMove(e) {\n if (!sessions.has(e.pointerId)) onMove(e);\n },\n onNativeDoubleClick(e) {\n if (!claimedDoubleClick) return;\n claimedDoubleClick = false;\n e.preventDefault();\n },\n takeNativeHold: () => {\n hold.routeToPress();\n return recognizer.takeHold();\n },\n cancelHeld() {\n for (const session of [...sessions.values()]) session.cancel();\n },\n dispose() {\n recognizer.reset();\n for (const session of sessions.values()) session.cancel();\n sessions.clear();\n },\n };\n}\n","/** The WebKit trackpad pinch channel: `gesturestart` / `gesturechange` / `gestureend` as `pinch` steps. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\nexport function webkitPinchInput(core: DispatchCore): {\n onGestureStart: (e: Event) => void;\n onGestureChange: (e: Event) => void;\n onGestureEnd: (e: Event) => void;\n /** Whether a claimed pinch is live, in which case it is the only driver. */\n live: () => boolean;\n end: () => void;\n} {\n const { canvas, routeAt, toWorld, target, dispatch, dispatcherNow, ctxNow } = core;\n\n // Set on a `gesturestart` some binding claims, cleared on its end. `scale`\n // and `rotation` on a GestureEvent are cumulative from the start; these\n // hold the previous sample's so each dispatched `pinch` is a step.\n let pinchLive = false;\n let pinchScale = 1;\n let pinchRotation = 0;\n\n const endPinch = (): void => {\n pinchLive = false;\n pinchScale = 1;\n pinchRotation = 0;\n };\n\n const pinchEventOf = (e: Event, scale: number, rotation: number): InputEvent => {\n const g = e as Event & {\n clientX?: number; clientY?: number;\n altKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean;\n };\n // A focal point is part of the WebKit shape; the canvas center stands\n // in for an embedder that leaves it off.\n const rect = typeof g.clientX === 'number' && typeof g.clientY === 'number'\n ? undefined : canvas?.getBoundingClientRect();\n const cx = typeof g.clientX === 'number' ? g.clientX : (rect ? rect.left + rect.width / 2 : 0);\n const cy = typeof g.clientY === 'number' ? g.clientY : (rect ? rect.top + rect.height / 2 : 0);\n routeAt(null, cx, cy);\n const local = core.toCanvasLocal(cx, cy);\n const hitPoint = toWorld(cx, cy);\n const mods = {\n altKey: g.altKey === true, ctrlKey: g.ctrlKey === true,\n metaKey: g.metaKey === true, shiftKey: g.shiftKey === true,\n };\n return {\n kind: 'pinch',\n scale,\n rotation,\n clientX: local.x,\n clientY: local.y,\n ...underPointer(target(), mods, hitPoint),\n };\n };\n\n const onGestureStart = (e: Event) => {\n endPinch();\n // Claimed up front, with a probe at unit scale: Safari starts its own\n // page zoom from an unprevented start, before any change arrives.\n // `direction`-filtered bindings cannot match a unit step, so they are\n // resolved per change instead and do not claim the start.\n const probe = pinchEventOf(e, 1, 0);\n if (dispatcherNow().resolveOnly(probe, ctxNow()) === null) return;\n pinchLive = true;\n e.preventDefault();\n };\n\n const onGestureChange = (e: Event) => {\n const g = e as Event & { scale?: number; rotation?: number };\n const scale = typeof g.scale === 'number' && g.scale > 0 ? g.scale : pinchScale;\n const rotation = typeof g.rotation === 'number' ? g.rotation : pinchRotation;\n const step = scale / pinchScale;\n const turn = rotation - pinchRotation;\n pinchScale = scale;\n pinchRotation = rotation;\n if (dispatch(pinchEventOf(e, step, turn)) === 'handled') {\n pinchLive = true;\n e.preventDefault();\n } else if (pinchLive) {\n // The start was claimed; letting one change through would hand the\n // rest of the pinch to Safari's page zoom mid-gesture.\n e.preventDefault();\n }\n };\n\n const onGestureEnd = (e: Event) => {\n if (pinchLive) e.preventDefault();\n endPinch();\n };\n\n return { onGestureStart, onGestureChange, onGestureEnd, live: () => pinchLive, end: endPinch };\n}\n","/** The wheel channel. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\nexport function wheelInput(core: DispatchCore, pinchLive: () => boolean): (e: WheelEvent) => void {\n const { routeAt, toWorld, target, dispatch } = core;\n\n const onWheel = (e: WheelEvent) => {\n core.activate();\n // Safari can report one trackpad pinch as both a gesture stream and\n // ctrl+wheel. While a claimed gesture is live it is the only driver.\n if (pinchLive() && e.ctrlKey) {\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n routeAt(null, e.clientX, e.clientY);\n // Canvas-local, not client: an anchored wheel zoom would otherwise drift\n // by the canvas's offset from the viewport's top-left.\n const local = core.toCanvasLocal(e.clientX, e.clientY);\n const hitPoint = toWorld(e.clientX, e.clientY);\n const ev: InputEvent = {\n kind: 'wheel',\n deltaX: e.deltaX,\n deltaY: e.deltaY,\n clientX: local.x,\n clientY: local.y,\n ...underPointer(target(), e, hitPoint),\n };\n const result = dispatch(ev);\n // A claimed wheel neither scrolls the page nor reaches the canvas's other listeners\n // (a host's camera would zoom under a loupe); capture phase lets this run first.\n if (result === 'handled') {\n e.preventDefault();\n e.stopImmediatePropagation();\n }\n };\n\n return onWheel;\n}\n","/**\n * One listener set for `useGestureDispatcher`: builds the input channels over a\n * shared dispatch core, binds the DOM listeners the enabled channels need, and\n * returns the teardown.\n */\nimport { heldPointers } from '@weasel-js/gestures';\nimport type { CursorSink, PaintedCursorState } from '@weasel-js/cursor';\nimport { createDispatchCore, type DispatchCoreSources } from './dispatchCore';\nimport type { Dispatcher } from './dispatcherApi';\nimport { dispatcherWatch } from './dispatcherWatch';\nimport { contextMenuInput } from './channels/contextMenu';\nimport { hoverCursorInput } from './channels/hoverCursor';\nimport { DROPOVER_CLASS, ingestInput } from './channels/ingest';\nimport { keyboardInput } from './channels/keyboard';\nimport { listenerSet } from './channels/listeners';\nimport { pointerInput, type PointerInput, type PointerInputOptions } from './channels/pointer';\nimport { webkitPinchInput } from './channels/webkitPinch';\nimport { wheelInput } from './channels/wheel';\n\n/** What a listener set reads. Each thunk answers for the hook's latest render. */\nexport interface InputSources\n extends Pick<DispatchCoreSources, 'root' | 'views' | 'context' | 'actions'>,\n Pick<PointerInputOptions, 'longPress' | 'onClick' | 'onDoubleClick' | 'clicks'> {\n /** Every live dispatcher — what a cancel-everything has to reach. */\n dispatchers(): Dispatcher[];\n requestRedraw(): void;\n paintedCursor(): PaintedCursorState | undefined;\n cursorSink(): CursorSink | undefined;\n}\n\n/** Which channels bind listeners. Fixed for the life of a listener set. */\nexport interface InputChannels {\n keyboard: boolean | 'first';\n pointer: boolean;\n wheel: boolean;\n pinch: boolean;\n contextMenu: boolean;\n ingest: boolean;\n}\n\nexport function attachInput(\n canvas: HTMLElement | null,\n src: InputSources,\n channels: InputChannels,\n): () => void {\n let disposed = false;\n // Dispatcher-only overlays (marquee, lasso) repaint on nothing else, and\n // the event that closes a gesture still has to clear its overlay.\n const redraw = dispatcherWatch(src.requestRedraw);\n redraw.sync(src.dispatchers());\n const core = createDispatchCore({\n canvas,\n root: src.root,\n views: src.views,\n context: src.context,\n actions: src.actions,\n uses: () => { redraw.sync(src.dispatchers()); },\n disposed: () => disposed,\n });\n const keys = keyboardInput(core);\n const pinch = webkitPinchInput(core);\n const ingest = ingestInput(core);\n const held = canvas ? heldPointers(canvas) : null;\n const hover = hoverCursorInput(core, src.paintedCursor, () => held?.count() ?? 0, src.cursorSink);\n const pointer: PointerInput = pointerInput(core, {\n longPress: src.longPress,\n onClick: src.onClick,\n onDoubleClick: src.onDoubleClick,\n clicks: src.clicks,\n hover,\n });\n\n // A window that loses focus never delivers the keyup, so without this every\n // in-flight key-held handle stays engaged until that key is pressed again.\n // Nor can a drag trust the release it may or may not see later.\n const onWindowBlur = (): void => {\n pinch.end();\n pointer.cancelHeld();\n keys.releaseAll();\n };\n\n const listeners = listenerSet();\n const keyCapture = channels.keyboard === 'first';\n if (channels.keyboard) {\n listeners.on(window, 'keydown', keys.onKeyDown, keyCapture);\n listeners.on(window, 'keyup', keys.onKeyUp, keyCapture);\n }\n listeners.on(window, 'blur', onWindowBlur);\n // Ahead of the pointer channel's own listener, and whether or not that\n // channel is on: a press with any button makes this the scope chrome and\n // keys reach.\n listeners.on(canvas, 'pointerdown', () => { src.actions().activate(); });\n if (channels.pointer) {\n // Separate from the key channel's listeners, so the cursor also tracks\n // modifiers when `keyboard: false` turns gesture key dispatch off.\n listeners.on(window, 'keydown', hover.onKey);\n listeners.on(window, 'keyup', hover.onKey);\n listeners.on(canvas, 'pointerleave', hover.onLeave);\n listeners.on(canvas, 'pointerdown', pointer.onPointerDown);\n listeners.on(canvas, 'pointermove', pointer.onHoverMove);\n listeners.on(canvas, 'dblclick', pointer.onNativeDoubleClick);\n }\n if (channels.wheel) {\n listeners.on(canvas, 'wheel', wheelInput(core, pinch.live), { passive: false, capture: true });\n }\n if (channels.pinch) {\n listeners.on(canvas, 'gesturestart', pinch.onGestureStart);\n listeners.on(canvas, 'gesturechange', pinch.onGestureChange);\n listeners.on(canvas, 'gestureend', pinch.onGestureEnd);\n }\n if (channels.contextMenu) {\n listeners.on(canvas, 'contextmenu', contextMenuInput(core, pointer.takeNativeHold));\n }\n if (channels.ingest) {\n listeners.on(canvas, 'dragenter', ingest.onDragOver);\n listeners.on(canvas, 'dragover', ingest.onDragOver);\n listeners.on(canvas, 'dragleave', ingest.onDragLeave);\n listeners.on(canvas, 'drop', ingest.onDrop);\n listeners.on(window, 'paste', ingest.onPaste);\n }\n\n return () => {\n listeners.removeAll();\n canvas?.classList.remove(DROPOVER_CLASS);\n // The registry in use at teardown is the one holding the keys.\n src.actions().dropKeys();\n hover.clear();\n // `disposed` first: the sessions' cancels must not re-enter dispatch on\n // the way out, and `cancelAll` below is what ends the gestures.\n disposed = true;\n pointer.dispose();\n held?.release();\n redraw.stop();\n for (const d of src.dispatchers()) d.cancelAll('cancel');\n };\n}\n","/**\n * Mounts the gesture dispatcher: composes the input channels (keys, wheel,\n * WebKit gesture events, pointer events, and multi-touch synthesized from\n * them) and routes each event to the dispatcher for the view it landed in.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { isApplePlatform, type ClickMemory } from '@weasel-js/gestures';\nimport { useLatest } from '@weasel-js/react';\nimport { useActiveToolContext } from '../actions/activeToolContext';\nimport { useDepRegistry } from '../actions/depRegistry';\nimport { useToolLifecycle } from '../../tools/useToolLifecycle';\nimport { createDispatcher, type Dispatcher, type DispatcherContext } from './dispatcher';\nimport { attachInput } from './attachInput';\nimport type { DispatcherViewTarget, UseGestureDispatcherOptions } from './gestureDispatcherOptions';\n\nexport type {\n DispatcherChannels, DispatcherViewTarget, UseGestureDispatcherOptions, ViewIdResolver,\n} from './gestureDispatcherOptions';\n\n/**\n * Attach the input pipeline to a canvas: DOM pointer, wheel, keyboard, and\n * multitouch listeners in, normalized input events out, routed through the\n * dispatcher to whichever action a binding names.\n *\n * The active tool and the dep registry come from context, so it must be\n * mounted inside `<SceneCanvas>`'s providers.\n */\nexport function useGestureDispatcher(opts: UseGestureDispatcherOptions): void {\n const { canvasRef, actions, entriesById, enabled = true, keyboard = true, affordanceAt, classifyTarget, dispatcher: dispatcherOpt, clientToWorld, requestRedraw, paintedCursor, cursorSink, getRuleCtx, onClick, onDoubleClick, views, channels, longPress, claimKeys = false } = opts;\n // Read out as booleans, not the object: the attach effect depends on\n // them, and an inline `channels={{...}}` would re-bind every listener on\n // every render.\n const pointerChannel = channels?.pointer !== false;\n const wheelChannel = channels?.wheel !== false;\n const pinchChannel = channels?.pinch !== false;\n const contextMenuChannel = channels?.contextMenu !== false;\n const ingestChannel = channels?.ingest !== false;\n const onClickRef = useLatest(onClick);\n const onDoubleClickRef = useLatest(onDoubleClick);\n const activeTool = useActiveToolContext();\n const depRegistry = useDepRegistry();\n const [isMac] = useState(isApplePlatform);\n\n const dispatcherRef = useRef<Dispatcher | null>(null);\n if (!dispatcherRef.current) {\n dispatcherRef.current = dispatcherOpt ?? createDispatcher();\n }\n\n // No `getRuleCtx` here: eligibility is a per-view answer, so it rides on the\n // dispatch record and the core installs the routed view's.\n const registryRef = useLatest(actions);\n const ctxRef = useLatest<DispatcherContext>({\n actions,\n depRegistry,\n activeToolId: activeTool.active,\n hotkeyStack: activeTool.hotkeyStack,\n entriesById,\n isMac,\n });\n\n // The flat options are view zero.\n const rootTargetRef = useLatest<DispatcherViewTarget>({\n id: null, dispatcher: dispatcherRef.current, affordanceAt, classifyTarget, clientToWorld,\n getRuleCtx,\n });\n const viewsRef = useLatest(views);\n\n /** Every live dispatcher — what a cancel-everything has to reach. */\n const allDispatchers = useCallback((): Dispatcher[] => [\n rootTargetRef.current.dispatcher,\n ...(viewsRef.current?.targets() ?? []).map((t) => t.dispatcher),\n ], [rootTargetRef, viewsRef]);\n const requestRedrawRef = useLatest(requestRedraw);\n const cursorRef = useLatest({ painted: paintedCursor, sink: cursorSink });\n const longPressRef = useLatest(longPress);\n\n // Held here rather than in the effect: a re-bind of the listeners between\n // two clicks would otherwise drop the double click.\n const clicksRef = useRef<ClickMemory>({ last: null });\n\n useToolLifecycle({\n entriesById,\n active: activeTool.active,\n hotkeyStack: activeTool.hotkeyStack,\n // The incoming tool must not inherit a live gesture.\n onSwitch: () => { for (const d of allDispatchers()) d.cancelAll('cancel'); },\n });\n\n useEffect(() => {\n if (enabled && claimKeys) registryRef.current.activate();\n }, [enabled, claimKeys, registryRef]);\n\n useEffect(() => {\n if (!enabled) return;\n return attachInput(canvasRef.current, {\n root: () => rootTargetRef.current,\n views: () => viewsRef.current,\n context: () => ctxRef.current,\n actions: () => registryRef.current,\n dispatchers: allDispatchers,\n requestRedraw: () => { requestRedrawRef.current?.(); },\n paintedCursor: () => cursorRef.current.painted?.(),\n cursorSink: () => cursorRef.current.sink?.(),\n longPress: () => longPressRef.current,\n onClick: () => onClickRef.current,\n onDoubleClick: () => onDoubleClickRef.current,\n clicks: clicksRef.current,\n }, {\n keyboard,\n pointer: pointerChannel,\n wheel: wheelChannel,\n pinch: pinchChannel,\n contextMenu: contextMenuChannel,\n ingest: ingestChannel,\n });\n }, [enabled, keyboard, canvasRef, pointerChannel, wheelChannel, pinchChannel, contextMenuChannel, ingestChannel,\n allDispatchers, ctxRef, longPressRef, onClickRef, onDoubleClickRef, cursorRef, registryRef, requestRedrawRef, rootTargetRef, viewsRef]);\n}\n","/**\n * @experimental\n * The React half of the actions registry: the context, the tree node that\n * owns each id → descriptor stack, the providers that mount nodes, and the two\n * hooks. The store contract it implements is in `registry.ts`.\n */\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport type { Action } from './action';\nimport { evaluateEnabled } from './actionEnabled';\nimport { useLatest } from '@weasel-js/react';\nimport {\n useOptionalDepRegistry,\n type DepRegistry,\n type DepName,\n} from './depRegistry';\nimport { buildDepsFromRequires } from './buildDeps';\nimport type { Dispatcher } from '../dispatcher/dispatcher';\nimport { validateActionId, validateActionDefaultBinding, type ActionsRegistry } from './registry';\nimport { pushOwner, ScopeNode } from './scopeNode';\nimport { tuneAction, type ActionTuning } from './tuning';\n\n/** @internal Provided by `<ActionsProvider>`, `<InputScope>` and `<Yoke>`. */\nexport const ActionsContext = createContext<ActionsRegistry | null>(null);\n\n/** The deps an action is invoked with: its declared `requires` when it has\n * one, the legacy fixed bag otherwise. The fixed bag has no `applyOps`, so an\n * action that needs the consumer's history must declare it. */\nfunction depsFor(a: Action, r: DepRegistry | null): Record<string, unknown> {\n if (!r) return {};\n if (a.requires) return buildDepsFromRequires(a, r) as Record<string, unknown>;\n return {\n selection: r.get('selection' as DepName),\n scene: r.get('scene' as DepName),\n history: r.get('history' as DepName),\n view: r.get('view' as DepName),\n activeTool: r.get('activeTool'),\n booleansAdapter: r.get('booleansAdapter' as DepName),\n };\n}\n\n/**\n * One node of the actions tree: the actions registered at it, over its\n * parent's. Each id holds a stack of registrants, newest live, so a displaced\n * registrant is restored when the one above it leaves. Every read the registry\n * answers — `list`, `trigger`, `begin` — starts at the node's leaf.\n */\nexport class ActionsNode extends ScopeNode<ActionsNode> {\n private readonly actions = new Map<string, Action[]>();\n private readonly muted = new Map<string, number>();\n private readonly tunings = new Map<string, ActionTuning[]>();\n private readonly dispatchers: Dispatcher[] = [];\n private cache: { version: number; leaf: ActionsNode; list: readonly Action[] } | null = null;\n /** Called on `activate`, so a scope's dep and tool nodes move with it. */\n readonly onActivate: (() => void)[] = [];\n\n constructor(\n parent: ActionsNode | null,\n descends: boolean,\n private readonly contextDeps: () => DepRegistry | null,\n ) {\n super(parent, descends);\n NODES.set(this.registry, this);\n }\n\n private resolve(id: string): Action | undefined {\n for (const n of this.chain()) {\n if (n.muted.has(id)) return undefined;\n const a = n.actions.get(id)?.at(-1);\n if (a) return this.tuned(a);\n }\n return undefined;\n }\n\n /** `a` under every tuning for its id from the root down to here. */\n private tuned(a: Action): Action {\n const tunings: ActionTuning[] = [];\n for (const n of this.chain()) {\n const stack = n.tunings.get(a.id);\n if (stack) tunings.unshift(...stack);\n }\n return tunings.length ? tuneAction(a, tunings) : a;\n }\n\n private snapshot(): readonly Action[] {\n const leaf = this.start();\n const cached = this.cache;\n if (cached && cached.version === this.tree.version && cached.leaf === leaf) return cached.list;\n const ids = new Set<string>();\n for (const n of leaf.chain()) for (const id of n.actions.keys()) ids.add(id);\n const out: Action[] = [];\n for (const id of ids) {\n const a = leaf.resolve(id);\n if (a) out.push(a);\n }\n const list = Object.freeze(out);\n this.cache = { version: this.tree.version, leaf, list };\n return list;\n }\n\n private deps(): DepRegistry | null {\n for (const n of this.chain()) {\n const r = n.contextDeps();\n if (r) return r;\n }\n return null;\n }\n\n private dispatcher(): Dispatcher | null {\n for (const n of this.chain()) {\n const d = n.dispatchers.at(-1);\n if (d) return d;\n }\n return null;\n }\n\n override activate(): void {\n keyHolder = this;\n super.activate();\n for (const f of this.onActivate) f();\n }\n\n readonly registry: ActionsRegistry = {\n register: (action: Action) => {\n validateActionId(action.id);\n validateActionDefaultBinding(action);\n const stack = this.actions.get(action.id);\n if (stack) stack.push(action);\n else this.actions.set(action.id, [action]);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const cur = this.actions.get(action.id);\n if (!cur) return;\n // Our own entry, wherever it now sits: a registrant that was already\n // displaced must take itself out without disturbing the one above it.\n const i = cur.lastIndexOf(action);\n if (i === -1) return;\n cur.splice(i, 1);\n // An emptied stack holds the id's place in registration order until\n // the tick ends, so a release followed at once by a register — what\n // `useAction` does when its action object changes — keeps its slot.\n if (cur.length === 0) {\n queueMicrotask(() => {\n if (cur.length === 0 && this.actions.get(action.id) === cur) this.actions.delete(action.id);\n });\n }\n this.changed();\n };\n },\n unregister: (id: string) => {\n if (this.actions.delete(id)) this.changed();\n },\n mute: (id: string) => {\n this.muted.set(id, (this.muted.get(id) ?? 0) + 1);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const held = this.muted.get(id);\n if (held === undefined) return;\n if (held > 1) this.muted.set(id, held - 1);\n else this.muted.delete(id);\n this.changed();\n };\n },\n tune: (id: string, tuning: ActionTuning) => {\n let stack = this.tunings.get(id);\n if (!stack) this.tunings.set(id, (stack = []));\n const release = pushOwner(stack, tuning);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n release();\n if (stack.length === 0) this.tunings.delete(id);\n this.changed();\n };\n },\n list: () => this.snapshot(),\n trigger: (id: string, params?: Record<string, unknown>) => {\n const leaf = this.start();\n const a = leaf.resolve(id);\n if (!a?.invoker || a.invoker.timing !== 'immediate') return false;\n const deps = depsFor(a, leaf.deps());\n if (!evaluateEnabled(a, deps as never).enabled) return false;\n try {\n a.invoker.run(deps as never, params);\n } catch (err) {\n console.error(`weasel ActionsRegistry: action \"${id}\" threw`, err);\n }\n return true;\n },\n subscribe: (listener: () => void) => this.tree.listeners.subscribe(listener),\n setDispatcher: (d: Dispatcher | null) => pushOwner(this.dispatchers, d),\n begin: (id: string, params?: Record<string, unknown>) => {\n const leaf = this.start();\n const a = leaf.resolve(id);\n const disp = leaf.dispatcher();\n if (!a || !disp) return null;\n return disp.beginUiOngoing(id, depsFor(a, leaf.deps()) as never, params);\n },\n activate: () => this.activate(),\n isActive: () => this.isActive(),\n holdsKeys: () => keyHolder === this,\n dropKeys: () => { if (keyHolder === this) keyHolder = null; },\n };\n}\n\n/** The node last activated on the page, across every tree: where a key that\n * reaches the page goes. Null until something is pressed or scrolled in. */\nlet keyHolder: ActionsNode | null = null;\n\nconst NODES = new WeakMap<ActionsRegistry, ActionsNode>();\n\n/** The tree node behind `registry`, when it is one of ours. */\nexport function actionsNodeOf(registry: ActionsRegistry | null): ActionsNode | null {\n return registry ? (NODES.get(registry) ?? null) : null;\n}\n\n/**\n * @experimental\n * Mounts a root `ActionsRegistry` for its lifetime. Children call\n * `useActionsRegistry()` or `useAction()` to participate. Mounts no input\n * listener of its own — the gesture dispatcher owns input.\n */\nexport function ActionsProvider({ children }: { children: ReactNode }): ReactElement {\n // `trigger` consults the dep registry in scope, so actions can be fired\n // imperatively from ActionBar / palette callers.\n const depReg = useOptionalDepRegistry();\n const depRegRef = useLatest<DepRegistry | null>(depReg);\n const node = useMemo(() => new ActionsNode(null, true, () => depRegRef.current), [depRegRef]);\n return <ActionsContext.Provider value={node.registry}>{children}</ActionsContext.Provider>;\n}\n\n/**\n * `import.meta.env.DEV` read through a cast — core must not depend on a\n * bundler's ambient augmentation (`vite/client`) to compile. Mirrors the same\n * cast in SceneCanvas.tsx, dispatcher.ts and buildDeps.ts.\n */\nconst IS_DEV: boolean = (() => {\n try {\n return Boolean((import.meta as unknown as { env?: { DEV?: boolean } }).env?.DEV);\n } catch {\n return false;\n }\n})();\n\n/**\n * @experimental\n * Returns the `ActionsRegistry` in scope, or `null` when there is none.\n */\nexport function useActionsRegistry(): ActionsRegistry | null {\n return useContext(ActionsContext);\n}\n\n/**\n * @experimental\n * Register an `Action` for the lifetime of the calling component. No-op (with\n * a dev-only warning) when no `ActionsProvider` is in scope. Re-registers on\n * `action` reference change (consumers should memoize stable identities to\n * avoid churn).\n */\nexport function useAction(action: Action): void {\n const reg = useActionsRegistry();\n useEffect(() => {\n if (!reg) {\n if (IS_DEV) {\n console.warn(\n `useAction(\"${action.id}\"): no <ActionsProvider> is in scope, so the action was not registered and its bindings will never fire.`,\n );\n }\n return;\n }\n return reg.register(action);\n }, [reg, action]);\n}\n","/**\n * @experimental\n * Input scopes and yokes: the tiers between a root registry and a canvas.\n */\nimport { useContext, useEffect, useMemo, type ReactElement, type ReactNode } from 'react';\nimport { ActionsContext, ActionsNode, actionsNodeOf, useActionsRegistry } from './ActionsProvider';\nimport { DepNode, DepRegistryContext, depNodeOf, useOptionalDepRegistry } from './depRegistry';\nimport { ActiveToolNodeContext, ToolNode } from './activeToolContext';\n\n/**\n * @experimental\n * Canvases that share input on purpose: the active tool, the gesture in\n * flight, history, and yoke-wide actions. Made once with `useYoke()`, and\n * passed to each canvas that joins it (`yoke={yoke}`) and to\n * `<Yoke value={yoke}>` around anything else that should reach it — a\n * toolbar, say. The members can sit anywhere in the tree.\n */\nexport interface Yoke {\n /** @internal */\n readonly actions: ActionsNode;\n /** @internal */\n readonly deps: DepNode;\n /** @internal */\n readonly tools: ToolNode;\n}\n\n/** The three nodes of a tier, under `parent`'s or the ones in scope, with\n * activation carried across all three. */\nfunction useNodes(\n descends: boolean,\n ownsTool: boolean,\n parent: Yoke | undefined,\n): Yoke {\n const parentActions = useActionsRegistry();\n const parentDeps = useOptionalDepRegistry();\n const parentTools = useContext(ActiveToolNodeContext);\n const pa = parent ? parent.actions : actionsNodeOf(parentActions);\n const pd = parent ? parent.deps : depNodeOf(parentDeps);\n const pt = parent ? parent.tools : parentTools;\n const nodes = useMemo<Yoke>(() => {\n const deps = new DepNode(pd, descends);\n const tools = new ToolNode(pt, descends, ownsTool, null);\n const actions = new ActionsNode(pa, descends, () => deps.registry);\n actions.onActivate.push(() => deps.activate(), () => tools.activate());\n return { actions, deps, tools };\n }, [pa, pd, pt, descends, ownsTool]);\n useEffect(() => {\n const leave = [nodes.deps.mount(), nodes.tools.mount(), nodes.actions.mount()];\n return () => {\n for (const f of leave) f();\n };\n }, [nodes]);\n return nodes;\n}\n\nfunction Provide({ nodes, children }: { nodes: Yoke; children: ReactNode }): ReactElement {\n return (\n <DepRegistryContext.Provider value={nodes.deps.registry}>\n <ActionsContext.Provider value={nodes.actions.registry}>\n <ActiveToolNodeContext.Provider value={nodes.tools}>{children}</ActiveToolNodeContext.Provider>\n </ActionsContext.Provider>\n </DepRegistryContext.Provider>\n );\n}\n\n/** Props for `<InputScope>`. */\nexport interface InputScopeProps {\n /** The yoke this scope joins. Omitted, it sits under the registries in\n * scope and keeps a tool of its own. */\n yoke?: Yoke;\n children: ReactNode;\n}\n\n/**\n * @experimental\n * One canvas's input: actions, deps and a tool of its own, under whichever\n * registries are in scope (or its yoke's). What the canvas registers stays\n * here; what it looks up is answered here first, then by the tiers above.\n * With nothing in scope it is a root.\n *\n * Chrome above calls `trigger` / `begin` / `useActiveToolContext` on its own\n * registries, and those reach the active scope: the one last activated — by a\n * pointerdown or wheel — or the newest where none has been. Keys are stricter:\n * one that reaches the page goes to the canvas last pressed or scrolled in,\n * across every root on the page, and to none before the first.\n */\nexport function InputScope({ yoke, children }: InputScopeProps): ReactElement {\n const nodes = useNodes(false, yoke === undefined, yoke);\n return <Provide nodes={nodes}>{children}</Provide>;\n}\n\n/**\n * @experimental\n * Make a yoke for canvases to join, under the registries in scope where it is\n * called. It lives as long as the calling component.\n */\nexport function useYoke(): Yoke {\n return useNodes(true, true, undefined);\n}\n\n/** Props for `<Yoke>`. */\nexport interface YokeProps {\n value: Yoke;\n children: ReactNode;\n}\n\n/**\n * @experimental\n * Put `value` in scope for what is not a canvas — a toolbar, a status bar — so\n * its actions, deps and tool reads reach the yoke and, through it, the member\n * canvas last used.\n */\nexport function Yoke({ value, children }: YokeProps): ReactElement {\n return <Provide nodes={value}>{children}</Provide>;\n}\n","import { useEffect, useMemo, useRef } from 'react';\nimport { useActionsRegistry } from './ActionsProvider';\nimport type { ActionsRegistry, UiOngoingControl } from './registry';\nimport { useLatest } from '@weasel-js/react';\n\n/**\n * One UI control's hold on an ongoing action — the handle a color picker, a\n * slider or a swatch drives the action through, the way a drag drives one\n * through a gesture.\n *\n * - `input(params)` opens the action on the first call and moves it on every\n * later one: the live preview.\n * - `commit(params?)` moves it to `params`, if given, and ends it as one\n * undoable edit. With nothing open, a commit carrying params is a whole edit\n * on its own — a click on a swatch, a switch of paint kind.\n * - `cancel()` ends an open edit without keeping it.\n *\n * An edit the dispatcher ended first — a tool switch, Escape, another control\n * committing the same action — counts as not open: the next `input` opens a\n * new one.\n *\n * All three are no-ops when no action is reachable, so a control renders the\n * same with or without a canvas in scope.\n */\nexport interface OngoingAction {\n input(params: Record<string, unknown>): void;\n commit(params?: Record<string, unknown>): void;\n cancel(): void;\n}\n\n/**\n * Drive the ongoing action `actionId` from a UI control: {@link OngoingAction}.\n *\n * An edit left open when the control unmounts, or when `actionId` changes, is\n * committed — it is what the user was looking at when the control went away.\n * On unmount that happens a microtask later.\n * The returned object is stable for the life of the component.\n */\nexport function useOngoingAction(actionId: string): OngoingAction {\n const reg = useActionsRegistry();\n const regRef = useLatest<ActionsRegistry | null>(reg);\n const idRef = useLatest(actionId);\n const ctrlRef = useRef<UiOngoingControl | null>(null);\n\n const edit = useMemo<OngoingAction>(() => {\n const end = (reason: 'commit' | 'cancel'): void => {\n const ctrl = ctrlRef.current;\n ctrlRef.current = null;\n ctrl?.end(reason);\n };\n /** Move the open edit to `params`, or open one there: the dispatcher may\n * have ended the one this control held. */\n const drive = (params: Record<string, unknown>): void => {\n if (ctrlRef.current?.active) ctrlRef.current.update(params);\n else ctrlRef.current = regRef.current?.begin(idRef.current, params) ?? null;\n };\n return {\n input: drive,\n commit(params) {\n if (params !== undefined) drive(params);\n end('commit');\n },\n cancel() {\n end('cancel');\n },\n };\n }, [regRef, idRef]);\n\n // The commit waits a microtask so that StrictMode's rehearsal unmount, which\n // remounts with the same id before then, does not end an edit opened in an effect.\n const leaving = useRef<string | null>(null);\n useEffect(() => {\n const left = leaving.current;\n leaving.current = null;\n if (left !== null && left !== actionId) edit.commit();\n return () => {\n leaving.current = actionId;\n queueMicrotask(() => {\n if (leaving.current !== actionId) return;\n leaving.current = null;\n edit.commit();\n });\n };\n }, [edit, actionId]);\n\n return edit;\n}\n","/**\n * @experimental\n * PointerContext — the world-space position of the canvas pointer, and the\n * view it is over, refreshed on every `pointermove` and cleared on\n * `pointerleave`.\n *\n * It is an external store rather than React state, so a consumer that only\n * reads on demand (paste at the pointer) does not re-render on every move.\n * Readers that need to follow it subscribe, or use `usePointerPosition()`.\n *\n * `<SceneCanvas>` publishes automatically, and defers to a provider already in\n * scope, so several surfaces under one provider share one pointer.\n */\nimport { createEmitter } from '@weasel-js/registry';\nimport {\n createContext, useContext, useState, useSyncExternalStore, type ReactNode,\n} from 'react';\n\n/** @experimental World-space pointer position and the view it is over — a\n * view id, or `null` for a surface's own camera. `null` as a whole when the\n * pointer is over no publishing surface. */\nexport type PointerWorldPos = { worldX: number; worldY: number; viewId: string | null } | null;\n\n/** @experimental */\nexport interface PointerContextValue {\n /** The latest position. */\n get(): PointerWorldPos;\n /** Publish a position. Subscribers hear only a changed value. */\n set(next: PointerWorldPos): void;\n /** Called after every change; returns the unsubscribe. */\n subscribe(fn: () => void): () => void;\n /** Bumps on every change. */\n getVersion(): number;\n /** `get()` as a stable thunk, for hooks taking a drop-point option. */\n readonly getDropPoint: () => PointerWorldPos;\n}\n\nfunction samePos(a: PointerWorldPos, b: PointerWorldPos): boolean {\n if (a === null || b === null) return a === b;\n return a.worldX === b.worldX && a.worldY === b.worldY && a.viewId === b.viewId;\n}\n\n/** @experimental A pointer store with no provider around it. */\nexport function createPointerStore(): PointerContextValue {\n let current: PointerWorldPos = null;\n let version = 0;\n const changed = createEmitter();\n const get = (): PointerWorldPos => current;\n return {\n get,\n set(next) {\n if (samePos(current, next)) return;\n current = next;\n version++;\n changed.emit();\n },\n subscribe: changed.subscribe,\n getVersion: () => version,\n getDropPoint: get,\n };\n}\n\nconst PointerContext = createContext<PointerContextValue | null>(null);\n\n/**\n * @experimental\n * Wrap the part of the React tree that should share one pointer.\n * `<SceneCanvas>` mounts one when none is in scope, so mount it yourself only\n * when two surfaces should share a pointer. Pass `store` to publish into one\n * you hold elsewhere (`createPointerStore()`).\n */\nexport function PointerContextProvider(\n { children, store }: { children: ReactNode; store?: PointerContextValue },\n): ReactNode {\n const [own] = useState(createPointerStore);\n return <PointerContext.Provider value={store ?? own}>{children}</PointerContext.Provider>;\n}\n\n/** @experimental The surrounding pointer store, or `null` when no provider is\n * in scope. */\nexport function usePointerContext(): PointerContextValue | null {\n return useContext(PointerContext);\n}\n\nconst noSubscribe = (): (() => void) => () => {};\nconst noPointer = (): PointerWorldPos => null;\n\n/** @experimental The pointer, re-rendering the caller whenever it changes.\n * `null` outside a provider. */\nexport function usePointerPosition(): PointerWorldPos {\n const store = usePointerContext();\n return useSyncExternalStore(\n store ? store.subscribe : noSubscribe,\n store ? store.get : noPointer,\n store ? store.get : noPointer,\n );\n}\n","/**\n * @experimental\n * SelectionContext — an ambient context that publishes \"what's currently\n * selected\" so non-canvas UI (command palette, status bar) can read it without\n * threading a selection prop through the tree.\n *\n * **Single slot:** the context holds one selection array. Whichever publisher\n * calls `publishSelection` most recently owns it, so a multi-canvas page gets\n * last-writer-wins. `<SceneCanvas>` publishes automatically.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { NodeId } from '../vocabulary';\n\n/** @experimental */\nexport interface SelectionContextValue {\n /** The most-recently-published selection. Empty array when no canvas\n * has published or when the active canvas's selection is empty. */\n readonly selection: readonly NodeId[];\n /** Optional per-id kind label, parallel to `selection` (e.g. `'rectangle'`,\n * `'path'`, `'group'`). Sparse entries (`undefined`) are allowed; treat it\n * as best-effort. */\n readonly kinds?: readonly (string | undefined)[];\n /** Publish the calling canvas's selection. Calling with the same content\n * does not re-render the consumer tree. */\n publishSelection(ids: readonly NodeId[], kinds?: readonly (string | undefined)[]): void;\n}\n\nconst SelectionContext = createContext<SelectionContextValue | null>(null);\n\n/**\n * @experimental\n * Wrap the part of the React tree that should share a selection context.\n * Usually placed at the demo / app root, alongside `<ActionsProvider>`.\n */\nexport function SelectionContextProvider({ children }: { children: ReactNode }): ReactNode {\n const [state, setState] = useState<{\n selection: readonly NodeId[];\n kinds: readonly (string | undefined)[] | undefined;\n }>({ selection: [], kinds: undefined });\n const lastSerializedRef = useRef<string>('');\n\n const publishSelection = useCallback((\n ids: readonly NodeId[],\n kinds?: readonly (string | undefined)[],\n ): void => {\n const next = JSON.stringify([ids, kinds]);\n if (next === lastSerializedRef.current) return;\n lastSerializedRef.current = next;\n setState({ selection: ids, kinds });\n }, []);\n\n const value = useMemo<SelectionContextValue>(\n () => ({\n selection: state.selection,\n ...(state.kinds !== undefined ? { kinds: state.kinds } : {}),\n publishSelection,\n }),\n [state, publishSelection],\n );\n\n return <SelectionContext.Provider value={value}>{children}</SelectionContext.Provider>;\n}\n\n/**\n * @experimental\n * The current selection-context value, or `null` when no\n * `<SelectionContextProvider>` is in scope.\n */\nexport function useSelectionContext(): SelectionContextValue | null {\n return useContext(SelectionContext);\n}\n\n/**\n * @experimental\n * Mounts a `<SelectionContextProvider>` only when no parent provider is in\n * scope; otherwise renders children unwrapped.\n */\nexport function SelectionContextProviderIfRoot({\n children,\n}: {\n children: ReactNode;\n}): ReactNode {\n const parent = useContext(SelectionContext);\n if (parent !== null) return <>{children}</>;\n return <SelectionContextProvider>{children}</SelectionContextProvider>;\n}\n\n/**\n * @experimental\n * Publishes `ids` into the surrounding `<SelectionContextProvider>` whenever\n * their content changes, and clears the slot on unmount unless another\n * publisher has written it since. No-op when there's no provider in scope.\n */\nexport function usePublishSelection(\n ids: readonly NodeId[],\n kinds?: readonly (string | undefined)[],\n): void {\n const ctx = useContext(SelectionContext);\n // Track latest values via refs so the effect's deps array can use a stable\n // serialization — avoids re-firing on identity-only changes.\n const idsRef = useLatest(ids);\n const kindsRef = useLatest(kinds);\n const serialized = JSON.stringify([ids, kinds]);\n // Depend on `publishSelection` rather than `ctx`: the provider mints a new\n // context value on every publish, so keying on `ctx` refires this effect for\n // every publisher whenever any one of them publishes.\n const publish = ctx?.publishSelection;\n useEffect(() => {\n if (!publish) return;\n publish(idsRef.current, kindsRef.current);\n }, [publish, serialized, idsRef, kindsRef]);\n // A publisher that goes away takes its selection with it, unless another\n // has written the slot since.\n const ctxRef = useLatest(ctx);\n const serializedRef = useLatest(serialized);\n useEffect(() => () => {\n const slot = ctxRef.current;\n if (slot && JSON.stringify([slot.selection, slot.kinds]) === serializedRef.current) {\n slot.publishSelection([]);\n }\n }, [ctxRef, serializedRef]);\n}\n","// src/contributions/useContributions.ts\nimport { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { activeModeOf, type ModeRegistry } from '@weasel-js/modes';\nimport { useActiveToolContext } from '../interactions/actions/activeToolContext';\nimport { useActionsRegistry } from '../interactions/actions/ActionsProvider';\nimport {\n buildToolOffhandBindings,\n makeToolOffhandAction,\n offhandKeyFor,\n type ToolOffhandBindingSpec,\n} from '../interactions/actions/toolOffhand';\nimport { reportRouteConflicts } from '../tools/routing/reflection/conflicts';\nimport type { HotkeyTrigger } from './types';\nimport { assembleEntries } from './assemble';\nimport { liveScope } from './eligibility';\nimport type { Contribution, OverlayPosition } from './types';\nimport { isDev } from '../devFlag';\nimport { sameList, useStableByContent } from '@weasel-js/react';\nimport type { KernelOverlay } from '../index';\n\nconst NO_MODES = (): (() => void) => () => {};\n\n/** Options for {@link useContributions}. */\nexport interface UseContributionsOptions<TOverlay = KernelOverlay> {\n /** Every registry entry, in declaration order. Order decides which of two\n * same-specificity bindings in one scope tier wins. */\n entries: readonly Contribution<TOverlay>[];\n /** Desired focused entry id, or `null` for none. First-mount-wins against\n * the shared `ActiveToolContext` — see `useTools` for the full semantics. */\n focused: string | null;\n /** The modes the canvas can be in. The active one decides which tagged\n * entries draw their overlays, and the dev-time route-conflict check reads\n * them all to decide whether two gated actions can ever compete; without a\n * registry nothing is barred and the check uses the kit's `DEFAULT_MODES`. */\n modes?: ModeRegistry;\n}\n\n/** The assembled registry {@link useContributions} returns. */\nexport interface ContributionsApi<TOverlay = KernelOverlay> {\n /** Every entry, as passed in. */\n entries: readonly Contribution<TOverlay>[];\n /** Currently focused entry id, or `null` when nothing is focused. */\n focused: string | null;\n /** Focus an entry, or pass `null` to focus none. Writes through to the\n * shared `ActiveToolContext`. */\n setFocused: (id: string | null) => void;\n /** Overlays of every live entry declaring `position`, ordered active, then\n * hotkey, then ambient. Live is what the dispatcher routes to: an entry the\n * active mode bars draws nothing. */\n overlays(position?: OverlayPosition): TOverlay[];\n}\n\n/**\n * Assembles one registry: every entry's bindings and overlays, each tiered by\n * what the entry declares about its own eligibility rather than by which\n * argument a consumer passed it in.\n *\n * Requires `<ActiveToolContextProvider>` (or `<WeaselProvider>` /\n * `<SceneCanvas>`, which mount one internally): focus and held-key state live\n * in the context so the gesture dispatcher and every sibling caller read the\n * same source of truth.\n */\nexport function useContributions<TOverlay = KernelOverlay>(\n opts: UseContributionsOptions<TOverlay>,\n): ContributionsApi<TOverlay> {\n const ctx = useActiveToolContext();\n const actionsRegistry = useActionsRegistry();\n\n // First-mount sync: if the context's slot is still unseeded and the caller\n // wants a tool, push it. Captured at first render; the setState runs in a\n // post-commit effect so it never updates state during render.\n const firstMountRef = useRef<{ sync: boolean } | null>(null);\n const isFirstRender = firstMountRef.current == null;\n if (firstMountRef.current == null) firstMountRef.current = { sync: ctx.active === null && opts.focused !== null };\n useEffect(() => {\n const first = firstMountRef.current;\n if (!first?.sync) return;\n first.sync = false;\n ctx.setActive(opts.focused);\n // First-mount sync only — deliberately runs once after mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const focused = isFirstRender && ctx.active === null && opts.focused !== null\n ? opts.focused\n : ctx.active;\n\n // Consumers commonly rebuild the entry list every render; identity follows\n // its contents, so everything keyed on it below changes only when they do.\n const entries = useStableByContent(opts.entries, sameList);\n const engaged = ctx.hotkeyStack;\n\n const setFocused = useCallback((id: string | null) => { ctx.setActive(id); }, [ctx]);\n\n // The active mode's capability set gates overlays as it gates bindings. Read\n // as state so `overlays` changes identity when the mode does.\n const modes = opts.modes;\n const modeVersion = useSyncExternalStore(\n modes ? modes.subscribe : NO_MODES,\n () => modes?.getVersion() ?? 0,\n );\n const snapshot = useCallback(() => assembleEntries(entries, {\n focusedId: focused,\n hotkeyStack: engaged,\n ...(modes ? { allowedCapabilities: activeModeOf(modes.current()).allowedCapabilities } : {}),\n // The version is what changes; `modes` is one object for the registry's life.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [entries, focused, engaged, modes, modeVersion]);\n\n const overlays = useCallback((position: OverlayPosition = 'top'): TOverlay[] => {\n const { ordered, state } = snapshot();\n const active: TOverlay[] = [];\n const hotkey: TOverlay[] = [];\n const ambient: TOverlay[] = [];\n for (const entry of ordered) {\n if (!entry.overlay) continue;\n if ((entry.overlayPosition ?? 'top') !== position) continue;\n const layers = Array.isArray(entry.overlay) ? entry.overlay : [entry.overlay];\n const scope = liveScope(entry.id, entry.eligibility ?? {}, state);\n if (scope === 'active') active.push(...layers);\n else if (scope === 'hotkey') hotkey.push(...layers);\n else if (scope === 'ambient') ambient.push(...layers);\n }\n return [...active, ...hotkey, ...ambient];\n }, [snapshot]);\n\n useOffhandAction(entries);\n\n // Route-conflict check. Two entries declaring the same (phase, gesture, arg,\n // target, modifiers) tuple in one scope are resolved by declaration order and\n // almost certainly not as either author intended. This is where the entry set\n // is assembled, so this is where it looks.\n //\n // Dev-only, and deduped on a signature of the entry set: the check walks\n // every binding of every entry, and consumers usually rebuild the entry list\n // each render. Actions are read inside the effect, after the registrations\n // that ran in child effects have landed.\n const lastConflictSigRef = useRef<{ sig: string; modes: ModeRegistry | undefined } | null>(null);\n const entrySig = entries.map((e) => e.id).join(',');\n const modesRegistry = opts.modes;\n useEffect(() => {\n if (!isDev()) return;\n const last = lastConflictSigRef.current;\n if (last?.sig === entrySig && last.modes === modesRegistry) return;\n lastConflictSigRef.current = { sig: entrySig, modes: modesRegistry };\n // An entry can be in both buckets and usually is: every tool `defineTool`\n // builds declares `focus: true`, and an ambient one carries `always: true`\n // on top of that. Sorting on \"not focus-eligible\" put ambient tools in the\n // registry bucket, which is never compared against itself — registry tools\n // take turns in the active slot — so ambient-vs-ambient went unreported.\n const registry: Contribution<TOverlay>[] = [];\n const ambient: Contribution<TOverlay>[] = [];\n for (const entry of entries) {\n if (entry.eligibility?.focus) registry.push(entry);\n if (entry.eligibility?.always || entry.eligibility?.claimed) ambient.push(entry);\n }\n reportRouteConflicts({\n registry,\n ambient,\n actions: actionsRegistry?.list() ?? [],\n ...(modesRegistry ? { modes: modesRegistry.list().map(activeModeOf) } : {}),\n });\n }, [entrySig, entries, actionsRegistry, modesRegistry]);\n\n // Memoized so consumers using the result as an effect dep don't see identity\n // churn every render — which loops infinitely when the consumer setStates\n // from inside such an effect.\n return useMemo(\n () => ({ entries, focused, setFocused, overlays }),\n [entries, focused, setFocused, overlays],\n );\n}\n\n/**\n * Registers the consolidated `tool.offhand` action for every entry declaring\n * an `offhand` trigger, into the nearest `<ActionsProvider>`; its invoker\n * reads `params.toolId` off the matched binding. `useContributions` calls it,\n * and so does any host that assembles its entries above its own provider —\n * `<SceneCanvas>` does — since a null registry here registers nothing.\n */\nexport function useOffhandAction(entries: readonly Contribution<unknown>[]): void {\n const actionsRegistry = useActionsRegistry();\n const offhandSig = JSON.stringify(entries\n .filter((e) => e.eligibility?.offhand)\n .map((e) => [e.id, e.eligibility.offhand]));\n useEffect(() => {\n const pairs = JSON.parse(offhandSig) as [string, HotkeyTrigger][];\n if (!actionsRegistry || pairs.length === 0) return;\n const specs: ToolOffhandBindingSpec[] = pairs.map(([toolId, trigger]) => (\n { toolId, key: offhandKeyFor(trigger) }\n ));\n return actionsRegistry.register(makeToolOffhandAction(buildToolOffhandBindings(specs)));\n }, [actionsRegistry, offhandSig]);\n}\n","// src/tools/useTools.ts\nimport { useCallback, useMemo } from 'react';\nimport type { ModeRegistry } from '@weasel-js/modes';\nimport { dlog } from '../dlog';\nimport type { AnyTool, Tool } from './types';\nimport type { HotkeyTrigger } from '../contributions/types';\nimport { useActiveToolContext } from '../interactions/actions/activeToolContext';\nimport { useContributions } from '../contributions/useContributions';\nimport type { Contribution, Eligibility, OverlayPosition } from '../contributions/types';\nimport type { KernelOverlay } from '../index';\nimport { sameList, useLatest, useStableByContent } from '@weasel-js/react';\n\n/** Options for `useTools`: which tools exist, which one starts active, and\n * which run continuously regardless of the active one. */\nexport interface UseToolsOptions<TOverlay = KernelOverlay> {\n /** Initial active-slot tool id, which must exist in `registry`. Omit, or\n * pass `null`, for no active tool: only hotkey and ambient bindings run. */\n active?: string | null;\n /** Tools eligible for the active slot or hotkey slot. The keys are the\n * tool ids; the values are the tool records. A tool with `hotkey` set\n * is wired into the hotkey slot whenever the engagement state matches. */\n registry: Record<string, Tool<TOverlay>>;\n /** Always-on entries — tools or other contributions, live regardless of\n * the active slot. */\n ambient?: readonly Contribution<TOverlay>[];\n /** The modes the canvas can be in, read by the dev-time route-conflict\n * check; without a registry it checks against the kit's `DEFAULT_MODES`. */\n modes?: ModeRegistry;\n}\n\n/** The tool registry's runtime surface: which tool is active, which is\n * temporarily held by a hotkey, and how to change either. */\nexport interface ToolsApi<TOverlay = KernelOverlay> {\n /** Current active-slot tool id, or `null` when no tool is active. */\n active: string | null;\n /** Set the active-slot tool, or `null` to clear it. The gesture dispatcher\n * watches the active tool and cancels any in-flight handle itself. */\n setActive: (id: string | null) => void;\n /** Currently hotkey-engaged tool id (or `null`): the top of the hotkey stack. */\n hotkeyEngaged: string | null;\n /** Engage a hotkey-slot tool by id. */\n engageHotkey: (id: string) => void;\n /** Disengage the hotkey-slot tool, if any. */\n disengageHotkey: () => void;\n /** All always-on entries, in registration order. */\n ambient: readonly Contribution<TOverlay>[];\n /** Full registry — for userland UI (palette buttons, etc.). */\n registry: Readonly<Record<string, Tool<TOverlay>>>;\n /** Returns true if a tool with the given id is in the registry or ambient list. */\n has(id: string): boolean;\n /** Overlay layers from currently-engaged tools that declare `position`.\n * Order: active, then hotkey (if engaged), then ambient (registration order). */\n getActiveOverlays(position?: OverlayPosition): TOverlay[];\n}\n\n/** The slot a caller passed a tool in, restated as declared eligibility.\n * A tool that already declares what its slot implies is returned as-is:\n * `ToolsApi.registry` hands back the objects the caller passed, and\n * consumers compare identity. */\nfunction declareSlot<T extends Contribution<unknown>>(tool: T, slot: 'focus' | 'always'): T {\n const hotkey = (tool.def as { hotkey?: HotkeyTrigger } | undefined)?.hotkey;\n const eligibility: Eligibility = {\n ...tool.eligibility,\n [slot]: true,\n ...(hotkey ? { offhand: hotkey } : {}),\n };\n return sameEligibility(tool.eligibility, eligibility) ? tool : { ...tool, eligibility };\n}\n\nconst NO_AMBIENT: readonly never[] = [];\n\n/** `registry` and `ambient` as last passed, kept by identity for as long as\n * every tool in them is the same object under the same id. */\nfunction useStableSources<T extends AnyTool, A extends Contribution<unknown>>(\n registry: Record<string, T>,\n ambient: readonly A[] | undefined,\n): { registry: Record<string, T>; ambient: readonly A[] } {\n return useStableByContent(\n { registry, ambient: ambient ?? NO_AMBIENT },\n (a, b) => sameRecord(a.registry, b.registry) && sameList(a.ambient, b.ambient),\n );\n}\n\nfunction sameRecord<T>(a: Record<string, T>, b: Record<string, T>): boolean {\n const ak = Object.keys(a);\n if (ak.length !== Object.keys(b).length) return false;\n return ak.every((k) => k in b && a[k] === b[k]);\n}\n\nfunction sameEligibility(a: Eligibility | undefined, b: Eligibility): boolean {\n if (!a) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof Eligibility>;\n for (const key of keys) if (a[key] !== b[key]) return false;\n return true;\n}\n\n/**\n * Manages the active tool and hotkey slot; a thin shim over\n * {@link useContributions}.\n *\n * Requires `<ActiveToolContextProvider>` (or `<WeaselProvider>` /\n * `<SceneCanvas>`, which mount one internally) in scope: active/hotkey state\n * lives in the context.\n *\n * **First mount wins**: if the context's slot is unseeded on first mount,\n * `useTools` pushes `opts.active` to the context. Subsequent mounts respect\n * whatever the context currently holds.\n */\nexport function useTools<TOverlay = KernelOverlay>(\n opts: UseToolsOptions<TOverlay>,\n): ToolsApi<TOverlay> {\n const initialActive = opts.active ?? null;\n if (initialActive !== null && !(initialActive in opts.registry)) {\n throw new Error(`useTools: active \"${initialActive}\" not in registry`);\n }\n\n const ctx = useActiveToolContext();\n\n // Rebuilt when the tools themselves change, not the objects holding them:\n // callers commonly pass `opts.registry` / `opts.ambient` as literals made\n // every render, while a tool redefined under an existing id must replace it.\n const sources = useStableSources(opts.registry, opts.ambient);\n const slotted = useMemo(() => {\n const registry: Record<string, Tool<TOverlay>> = {};\n for (const [id, tool] of Object.entries(sources.registry)) {\n registry[id] = declareSlot(tool, 'focus');\n }\n const ambient = sources.ambient.map((t) => declareSlot(t, 'always'));\n const byId = new Map<string, Contribution<TOverlay>>();\n for (const tool of [...Object.values(registry), ...ambient]) {\n const prior = byId.get(tool.id);\n if (prior) byId.set(tool.id, { ...tool, eligibility: { ...prior.eligibility, ...tool.eligibility } });\n else byId.set(tool.id, tool);\n }\n return { registry, ambient, entries: [...byId.values()] };\n }, [sources]);\n\n const contributions = useContributions<TOverlay>({\n entries: slotted.entries,\n focused: initialActive,\n ...(opts.modes ? { modes: opts.modes } : {}),\n });\n\n const hotkeyEngaged = ctx.hotkeyStack.at(-1) ?? null;\n\n // Refs so the memoized callbacks below see latest values without\n // re-creating themselves.\n const slottedRef = useLatest(slotted);\n const activeRef = useLatest(contributions.focused);\n const hotkeyRef = useLatest(hotkeyEngaged);\n\n const setFocused = contributions.setFocused;\n const setActive = useCallback(\n (id: string | null) => {\n if (id !== null && !(id in slottedRef.current.registry)) {\n throw new Error(`setActive: \"${id}\" not in registry`);\n }\n dlog('tools', 'active:', activeRef.current, '→', id);\n setFocused(id);\n },\n [setFocused, slottedRef, activeRef],\n );\n\n const engageHotkey = useCallback(\n (id: string) => {\n if (!(id in slottedRef.current.registry)) {\n throw new Error(`engageHotkey: \"${id}\" not in registry`);\n }\n dlog('tools', 'hotkey engaged:', id);\n ctx.pushHotkey(id);\n },\n [ctx, slottedRef],\n );\n\n const disengageHotkey = useCallback(() => {\n if (hotkeyRef.current) dlog('tools', 'hotkey disengaged:', hotkeyRef.current);\n ctx.popHotkey();\n }, [ctx, hotkeyRef]);\n\n // May be called while rendering, so it reads this render's tools, not a ref.\n const has = useCallback(\n (id: string): boolean =>\n id in slotted.registry\n || slotted.ambient.some((t) => t.id === id),\n [slotted],\n );\n\n // Memoized: a consumer using `tools` as an effect dep loops infinitely on\n // identity churn when it setStates from inside that effect.\n const active = contributions.focused;\n const getActiveOverlays = contributions.overlays;\n return useMemo(\n () => ({\n active,\n setActive,\n hotkeyEngaged,\n engageHotkey,\n disengageHotkey,\n ambient: slotted.ambient,\n registry: slotted.registry,\n has,\n getActiveOverlays,\n }),\n [active, setActive, hotkeyEngaged, engageHotkey, disengageHotkey, has, getActiveOverlays, slotted],\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/interactions/actions/activeToolContext.tsx","../src/interactions/actions/depRegistry.tsx","../src/menus/MenuHostContext.tsx","../src/interactions/actions/ActionsProvider.tsx","../src/tools/useToolLifecycle.ts","../src/interactions/dispatcher/dispatchCore.ts","../src/interactions/dispatcher/dispatcherWatch.ts","../src/interactions/dispatcher/underPointer.ts","../src/interactions/dispatcher/channels/carry.ts","../src/interactions/dispatcher/channels/contextMenu.ts","../src/interactions/dispatcher/channels/hoverCursor.ts","../src/interactions/dispatcher/channels/ingest.ts","../src/interactions/dispatcher/channels/keyboard.ts","../src/interactions/dispatcher/channels/listeners.ts","../src/interactions/dispatcher/channels/pointer.ts","../src/interactions/dispatcher/channels/webkitPinch.ts","../src/interactions/dispatcher/channels/wheel.ts","../src/interactions/dispatcher/attachInput.ts","../src/interactions/dispatcher/useGestureDispatcher.tsx","../src/interactions/actions/useCommand.ts","../src/interactions/actions/inputScope.tsx","../src/interactions/actions/useOngoingAction.ts","../src/ambient/PointerContext.tsx","../src/ambient/SelectionContext.tsx","../src/contributions/useContributions.ts","../src/tools/useTools.ts"],"names":["createContext","useState","jsx","useContext","useEffect","useLatest","useMemo","useRef","useCallback","useSyncExternalStore","Fragment","useStableByContent","isDev","sameList"],"mappings":";;;;;;;;;AA+CO,IAAM,QAAA,GAAN,cAAuB,SAAA,CAAoB;AAAA,EACxC,KAAA;AAAA,EACA,KAAA,GAAkF,IAAA;AAAA,EAE1F,WAAA,CAAY,MAAA,EAAyB,QAAA,EAAmB,IAAA,EAAe,aAAA,EAA8B;AACnG,IAAA,KAAA,CAAM,QAAQ,QAAQ,CAAA;AAGtB,IAAA,IAAA,CAAK,KAA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AA,EAAe,cAAc,eAAA,EAAiB,GAAA,EAAK,mBAAmB,OAAO;AAAA,GACnG;AACF","file":"react.js","sourcesContent":["/**\n * ActiveToolContext — the currently active tool id and a hotkey stack (tools\n * held active temporarily, e.g. space-for-hand).\n *\n * The state hangs on the same scope tree as the actions and dep registries:\n * every canvas's input scope owns a tool of its own unless it joins a yoke,\n * and a provider above reads and writes the tool of the scope last used.\n */\n\nimport {\n createContext,\n useContext,\n useMemo,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { ScopeNode } from './scopeNode';\n\n/** Which tool is active, plus the stack of tools temporarily held active by a\n * hotkey (space-for-hand and the like). The dispatcher reads this to decide\n * whose bindings are in scope. */\nexport interface ActiveToolContextValue {\n /** The focused tool's id, or `null` when no tool holds the active slot —\n * a canvas can run on ambient bindings alone. */\n active: string | null;\n hotkeyStack: string[];\n setActive(id: string | null): void;\n pushHotkey(id: string): void;\n /**\n * Disengage a hotkey-held tool. With `id`, removes that tool's own entry\n * wherever it now sits — holds do not have to come up in the order they went\n * down, and popping the top would disengage a tool whose key is still held.\n * With no id, pops the top.\n */\n popHotkey(id?: string): void;\n}\n\ninterface ToolState {\n active: string | null;\n hotkeyStack: string[];\n}\n\n/**\n * One node of the tool tree. A node that `owns` a tool holds its state; one\n * that does not — a scope inside a yoke — reads and writes its yoke's.\n */\nexport class ToolNode extends ScopeNode<ToolNode> {\n private state: ToolState | null;\n private value: { from: ToolNode; state: ToolState; out: ActiveToolContextValue } | null = null;\n\n constructor(parent: ToolNode | null, descends: boolean, owns: boolean, initialActive: string | null) {\n super(parent, descends);\n // A new scope starts on the tool in effect around it, so a tool a\n // consumer seeded above a canvas before it mounted is not lost.\n this.state = owns\n ? { active: initialActive ?? parent?.owner().state?.active ?? null, hotkeyStack: [] }\n : null;\n }\n\n /** The node whose tool a read here resolves to. */\n owner(): ToolNode {\n for (const n of this.start().chain()) if (n.state) return n;\n return this;\n }\n\n private update(next: (s: ToolState) => ToolState): void {\n const owner = this.owner();\n if (!owner.state) return;\n const updated = next(owner.state);\n if (updated === owner.state) return;\n owner.state = updated;\n owner.changed();\n }\n\n /** A stable value per owner and state, for `useSyncExternalStore`. */\n snapshot(): ActiveToolContextValue {\n const from = this.owner();\n const state = from.state ?? { active: null, hotkeyStack: [] };\n const cached = this.value;\n if (cached && cached.from === from && cached.state === state) return cached.out;\n const out: ActiveToolContextValue = {\n active: state.active,\n hotkeyStack: state.hotkeyStack,\n setActive: (id) => this.update((s) => (s.active === id ? s : { ...s, active: id })),\n pushHotkey: (id) => this.update((s) => ({ ...s, hotkeyStack: [...s.hotkeyStack, id] })),\n popHotkey: (id) =>\n this.update((s) => {\n const stack = s.hotkeyStack;\n if (stack.length === 0) return s;\n if (id === undefined) return { ...s, hotkeyStack: stack.slice(0, -1) };\n const i = stack.lastIndexOf(id);\n return i === -1 ? s : { ...s, hotkeyStack: [...stack.slice(0, i), ...stack.slice(i + 1)] };\n }),\n };\n this.value = { from, state, out };\n return out;\n }\n\n subscribe = (listener: () => void): (() => void) => this.tree.listeners.subscribe(listener);\n}\n\nconst ActiveToolContext = createContext<ToolNode | null>(null);\n\n/** @internal The context `<InputScope>` and `<Yoke>` provide a tool node through. */\nexport const ActiveToolNodeContext = ActiveToolContext;\n\n/** Props for `<ActiveToolContextProvider>`. */\nexport interface ActiveToolContextProviderProps {\n children: ReactNode;\n /** Seeds the active slot, and wins over the first `useTools` call's\n * `active`. Omitted, the slot starts empty and that call seeds it. */\n initialActive?: string | null;\n}\n\n/** Provides root active-tool state. Every canvas below has a tool of its own;\n * reads and writes here reach the one last used. */\nexport function ActiveToolContextProvider({\n children,\n initialActive = null,\n}: ActiveToolContextProviderProps) {\n const [node] = useState(() => new ToolNode(null, true, true, initialActive));\n return <ActiveToolContext.Provider value={node}>{children}</ActiveToolContext.Provider>;\n}\n\nfunction useNodeValue(node: ToolNode | null): ActiveToolContextValue | null {\n const subscribe = useMemo(() => node?.subscribe ?? NO_SUBSCRIBE, [node]);\n return useSyncExternalStore(\n subscribe,\n () => node?.snapshot() ?? null,\n () => node?.snapshot() ?? null,\n );\n}\n\nconst NO_SUBSCRIBE = (): (() => void) => () => {};\n\n/** The active-tool state in scope. Throws outside a provider; use\n * `useOptionalActiveToolContext` where one is not guaranteed. */\nexport function useActiveToolContext(): ActiveToolContextValue {\n const value = useNodeValue(useContext(ActiveToolContext));\n if (value === null) {\n throw new Error(\n 'useActiveToolContext: no ActiveToolContextProvider in scope. Wrap your tree with <ActiveToolContextProvider> (typically inside <SceneCanvas>).',\n );\n }\n return value;\n}\n\n/**\n * Like `useActiveToolContext`, but returns `null` when no\n * `<ActiveToolContextProvider>` is in scope instead of throwing.\n */\nexport function useOptionalActiveToolContext(): ActiveToolContextValue | null {\n return useNodeValue(useContext(ActiveToolContext));\n}\n\n/**\n * Mounts an `<ActiveToolContextProvider>` only when no parent provider is in\n * scope; otherwise renders children unwrapped.\n */\nexport function ActiveToolContextProviderIfRoot({\n children,\n}: {\n children: ReactNode;\n}) {\n const parent = useContext(ActiveToolContext);\n if (parent !== null) return <>{children}</>;\n return <ActiveToolContextProvider>{children}</ActiveToolContextProvider>;\n}\n","/** The React seam over the dep registry in `./depNode`: its provider and hooks. */\nimport {\n createContext, useContext, useEffect, useState,\n type ReactNode,\n} from 'react';\nimport type { DepSchema, DepName } from '../../index';\nimport { createDepRegistry, type DepRegistry, type DepSource } from './depNode';\nimport { useLatest } from '@weasel-js/react';\n\nexport type { DepSchema, DepName, DepRegistry, DepSource };\nexport { DepNode, depNodeOf, createDepRegistry } from './depNode';\n\n/** @internal The context `<InputScope>` provides a scope's dep registry through. */\nexport const DepRegistryContext = createContext<DepRegistry | null>(null);\n\n/** Provides the dep registry for a canvas. `<SceneCanvas>` mounts one; a\n * consumer registering its own dep sources must be inside it. */\nexport function DepRegistryProvider({ children }: { children: ReactNode }) {\n const [registry] = useState(createDepRegistry);\n return <DepRegistryContext.Provider value={registry}>{children}</DepRegistryContext.Provider>;\n}\n\n/** The dep registry in scope. Throws outside a `<DepRegistryProvider>`. */\nexport function useDepRegistry(): DepRegistry {\n const r = useContext(DepRegistryContext);\n if (r === null) {\n throw new Error('useDepRegistry: no DepRegistryProvider in scope. Wrap your tree with <DepRegistryProvider> (typically inside <SceneCanvas>).');\n }\n return r;\n}\n\n/**\n * Like `useDepRegistry`, but returns `null` when no `<DepRegistryProvider>` is\n * in scope instead of throwing. Used by `useStandardActions` to preserve its\n * silent-no-op contract when neither provider is present.\n */\nexport function useOptionalDepRegistry(): DepRegistry | null {\n return useContext(DepRegistryContext);\n}\n\n/** Register a live source for `name` for the lifetime of the calling\n * component. The `source` thunk is called at dispatch time and should\n * return the latest value; its `below` reads the source it displaced. */\nexport function useDepSource<K extends DepName>(name: K, source: DepSource<K>) {\n const registry = useDepRegistry();\n const sourceRef = useLatest(source);\n useEffect(() => {\n return registry.register(name, (below) => sourceRef.current(below));\n }, [name, registry, sourceRef]);\n}\n","import { createContext, useContext, useEffect } from 'react';\nimport type { MenuHost } from './menuHost';\nimport type { MenuDef } from './types';\n\nexport const MenuHostContext = createContext<MenuHost | null>(null);\n\n/** The menu host in scope: the nearest `<ActionsProvider>`'s, else the one a\n * canvas with no provider above it makes. Null outside both. */\nexport function useMenuHost(): MenuHost | null {\n return useContext(MenuHostContext);\n}\n\n/** Declare menus for the calling component's lifetime. Memoize `defs`. */\nexport function useMenus(defs: readonly MenuDef[], owner: string | null = null): void {\n const host = useMenuHost();\n useEffect(() => {\n if (!host) return;\n const releases = defs.map((d) => host.define(d, owner));\n return () => { for (const r of releases) r(); };\n }, [host, defs, owner]);\n}\n","/**\n * The React half of the actions registry: the context, the tree node that\n * owns each id → descriptor stack, the providers that mount nodes, and the two\n * hooks. The store contract it implements is in `registry.ts`.\n */\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport type { Action } from './action';\nimport { evaluateEnabled } from './actionEnabled';\nimport { useLatest } from '@weasel-js/react';\nimport {\n useOptionalDepRegistry,\n type DepRegistry,\n type DepName,\n} from './depRegistry';\nimport { buildDepsFromRequires } from './buildDeps';\nimport type { ActionDeps } from './invoker';\nimport type { Dispatcher } from '../dispatcher/dispatcher';\nimport { validateActionId, validateActionDefaultBinding, type ActionsRegistry } from './registry';\nimport { createMenuHost, type MenuHost } from '../../menus/menuHost';\nimport { MenuHostContext } from '../../menus/MenuHostContext';\nimport { pushOwner, ScopeNode } from './scopeNode';\nimport { tuneAction, tunedParams, type ActionTuning } from './tuning';\nimport { isDev } from '@weasel-js/react';\n\n/** @internal Provided by `<ActionsProvider>`, `<InputScope>` and `<Yoke>`. */\nexport const ActionsContext = createContext<ActionsRegistry | null>(null);\n\n/** The deps an action is invoked with: its declared `requires` when it has\n * one, the legacy fixed bag otherwise. The fixed bag has no `applyOps`, so an\n * action that needs the consumer's history must declare it. */\nfunction depsFor(a: Action, r: DepRegistry | null): ActionDeps {\n if (!r) return {};\n if (a.requires) return buildDepsFromRequires(a, r);\n return {\n selection: r.get('selection' as DepName),\n scene: r.get('scene' as DepName),\n history: r.get('history' as DepName),\n view: r.get('view' as DepName),\n activeTool: r.get('activeTool'),\n booleansAdapter: r.get('booleansAdapter' as DepName),\n } as ActionDeps;\n}\n\n/**\n * One node of the actions tree: the actions registered at it, over its\n * parent's. Each id holds a stack of registrants, newest live, so a displaced\n * registrant is restored when the one above it leaves. Every read the registry\n * answers — `list`, `trigger`, `begin` — starts at the node's leaf.\n */\nexport class ActionsNode extends ScopeNode<ActionsNode> {\n private readonly actions = new Map<string, Action[]>();\n private readonly muted = new Map<string, number>();\n private readonly tunings = new Map<string, ActionTuning[]>();\n private readonly dispatchers: Dispatcher[] = [];\n private cache: { version: number; leaf: ActionsNode; list: readonly Action[] } | null = null;\n private host: MenuHost | null = null;\n /** Called on `activate`, so a scope's dep and tool nodes move with it. */\n readonly onActivate: (() => void)[] = [];\n\n constructor(\n parent: ActionsNode | null,\n descends: boolean,\n private readonly contextDeps: () => DepRegistry | null,\n ) {\n super(parent, descends);\n NODES.set(this.registry, this);\n }\n\n private resolve(id: string): Action | undefined {\n for (const n of this.chain()) {\n if (n.muted.has(id)) return undefined;\n const a = n.actions.get(id)?.at(-1);\n if (a) return this.tuned(a);\n }\n return undefined;\n }\n\n /** Every tuning for `id` from the root down to here, root first. */\n private tuningsOf(id: string): ActionTuning[] {\n const tunings: ActionTuning[] = [];\n for (const n of this.chain()) {\n const stack = n.tunings.get(id);\n if (stack) tunings.unshift(...stack);\n }\n return tunings;\n }\n\n /** `a` under every tuning for its id from the root down to here. */\n private tuned(a: Action): Action {\n const tunings = this.tuningsOf(a.id);\n return tunings.length ? tuneAction(a, tunings) : a;\n }\n\n private snapshot(): readonly Action[] {\n const leaf = this.start();\n const cached = this.cache;\n if (cached && cached.version === this.tree.version && cached.leaf === leaf) return cached.list;\n const ids = new Set<string>();\n for (const n of leaf.chain()) for (const id of n.actions.keys()) ids.add(id);\n const out: Action[] = [];\n for (const id of ids) {\n const a = leaf.resolve(id);\n if (a) out.push(a);\n }\n const list = Object.freeze(out);\n this.cache = { version: this.tree.version, leaf, list };\n return list;\n }\n\n private deps(): DepRegistry | null {\n for (const n of this.chain()) {\n const r = n.contextDeps();\n if (r) return r;\n }\n return null;\n }\n\n /** The actions registered at this node itself, live, unmuted and tuned —\n * none from the scopes below it. */\n ownActions(): readonly Action[] {\n const out: Action[] = [];\n for (const [id, stack] of this.actions) {\n if (stack.length > 0 && !this.muted.has(id)) out.push(this.tuned(stack.at(-1)!));\n }\n return out;\n }\n\n /** The deps `a` is invoked with from here: the active scope's, which is\n * what `trigger` and `begin` run it with. */\n depsOf(a: Action): ActionDeps {\n return depsFor(a, this.start().deps());\n }\n\n /** The menu host of this node's tree, made by its root on first ask. Rows\n * resolve and run against the active scope, as chrome's `trigger` does. */\n menuHost(): MenuHost {\n const root = [...this.chain()].at(-1)!;\n return root.host ??= createMenuHost({\n actions: () => root.registry.list(),\n depsFor: (a) => root.depsOf(a),\n trigger: (id, params) => root.registry.trigger(id, params),\n activeTool: () => root.start().deps()?.get('activeTool')?.active ?? null,\n });\n }\n\n private dispatcher(): Dispatcher | null {\n for (const n of this.chain()) {\n const d = n.dispatchers.at(-1);\n if (d) return d;\n }\n return null;\n }\n\n override activate(): void {\n keyHolder = this;\n super.activate();\n for (const f of this.onActivate) f();\n }\n\n readonly registry: ActionsRegistry = {\n register: (action: Action) => {\n validateActionId(action.id);\n validateActionDefaultBinding(action);\n const stack = this.actions.get(action.id);\n if (stack) stack.push(action);\n else this.actions.set(action.id, [action]);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const cur = this.actions.get(action.id);\n if (!cur) return;\n // Our own entry, wherever it now sits: a registrant that was already\n // displaced must take itself out without disturbing the one above it.\n const i = cur.lastIndexOf(action);\n if (i === -1) return;\n cur.splice(i, 1);\n // An emptied stack holds the id's place in registration order until\n // the tick ends, so a release followed at once by a register — what\n // `useAction` does when its action object changes — keeps its slot.\n if (cur.length === 0) {\n queueMicrotask(() => {\n if (cur.length === 0 && this.actions.get(action.id) === cur) this.actions.delete(action.id);\n });\n }\n this.changed();\n };\n },\n unregister: (id: string) => {\n if (this.actions.delete(id)) this.changed();\n },\n mute: (id: string) => {\n this.muted.set(id, (this.muted.get(id) ?? 0) + 1);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const held = this.muted.get(id);\n if (held === undefined) return;\n if (held > 1) this.muted.set(id, held - 1);\n else this.muted.delete(id);\n this.changed();\n };\n },\n tune: (id: string, tuning: ActionTuning) => {\n let stack = this.tunings.get(id);\n if (!stack) this.tunings.set(id, (stack = []));\n const release = pushOwner(stack, tuning);\n this.changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n release();\n if (stack.length === 0) this.tunings.delete(id);\n this.changed();\n };\n },\n paramsOf: (id: string, given?: Record<string, unknown>) => tunedParams(this.tuningsOf(id), given),\n list: () => this.snapshot(),\n trigger: (id: string, params?: Record<string, unknown>) => {\n const leaf = this.start();\n const a = leaf.resolve(id);\n if (!a?.invoker || a.invoker.timing !== 'immediate') return false;\n const deps = leaf.depsOf(a);\n if (!evaluateEnabled(a, deps, pointOf(params)).enabled) return false;\n try {\n a.invoker.run(deps, params);\n } catch (err) {\n console.error(`weasel ActionsRegistry: action \"${id}\" threw`, err);\n }\n return true;\n },\n preview: (id: string, params?: Record<string, unknown>) => {\n const leaf = this.start();\n const a = leaf.resolve(id);\n if (!a?.preview) return NO_PREVIEW;\n const deps = leaf.depsOf(a);\n if (!evaluateEnabled(a, deps, pointOf(params)).enabled) return NO_PREVIEW;\n let stop: (() => void) | void;\n try {\n stop = a.preview(deps, params);\n } catch (err) {\n console.error(`weasel ActionsRegistry: preview of \"${id}\" threw`, err);\n return NO_PREVIEW;\n }\n if (typeof stop !== 'function') return NO_PREVIEW;\n let down = false;\n return () => {\n if (down) return;\n down = true;\n try {\n stop();\n } catch (err) {\n console.error(`weasel ActionsRegistry: preview of \"${id}\" threw as it ended`, err);\n }\n };\n },\n subscribe: (listener: () => void) => this.tree.listeners.subscribe(listener),\n setDispatcher: (d: Dispatcher | null) => pushOwner(this.dispatchers, d),\n begin: (id: string, params?: Record<string, unknown>) => {\n const leaf = this.start();\n const a = leaf.resolve(id);\n const disp = leaf.dispatcher();\n if (!a || !disp) return null;\n return disp.beginUiOngoing(id, leaf.depsOf(a), params);\n },\n activate: () => this.activate(),\n isActive: () => this.isActive(),\n holdsKeys: () => keyHolder === this,\n dropKeys: () => { if (keyHolder === this) keyHolder = null; },\n };\n}\n\nconst NO_PREVIEW = (): void => {};\n\n/** The world point a trigger's params carry, when they carry both coordinates. */\nfunction pointOf(params: Record<string, unknown> | undefined): { x: number; y: number } | undefined {\n const { worldX: x, worldY: y } = params ?? {};\n return typeof x === 'number' && typeof y === 'number' ? { x, y } : undefined;\n}\n\n/** The node last activated on the page, across every tree: where a key that\n * reaches the page goes. Null until something is pressed or scrolled in. */\nlet keyHolder: ActionsNode | null = null;\n\nconst NODES = new WeakMap<ActionsRegistry, ActionsNode>();\n\n/** The tree node behind `registry`, when it is one of ours. */\nexport function actionsNodeOf(registry: ActionsRegistry | null): ActionsNode | null {\n return registry ? (NODES.get(registry) ?? null) : null;\n}\n\n/**\n * Mounts a root `ActionsRegistry` for its lifetime. Children call\n * `useActionsRegistry()` or `useAction()` to participate. Mounts no input\n * listener of its own — the gesture dispatcher owns input.\n */\nexport function ActionsProvider({ children }: { children: ReactNode }): ReactElement {\n // `trigger` consults the dep registry in scope, so actions can be fired\n // imperatively from ActionBar / palette callers.\n const depReg = useOptionalDepRegistry();\n const depRegRef = useLatest<DepRegistry | null>(depReg);\n const node = useMemo(() => new ActionsNode(null, true, () => depRegRef.current), [depRegRef]);\n return (\n <ActionsContext.Provider value={node.registry}>\n <MenuHostContext.Provider value={node.menuHost()}>{children}</MenuHostContext.Provider>\n </ActionsContext.Provider>\n );\n}\n\nconst IS_DEV = isDev();\n\n/**\n * Returns the `ActionsRegistry` in scope, or `null` when there is none.\n */\nexport function useActionsRegistry(): ActionsRegistry | null {\n return useContext(ActionsContext);\n}\n\n/**\n * Register an `Action` for the lifetime of the calling component. No-op (with\n * a dev-only warning) when no `ActionsProvider` is in scope. Re-registers on\n * `action` reference change (consumers should memoize stable identities to\n * avoid churn).\n */\nexport function useAction(action: Action): void {\n const reg = useActionsRegistry();\n useEffect(() => {\n if (!reg) {\n if (IS_DEV) {\n console.warn(\n `useAction(\"${action.id}\"): no <ActionsProvider> is in scope, so the action was not registered and its bindings will never fire.`,\n );\n }\n return;\n }\n return reg.register(action);\n }, [reg, action]);\n}\n","import { useCallback, useEffect, useRef } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { Contribution } from '../contributions/types';\nimport { isTool } from './types';\n\nexport interface ToolLifecycleOptions {\n entriesById: ReadonlyMap<string, Contribution<unknown>>;\n /** The active tool's id, and the tools held on a hotkey, as the input scope reports them. */\n active: string | null;\n hotkeyStack: readonly string[];\n /** The active tool changed away from a tool. Not called when an empty slot is first filled. */\n onSwitch?: () => void;\n}\n\n/**\n * Runs each tool's `onActivate` / `onDeactivate` around the time it is live:\n * holding the active slot, or sitting in the hotkey stack.\n *\n * `onSwitch` runs between the outgoing tools' `onDeactivate` and the incoming\n * tools' `onActivate`, so whatever it ends is over before the new tool hears\n * it is live.\n */\nexport function useToolLifecycle(opts: ToolLifecycleOptions): void {\n const { active, hotkeyStack } = opts;\n const liveRef = useRef<ReadonlySet<string>>(new Set());\n const prevActiveRef = useRef(active);\n const entriesRef = useLatest(opts.entriesById);\n const onSwitchRef = useLatest(opts.onSwitch);\n\n const fire = useCallback((id: string, hook: 'onActivate' | 'onDeactivate'): void => {\n const tool = entriesRef.current.get(id);\n if (!tool || !isTool(tool)) return;\n const fn = tool[hook];\n if (!fn) return;\n try {\n fn();\n } catch (err) {\n console.error(`weasel: tool \"${id}\".${hook} threw`, err);\n }\n }, [entriesRef]);\n\n useEffect(() => {\n const prev = liveRef.current;\n const next = new Set<string>(active === null ? hotkeyStack : [active, ...hotkeyStack]);\n liveRef.current = next;\n for (const id of prev) if (!next.has(id)) fire(id, 'onDeactivate');\n // An empty slot being seeded has no outgoing tool, so nothing to end.\n if (prevActiveRef.current !== null && prevActiveRef.current !== active) onSwitchRef.current?.();\n prevActiveRef.current = active;\n for (const id of next) if (!prev.has(id)) fire(id, 'onActivate');\n });\n\n useEffect(() => () => {\n const live = liveRef.current;\n liveRef.current = new Set();\n for (const id of live) fire(id, 'onDeactivate');\n }, [fire]);\n}\n","/**\n * The routing core every input channel of `useGestureDispatcher` shares: which\n * view an event belongs to, that view's dispatcher and context, and the one\n * `dispatch` every channel sends through.\n */\nimport type { DepName, DepSchema } from '../../index';\nimport { clientToCanvas } from '../../viewport/clientToCanvas';\nimport type { DepRegistry } from '../actions/depRegistry';\nimport type { ActionsRegistry } from '../actions/registry';\nimport type { Dispatcher, DispatcherContext, KeyReach } from './dispatcherApi';\nimport type { DispatcherViewTarget, UseGestureDispatcherOptions } from './gestureDispatcherOptions';\nimport type { InputEvent } from './matcher';\n\n/** What a channel reads and calls. Every member is a closure over the\n * hook's effect, so a channel may destructure it. */\nexport interface DispatchCore {\n readonly canvas: HTMLElement | null;\n /** The dispatch record for the routed view. */\n target(): DispatcherViewTarget;\n /** Route an event with coordinates. `pointerId` is `null` for input with\n * nothing to capture: wheel, hover, contextmenu, drop. */\n routeAt(pointerId: number | null, clientX: number, clientY: number): void;\n /** The routed view's id, and a way to put one back: an event that\n * dispatches later runs on the view it landed in. */\n routedView(): string | null;\n setRoutedView(id: string | null): void;\n dispatcherNow(): Dispatcher;\n ctxNow(): DispatcherContext;\n /** Client point to the routed view's world point. */\n toWorld(clientX: number, clientY: number): { x: number; y: number };\n /** Client point to CSS pixels from the canvas's top-left, the space `zoomAt`\n * anchors in and a `space: 'screen'` layer draws in. Unchanged with no canvas. */\n toCanvasLocal(clientX: number, clientY: number): { x: number; y: number };\n /** Dispatch on the routed view's dispatcher, or on `on` for an event that\n * belongs to the one an earlier event ran on. */\n dispatch(ev: InputEvent, on?: Dispatcher, reach?: KeyReach): 'handled' | 'unhandled';\n /** Whether a key or a paste that reached the page is this dispatcher's to\n * handle: its canvas was the last one pressed or scrolled in, or it has no\n * canvas and its input scope is the active one. */\n holdsKeys(): boolean;\n /** Whether the pointer is over the canvas, as its enter, move and leave\n * report it. Always false with no canvas. */\n pointerOver(): boolean;\n setPointerOver(over: boolean): void;\n /** Make this canvas's input scope the active one. */\n activate(): void;\n /** Whether the hook's effect has been torn down. */\n disposed(): boolean;\n}\n\n/** The pointer channel's core: a pointer stays pinned to the view it went down in. */\nexport interface PointerDispatchCore extends DispatchCore {\n /** Route a pointerdown, pinning the pointer to the view it landed in. */\n routeDown(pointerId: number, clientX: number, clientY: number): void;\n /** Unpin a pointer whose release or cancel has been dispatched in full. */\n routeRelease(pointerId: number): void;\n}\n\n/** What a core reads. Each is a thunk over the hook's latest render, except\n * `canvas`, which is fixed for the life of a listener set. */\nexport interface DispatchCoreSources {\n canvas: HTMLElement | null;\n /** The record the hook's flat options describe: view zero. */\n root(): DispatcherViewTarget;\n views(): UseGestureDispatcherOptions['views'];\n /** The host's client-to-canvas-local mapping, if it supplies one. */\n clientToLocal(): UseGestureDispatcherOptions['clientToLocal'];\n /** The dispatcher context, less the parts that depend on the routed view. */\n context(): DispatcherContext;\n actions(): ActionsRegistry;\n /** Told of the dispatcher each event is about to run on. A view's appears\n * with no render of the hook, so this is where one is first seen. */\n uses(dispatcher: Dispatcher): void;\n disposed(): boolean;\n}\n\nexport function createDispatchCore(src: DispatchCoreSources): PointerDispatchCore {\n const { canvas } = src;\n // An id rather than a record: the record is rebuilt every render, so holding\n // one across events would dispatch through last render's lookups.\n let routedId: string | null = null;\n let over = false;\n\n const target = (): DispatcherViewTarget => {\n if (routedId === null) return src.root();\n // A resolved id with no live record falls back to the root.\n return src.views()?.targets().find((t) => t.id === routedId) ?? src.root();\n };\n const dispatcherNow = (): Dispatcher => target().dispatcher;\n const routedDeps = withViewDeps(() => src.context().depRegistry, () => target().deps?.());\n const routedRuleCtx = (): ReturnType<NonNullable<DispatcherViewTarget['getRuleCtx']>> =>\n target().getRuleCtx?.();\n const ctxNow = (): DispatcherContext => ({\n ...src.context(), depRegistry: routedDeps, getRuleCtx: routedRuleCtx, viewId: target().id,\n });\n\n return {\n canvas,\n target,\n routeAt: (pointerId, clientX, clientY) => {\n routedId = src.views()?.resolver.at(pointerId, clientX, clientY).id ?? null;\n },\n routeDown: (pointerId, clientX, clientY) => {\n routedId = src.views()?.resolver.begin(pointerId, clientX, clientY).id ?? null;\n },\n routeRelease: (pointerId) => { src.views()?.resolver.end(pointerId); },\n routedView: () => routedId,\n setRoutedView: (id) => { routedId = id; },\n dispatcherNow,\n ctxNow,\n toWorld: (cx, cy) => {\n const fn = target().clientToWorld;\n return fn ? fn(cx, cy) : { x: cx, y: cy };\n },\n toCanvasLocal: (cx, cy) => {\n const own = src.clientToLocal();\n if (own) return own(cx, cy);\n if (!canvas) return { x: cx, y: cy };\n const [x, y] = clientToCanvas(canvas, cx, cy);\n return { x, y };\n },\n dispatch: (ev, on, reach) => {\n const d = on ?? dispatcherNow();\n src.uses(d);\n return d.handleInput(ev, reach ? { ...ctxNow(), keyReach: reach } : ctxNow());\n },\n holdsKeys: () => (canvas ? src.actions().holdsKeys() : src.actions().isActive()),\n pointerOver: () => over,\n setPointerOver: (next) => { over = canvas !== null && next; },\n activate: () => src.actions().activate(),\n disposed: src.disposed,\n };\n}\n\n/**\n * `base` with the routed view's own deps in front of it. Both sides are read\n * through thunks, so the result is stable for the life of a listener set while\n * still answering for whichever view the current event landed in.\n */\nexport function withViewDeps(\n base: () => DepRegistry,\n overlay: () => Partial<DepSchema> | undefined,\n): DepRegistry {\n return {\n register: (name, source) => base().register(name, source),\n get: <K extends DepName>(name: K): DepSchema[K] | undefined => {\n const own = overlay()?.[name];\n if (own !== undefined) return own as DepSchema[K];\n return base().get(name);\n },\n };\n}\n","import type { Dispatcher } from './dispatcherApi';\n\n/** One subscription per live dispatcher. */\nexport interface DispatcherWatch {\n /** Subscribe to each of `live` not yet watched, and drop any no longer among them. */\n sync(live: readonly Dispatcher[]): void;\n stop(): void;\n}\n\n/** Calls `onChange` whenever a watched dispatcher notifies: an event or a\n * cancel that found or left a gesture in flight. */\nexport function dispatcherWatch(onChange: () => void): DispatcherWatch {\n const subscriptions = new Map<Dispatcher, () => void>();\n return {\n sync(live) {\n for (const d of live) {\n if (!subscriptions.has(d)) subscriptions.set(d, d.subscribe(onChange));\n }\n if (subscriptions.size === live.length) return;\n const keep = new Set(live);\n for (const [d, unsubscribe] of subscriptions) {\n if (keep.has(d)) continue;\n unsubscribe();\n subscriptions.delete(d);\n }\n },\n stop() {\n for (const unsubscribe of subscriptions.values()) unsubscribe();\n subscriptions.clear();\n },\n };\n}\n","import type { BodyKind, BodyTarget, DoubleClickBody, EventModifiers } from '@weasel-js/gestures';\nimport type { AffordanceHit } from '../actions/invoker';\nimport type { DispatcherViewTarget } from './gestureDispatcherOptions';\n\n/** The modifiers held and what sits under the pointer, as a pointer event carries them. */\nexport type UnderPointer = EventModifiers & {\n affordance?: AffordanceHit;\n bodyTarget?: BodyTarget;\n bodyKind?: BodyKind;\n doubleClickBody?: DoubleClickBody;\n};\n\n/** Hit-test `view` at the world point `w`, for a pointer holding `mods`. */\nexport function underPointer(view: DispatcherViewTarget, mods: EventModifiers, w: { x: number; y: number }): UnderPointer {\n const affordance = view.affordanceAt?.(w) ?? undefined;\n const body = view.classifyTarget?.(w);\n return {\n altKey: mods.altKey, ctrlKey: mods.ctrlKey, metaKey: mods.metaKey, shiftKey: mods.shiftKey,\n ...(affordance !== undefined ? { affordance } : {}),\n ...(body?.body !== undefined ? { bodyTarget: body.body } : {}),\n ...(body?.kind !== undefined ? { bodyKind: body.kind } : {}),\n ...(body?.doubleClick !== undefined ? { doubleClickBody: doubleClickBodyOf(body.doubleClick) } : {}),\n };\n}\n\nfunction doubleClickBodyOf(named: { body: BodyTarget; kind?: BodyKind }): DoubleClickBody {\n return { bodyTarget: named.body, ...(named.kind !== undefined ? { bodyKind: named.kind } : {}) };\n}\n","/**\n * Carries (`startCarry`) over the canvas: the element registers as a carry\n * surface, and each step of a carry over it is dispatched as a `carry` event.\n */\nimport { addCarrySurface, type CarryPointer, type CarryStage } from '../../carry/carry';\nimport type { DispatchCore } from '../dispatchCore';\nimport { carryGestureId } from '../gestureIds';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\nexport function carryInput(core: DispatchCore): () => void {\n const { canvas } = core;\n if (!canvas) return () => {};\n // The view each pointer's carry came over in: the handle it started lives\n // on that view's dispatcher, so its moves and its release go there too.\n const pinned = new Map<number, string | null>();\n\n return addCarrySurface({\n element: canvas,\n receive(stage: CarryStage, payload, at: CarryPointer, pointerId) {\n if (core.disposed()) return 'unhandled';\n // Built in the view routed at the time, which places it and classifies what is under it.\n const event = (): InputEvent => {\n const w = core.toWorld(at.clientX, at.clientY);\n const { affordance, bodyTarget, bodyKind } = underPointer(core.target(), at, w);\n return {\n kind: 'carry', stage, pointerId, type: payload.type, value: payload.value,\n x: w.x, y: w.y, clientX: at.clientX, clientY: at.clientY,\n altKey: at.altKey, ctrlKey: at.ctrlKey, metaKey: at.metaKey, shiftKey: at.shiftKey,\n ...(affordance !== undefined ? { affordance } : {}),\n ...(bodyTarget !== undefined ? { bodyTarget } : {}),\n ...(bodyKind !== undefined ? { bodyKind } : {}),\n };\n };\n const routedNow = core.routedView();\n try {\n if (stage === 'enter') {\n core.routeAt(null, at.clientX, at.clientY);\n pinned.set(pointerId, core.routedView());\n return core.dispatch(event());\n }\n if (pinned.has(pointerId)) core.setRoutedView(pinned.get(pointerId)!);\n if (stage === 'drop' || stage === 'leave') pinned.delete(pointerId);\n if (stage !== 'leave' && !core.dispatcherNow().inFlight().has(carryGestureId(pointerId))) {\n // A move or a release nothing has taken yet is the walk's again, in\n // whichever view it is over; a handle a move starts there keeps it.\n core.routeAt(null, at.clientX, at.clientY);\n if (stage === 'move') pinned.set(pointerId, core.routedView());\n }\n return core.dispatch(event());\n } finally {\n core.setRoutedView(routedNow);\n }\n },\n });\n}\n","/** The contextmenu channel: a right-click. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\n/**\n * `takeNativeHold` answers whether a touch or pen hold is in progress, firing\n * its long-press if that is still pending. A browser that sends `contextmenu`\n * for a hold (Android Chrome) is reporting the same hold the dispatcher times,\n * so the event stands for the long-press and never dispatches a second menu.\n */\nexport function contextMenuInput(core: DispatchCore, takeNativeHold: () => boolean): (e: MouseEvent) => void {\n const { routeAt, toWorld, target, dispatch } = core;\n\n const onContextMenu = (e: MouseEvent) => {\n // Suppress native menu so tools/actions own the right-click UX.\n e.preventDefault();\n if (takeNativeHold()) return;\n // The keyboard ContextMenu key sends this with no press before it, and\n // the menu's rows resolve through the active scope.\n core.activate();\n routeAt(null, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n // A secondary button never reaches `onPointerDown`, so unlike click and\n // long-press there is no press to replay the classification from.\n const ev: InputEvent = {\n kind: 'contextmenu',\n target: e.target,\n x: w.x,\n y: w.y,\n clientX: e.clientX,\n clientY: e.clientY,\n ...underPointer(target(), e, w),\n };\n dispatch(ev);\n };\n\n return onContextMenu;\n}\n","/**\n * The hover half of the pointer channel: a `hover` event for each move of the\n * pointer, marked `held` while a button is down, and the cursor shown for what\n * a press there would do.\n */\nimport { createCursorSink, resolveCursorTier, type CursorSink, type CursorSpec, type PaintedCursorState } from '@weasel-js/cursor';\nimport type { EventModifiers, HoverWhere } from '@weasel-js/gestures';\nimport { actionCursor } from '../../actions/action';\nimport type { DispatchCore } from '../dispatchCore';\nimport type { ResolveOnlyResult } from '../dispatcherApi';\nimport type { InputEvent } from '../matcher';\nimport { underPointer, type UnderPointer } from '../underPointer';\nimport { anyBinding } from '../walk';\n\ntype Hover = EventModifiers & { clientX: number; clientY: number };\n\nconst whereOf = ({ affordance, bodyTarget, bodyKind }: UnderPointer): HoverWhere => ({\n ...(affordance !== undefined ? { affordance } : {}),\n ...(bodyTarget !== undefined ? { bodyTarget } : {}),\n ...(bodyKind !== undefined ? { bodyKind } : {}),\n});\n\nconst hoverOf = (e: Hover): Hover => ({\n clientX: e.clientX, clientY: e.clientY,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n});\n\nexport interface HoverCursorInput {\n /** A pointer moved, and its move has been dispatched. */\n moved(e: PointerEvent): void;\n /** A pointer was released: re-resolve where it let go. */\n released(e: PointerEvent): void;\n onLeave(): void;\n /** A modifier or hotkey changed, which re-routes the predicted drag with no pointer movement. */\n onKey(e: KeyboardEvent): void;\n clear(): void;\n}\n\n/**\n * Idle, the cursor is the first of: an affordance hit's `cursor`; the\n * `Action.cursor` of the action a drag from here would route to; that of the\n * action a click here would route to; no override. Mid-gesture it is the\n * in-flight action's `activeCursor`.\n */\nexport function hoverCursorInput(\n core: DispatchCore,\n paintedCursor: () => PaintedCursorState | undefined,\n /** Pointers down on the canvas with any button, `heldPointers`' count. */\n pointersHeld: () => number,\n /** The surface's own sink, which also holds its tool cursor. Without one\n * the override is written to the canvas and removed when it clears. */\n cursorSink: () => CursorSink | undefined = () => undefined,\n): HoverCursorInput {\n const { canvas, routeAt, toWorld, target, dispatch, dispatcherNow, ctxNow } = core;\n const ownSink = createCursorSink({ element: () => canvas, painted: paintedCursor });\n const override = {\n apply: (spec: CursorSpec | null): void =>\n (cursorSink() ?? ownSink).setOverride(spec === null ? null : resolveCursorTier(spec)),\n clear: (): void => (cursorSink() ?? ownSink).setOverride(null),\n };\n let last: Hover | null = null;\n /** What the last move found under the pointer, so its hover and its cursor hit-test once. */\n let facts: { at: Hover; where: UnderPointer } | null = null;\n /** Whether a binding hears a held pointer's moves, asked once a press, so a\n * drag nothing listens to is not hit-tested on every move. */\n let heldHeard: boolean | null = null;\n const hears = (): boolean => {\n if (pointersHeld() === 0) {\n heldHeard = null;\n return true;\n }\n heldHeard ??= anyBinding(ctxNow(), (s) => s.kind === 'hover' && s.held !== undefined);\n return heldHeard;\n };\n\n const resolve = (): void => {\n if (!canvas || !last) return;\n if (pointersHeld() > 0 || dispatcherNow().inFlight().size > 0) {\n override.apply(dispatcherNow().inFlightCursor());\n return;\n }\n const h = last;\n // Only idle: mid-gesture the branch above returned, so a pinned pointer\n // is never unpinned by a hover refresh.\n routeAt(null, h.clientX, h.clientY);\n const w = toWorld(h.clientX, h.clientY);\n const where = facts?.at === h ? facts.where : underPointer(target(), h, w);\n if (where.affordance?.cursor) {\n override.apply(where.affordance.cursor);\n return;\n }\n const ctx = ctxNow();\n const d = dispatcherNow();\n const press: InputEvent = { kind: 'pointerdown', x: w.x, y: w.y, clientX: h.clientX, clientY: h.clientY, ...where };\n if (ctx.trace?.recording()) ctx.trace.setLive(() => d.explain(press, ctx));\n const click: InputEvent = { kind: 'click', x: w.x, y: w.y, pressX: w.x, pressY: w.y, ...where };\n const cursorOf = (r: ResolveOnlyResult | null) => (r ? actionCursor(r.action, r.params) : undefined);\n const cursor = cursorOf(d.resolveOnly(press, ctx)) ?? cursorOf(dispatcherNow().resolveOnly(click, ctx));\n override.apply(cursor ?? null);\n };\n\n const refresh = (): void => {\n resolve();\n // After the cursor is resolved, not before: on the move that first selects\n // a painted cursor, a position written ahead of the decision is discarded.\n // Guarded on `active()`, so a CSS cursor costs no layout read per move.\n const painted = paintedCursor();\n if (!painted?.active() || !canvas || !last) return;\n const local = core.toCanvasLocal(last.clientX, last.clientY);\n painted.setPointer(local.x, local.y);\n };\n // A tick later, so state the event changed (hotkey stack, active tool,\n // selection) has committed before the prediction reruns.\n const refreshSoon = (): void => {\n setTimeout(() => { if (!core.disposed()) refresh(); }, 0);\n };\n\n const hoverAt = (at: Hover): void => {\n const w = toWorld(at.clientX, at.clientY);\n const where = underPointer(target(), at, w);\n const from = facts ? { from: whereOf(facts.where) } : {};\n const held = pointersHeld() > 0 ? { held: true } : {};\n facts = { at, where };\n dispatch({ kind: 'hover', x: w.x, y: w.y, clientX: at.clientX, clientY: at.clientY, ...where, ...from, ...held });\n };\n\n return {\n moved(e) {\n last = hoverOf(e);\n if (hears()) hoverAt(last);\n refresh();\n },\n released(e) {\n heldHeard = null;\n last = hoverOf(e);\n refreshSoon();\n },\n onLeave() {\n if (facts) {\n const { at, where } = facts;\n const w = toWorld(at.clientX, at.clientY);\n dispatch({ kind: 'hover', off: true, x: w.x, y: w.y, clientX: at.clientX, clientY: at.clientY, ...where, from: whereOf(where) });\n }\n facts = null;\n last = null;\n ctxNow().trace?.setLive(null);\n paintedCursor()?.clearPointer();\n override.clear();\n },\n onKey(e) {\n if (!last) return;\n const prev = last;\n last = { ...last, altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey };\n const changed = prev.altKey !== last.altKey || prev.ctrlKey !== last.ctrlKey\n || prev.metaKey !== last.metaKey || prev.shiftKey !== last.shiftKey;\n // A modifier changing over a resting pointer is a hover with new modifiers.\n if (changed && hears()) hoverAt(last);\n refreshSoon();\n },\n clear: override.clear,\n };\n}\n","/**\n * External-content ingestion: an OS drop on the canvas, a paste on window.\n * Items are materialized during the event, since a DataTransfer is only live\n * on the event stack; dispatch happens when materialization resolves.\n */\nimport { itemsFromClipboardData, itemsFromDataTransfer, itemTypesFromDataTransfer } from '../../../ingestion/ingestItems';\nimport { isEditableTarget } from '../../keyHelpers';\nimport type { DispatchCore } from '../dispatchCore';\n\n/** Toggled on the canvas while an OS drag hovers it; consumers style it. */\nexport const DROPOVER_CLASS = 'weasel-dropover';\n\nexport function ingestInput(core: DispatchCore): {\n onDragOver: (e: DragEvent) => void;\n onDragLeave: () => void;\n onDrop: (e: DragEvent) => void;\n onPaste: (e: ClipboardEvent) => void;\n} {\n const { canvas, routeAt, toWorld, dispatch } = core;\n\n // Attached to both dragover and dragenter: cancelling dragenter (WHATWG)\n // guarantees the element stays the active drop target and shows the copy\n // cursor on entry rather than waiting for the first dragover tick.\n const onDragOver = (e: DragEvent) => {\n const dt = e.dataTransfer;\n if (!dt) return;\n routeAt(null, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n const wanted = core.dispatcherNow().resolveOnly({\n kind: 'drop', items: itemTypesFromDataTransfer(dt),\n x: w.x, y: w.y, clientX: e.clientX, clientY: e.clientY,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n }, core.ctxNow()) !== null;\n canvas?.classList.toggle(DROPOVER_CLASS, wanted);\n // Left alone, a drag no binding would take stays the page's: no copy\n // cursor, and no `drop` event here to swallow.\n if (!wanted) return;\n e.preventDefault();\n dt.dropEffect = 'copy';\n };\n\n const onDragLeave = () => {\n canvas?.classList.remove(DROPOVER_CLASS);\n };\n\n // No stopPropagation: handled-ness is only known after the async\n // materialization microtask, so a conditional stop (wheel-style) is\n // impossible; an unconditional one would swallow drops the kit doesn't\n // dispatch. Callers that need exclusivity should gate on the action result.\n const onDrop = (e: DragEvent) => {\n canvas?.classList.remove(DROPOVER_CLASS);\n const dt = e.dataTransfer;\n if (!dt) return;\n e.preventDefault();\n routeAt(null, e.clientX, e.clientY);\n const dropView = core.routedView();\n const w = toWorld(e.clientX, e.clientY);\n // Real modifiers forwarded (Option-drag is a copy-drag on macOS); the\n // kit ingest binding declares all modifiers optional, so they can't\n // block the default route — but a consumer binding may key on them.\n const base = {\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n };\n void itemsFromDataTransfer(dt).then((items) => {\n if (core.disposed()) return;\n if (items.length === 0) return;\n // The routed view is whatever moved under the cursor since; the drop\n // runs on the one it landed in, dispatcher and context both.\n const routedNow = core.routedView();\n core.setRoutedView(dropView);\n try {\n dispatch({\n kind: 'drop', items,\n x: w.x, y: w.y, clientX: e.clientX, clientY: e.clientY,\n ...base,\n });\n } finally {\n core.setRoutedView(routedNow);\n }\n });\n };\n\n const onPaste = (e: ClipboardEvent) => {\n // Text-editing surfaces (inputs, the text-edit overlay) own their own\n // paste — never steal it for scene ingestion.\n if (e.defaultPrevented || isEditableTarget(e.target)) return;\n // Every dispatcher hears paste on window; only the one holding the keys acts.\n if (!core.holdsKeys()) return;\n const cd = e.clipboardData;\n if (!cd) return;\n const items = itemsFromClipboardData(cd);\n if (items.length === 0) return;\n // Wheel's shape: dispatch first, suppress the default only when a\n // binding claimed it. Clipboard items materialize synchronously, so\n // unlike `onDrop` the result is known while `preventDefault` is still\n // honored — and a paste no binding wanted stays the page's to handle.\n const result = dispatch({\n kind: 'paste', items,\n // ClipboardEvent carries no modifier state.\n altKey: false, ctrlKey: false, metaKey: false, shiftKey: false,\n });\n if (result === 'handled') e.preventDefault();\n };\n\n return { onDragOver, onDragLeave, onDrop, onPaste };\n}\n","/** The keyboard channel: window keydown and keyup as `key` and `key-held` input. */\nimport { focusedControlOwnsKey, isEditableTarget } from '../../keyHelpers';\nimport type { DispatchCore } from '../dispatchCore';\nimport type { Dispatcher, KeyReach } from '../dispatcherApi';\nimport type { InputEvent } from '../matcher';\n\n/**\n * True when AltGr typed the character `e` reports. A layout that types `[` with\n * AltGr reports Ctrl and Alt held with it, which are part of the keystroke\n * rather than a chord. A key that reports its own unshifted letter or digit\n * typed nothing through AltGr: Firefox on Windows reports AltGraph for a plain\n * Ctrl+Alt too, and that one is a chord.\n */\nfunction typedWithAltGraph(e: KeyboardEvent): boolean {\n if (!e.ctrlKey || !e.altKey || e.key.length !== 1 || !e.getModifierState?.('AltGraph')) return false;\n const base = /^(?:Key|Digit)(.)$/.exec(e.code)?.[1];\n return base === undefined || base.toLowerCase() !== e.key.toLowerCase();\n}\n\n/** True inside an open ARIA menu, which owns every key typed in it. */\nconst inMenu = (t: EventTarget | null): boolean => t instanceof Element && t.closest('[role=\"menu\"]') !== null;\n\nexport function keyboardInput(core: DispatchCore): {\n onKeyDown: (e: KeyboardEvent) => void;\n onKeyUp: (e: KeyboardEvent) => void;\n /** End every held key, as a window that lost focus must: it never delivers the keyup. */\n releaseAll: () => void;\n} {\n const { dispatch, dispatcherNow } = core;\n\n // Held keys by physical key, mapped to the `key` they went down as (Shift\n // pressed mid-hold makes the keyup of an 'o' press report 'O') and the\n // dispatcher that took the down, which hover may have routed away from.\n const heldKeys = new Map<string, { key: string; code?: string; on: Dispatcher }>();\n const codeOf = (e: KeyboardEvent): { code?: string } => (e.code ? { code: e.code } : {});\n const physicalKey = (e: KeyboardEvent): string => e.code || e.key.toLowerCase();\n\n const onKeyDown = (e: KeyboardEvent) => {\n if (e.defaultPrevented || isEditableTarget(e.target) || inMenu(e.target) || focusedControlOwnsKey(e)) return;\n // Every dispatcher hears keys on window. The one holding them acts, and so\n // does the one under the pointer, for its `over` bindings alone.\n const reach: KeyReach = { held: core.holdsKeys(), over: core.pointerOver() };\n if (!reach.held && !reach.over) return;\n\n // Autorepeat for a key that's already engaged a key-held binding is\n // suppressed entirely — no dispatch (no trace flood) and the\n // browser default is blocked. Holding Space-for-hand otherwise\n // streamed an 'unhandled' immediate-`key` trace entry per repeat.\n // Autorepeat for a key that ISN'T held still dispatches normally,\n // so things like Cmd+= step-zoom keep auto-repeating.\n if (e.repeat && heldKeys.has(physicalKey(e))) {\n e.preventDefault();\n return;\n }\n\n if (press(e, { altKey: e.altKey, ctrlKey: e.ctrlKey }, reach)) return;\n // The chord as reported comes first, so a binding that names Ctrl+Alt keeps it.\n if (typedWithAltGraph(e)) press(e, { altKey: false, ctrlKey: false }, reach);\n };\n\n /** Dispatch `e` as both `key` and `key-held` with `mods` for its Alt and Ctrl. True when either was handled. */\n const press = (e: KeyboardEvent, mods: { altKey: boolean; ctrlKey: boolean }, reach: KeyReach): boolean => {\n // Both forms dispatch unconditionally. The dispatcher\n // de-dupes naturally because each form uses a different gestureId and\n // different GestureSpec kind. The dispatcher returns 'unhandled' when no\n // binding matches the alternate form, so there's no double-fire risk.\n\n const keyEv: InputEvent = {\n kind: 'key',\n key: e.key,\n ...codeOf(e),\n ...mods,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n repeat: e.repeat,\n };\n const keyResult = dispatch(keyEv, undefined, reach);\n\n // Always dispatch key-held DOWN, even on autorepeat. The dispatcher's\n // own defense returns 'handled' (no-op) when a handle is already in\n // flight for this gestureId, which both prevents start() re-invocation\n // and lets us preventDefault the repeat so the page doesn't react.\n const heldEv: InputEvent = {\n kind: 'key-held',\n key: e.key,\n ...codeOf(e),\n phase: 'down',\n ...mods,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n };\n const heldOn = dispatcherNow();\n const heldResult = dispatch(heldEv, heldOn, reach);\n\n if (heldResult === 'handled') {\n heldKeys.set(physicalKey(e), { key: e.key, ...codeOf(e), on: heldOn });\n }\n\n const handled = keyResult === 'handled' || heldResult === 'handled';\n if (handled) e.preventDefault();\n return handled;\n };\n\n const onKeyUp = (e: KeyboardEvent) => {\n const physical = physicalKey(e);\n const down = heldKeys.get(physical);\n if (down === undefined) return;\n const ev: InputEvent = {\n kind: 'key-held',\n key: down.key,\n ...(down.code !== undefined ? { code: down.code } : {}),\n phase: 'up',\n altKey: e.altKey,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n shiftKey: e.shiftKey,\n };\n heldKeys.delete(physical);\n dispatch(ev, down.on);\n };\n\n const releaseAll = (): void => {\n const releasing = [...heldKeys.values()];\n heldKeys.clear();\n for (const { key, code, on } of releasing) {\n const ev: InputEvent = {\n kind: 'key-held',\n key,\n ...(code !== undefined ? { code } : {}),\n phase: 'up',\n altKey: false,\n ctrlKey: false,\n metaKey: false,\n shiftKey: false,\n };\n dispatch(ev, on);\n }\n };\n\n return { onKeyDown, onKeyUp, releaseAll };\n}\n","/** Listeners attached one by one and removed together. */\nexport interface ListenerSet {\n /** A missing target attaches nothing. */\n on<E extends Event>(\n target: EventTarget | null | undefined,\n type: string,\n listener: (e: E) => void,\n options?: boolean | AddEventListenerOptions,\n ): void;\n removeAll(): void;\n}\n\nexport function listenerSet(): ListenerSet {\n const removers: (() => void)[] = [];\n return {\n on(target, type, listener, options) {\n if (!target) return;\n target.addEventListener(type, listener as EventListener, options);\n removers.push(() => { target.removeEventListener(type, listener as EventListener, options); });\n },\n removeAll() {\n for (const remove of removers.splice(0)) remove();\n },\n };\n}\n","/**\n * The pointer channel: feeds each held pointer's events to the recognizer,\n * and does for it what needs a DOM — sessions, timers, haptics.\n */\nimport {\n createPointerRecognizer, isInControlWithin, longPressEvents, stylusOf,\n type ClickMemory, type HeldPress, type PointerSample, type RecognizerClock,\n} from '@weasel-js/gestures';\nimport type { KitSettingsStore } from '@weasel-js/react';\nimport { openPointerSession, type PointerSession } from '../../pointerSession';\nimport type { PointerDispatchCore } from '../dispatchCore';\nimport { multiTouchGestureId } from '../dispatcher';\nimport { LONG_PRESS_HAPTIC_MS, type LongPressOptions } from '../longPressState';\nimport { underPointer } from '../underPointer';\nimport type { HoverCursorInput } from './hoverCursor';\n\ntype WorldObserver = ((world: { x: number; y: number }) => void) | undefined;\n\n/** Read through thunks, so each answers for the hook's latest render. */\nexport interface PointerInputOptions {\n longPress(): LongPressOptions | undefined;\n /** The kit settings the `gestures` thresholds are read from, at each use. */\n kitSettings(): KitSettingsStore;\n onClick(): WorldObserver;\n onDoubleClick(): WorldObserver;\n /** Outlives this listener set: a re-bind between two clicks must not drop the double click. */\n clicks: ClickMemory;\n hover: Pick<HoverCursorInput, 'moved' | 'released'>;\n}\n\nexport interface PointerInput {\n onPointerDown(e: PointerEvent): void;\n /** The canvas's own `pointermove`, left with the unpressed half: a held\n * pointer's moves arrive through its session, which keeps seeing them once\n * the pointer has left the canvas. */\n onHoverMove(e: PointerEvent): void;\n onNativeDoubleClick(e: MouseEvent): void;\n /** Whether a touch or pen hold is in progress, firing its long-press if still pending. */\n takeNativeHold(): boolean;\n /** Cancel every held pointer, each through its session, which reports once. */\n cancelHeld(): void;\n /** Drop every held pointer and timer without dispatching. */\n dispose(): void;\n}\n\nconst sampleOf = (e: PointerEvent): PointerSample => ({\n pointerId: e.pointerId, clientX: e.clientX, clientY: e.clientY, target: e.target, timeStamp: e.timeStamp,\n altKey: e.altKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, shiftKey: e.shiftKey,\n ...stylusOf(e),\n});\n\n/** Publishes the press being held, with whether holding it to the end would\n * fire anything: the two dispatches a long-press makes, predicted without invoking. */\nfunction holdPublisher(core: PointerDispatchCore, longPress: PointerInputOptions['longPress']) {\n return (pending: HeldPress | null): void => {\n const store = longPress()?.state;\n if (!store) return;\n if (!pending) {\n store.set(null);\n return;\n }\n const { press } = pending;\n const evs = longPressEvents(press);\n const d = core.dispatcherNow();\n store.set({\n pointerId: pending.pointerId,\n pointerType: pending.pointerType,\n client: { x: press.clientX, y: press.clientY },\n local: core.toCanvasLocal(press.clientX, press.clientY),\n world: { x: press.worldX, y: press.worldY },\n viewId: core.target().id,\n startedAt: pending.startedAt,\n duration: pending.duration,\n armed: d.resolveOnly(evs.longpress, core.ctxNow()) !== null\n || d.resolveOnly(evs.contextmenu, core.ctxNow()) !== null,\n });\n };\n}\n\n/**\n * The recognizer's clock. Its one timer is the long-press hold, armed inside\n * `press`, and other input routes elsewhere while that press is held: the hold\n * fires on the view its press went down in.\n */\nfunction holdClock(core: PointerDispatchCore): { clock: RecognizerClock; routeToPress(): void } {\n let holdView: { id: string | null } | null = null;\n return {\n clock: {\n now: () => performance.now(),\n setTimer: (fn, ms) => {\n const view = core.routedView();\n holdView = { id: view };\n return setTimeout(() => {\n holdView = null;\n core.setRoutedView(view);\n fn();\n }, ms);\n },\n clearTimer: (timer) => {\n holdView = null;\n clearTimeout(timer as ReturnType<typeof setTimeout>);\n },\n },\n routeToPress: () => { if (holdView) core.setRoutedView(holdView.id); },\n };\n}\n\nexport function pointerInput(core: PointerDispatchCore, opts: PointerInputOptions): PointerInput {\n const { canvas, routeAt, routeDown, routeRelease, toWorld, target } = core;\n const sessions = new Map<number, PointerSession>();\n // A double click this dispatcher acted on is spent: the browser's own\n // `dblclick` that follows is marked handled, so a container that opens or\n // toggles on double-click leaves it alone.\n let claimedDoubleClick = false;\n const hold = holdClock(core);\n\n const recognizer = createPointerRecognizer({\n sink: {\n dispatch: (ev) => core.dispatch(ev),\n multiTouchInFlight: (fingers) => core.dispatcherNow().inFlight().has(multiTouchGestureId(fingers)),\n },\n clock: hold.clock,\n toWorld,\n toSurface: (p) => core.toCanvasLocal(p.x, p.y),\n longPressMs: () => opts.longPress()?.duration ?? opts.kitSettings().get('gestures.longPressMs'),\n doubleClickMs: () => opts.kitSettings().get('gestures.doubleClickMs'),\n doubleClickPx: () => opts.kitSettings().get('gestures.doubleClickPx'),\n tapPx: () => opts.kitSettings().get('gestures.tapPx'),\n dragPx: () => opts.kitSettings().get('gestures.dragPx'),\n clicks: opts.clicks,\n observer: {\n click: (world) => { opts.onClick()?.(world); },\n doubleClick: (world) => { opts.onDoubleClick()?.(world); },\n holdChanged: holdPublisher(core, opts.longPress),\n longPress: () => {\n if (opts.longPress()?.haptics === false) return;\n if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') {\n navigator.vibrate(LONG_PRESS_HAPTIC_MS);\n }\n },\n },\n });\n\n const onMove = (e: PointerEvent): void => {\n routeAt(e.pointerId, e.clientX, e.clientY);\n recognizer.move(sampleOf(e));\n opts.hover.moved(e);\n };\n\n const onUp = (e: PointerEvent): void => {\n routeAt(e.pointerId, e.clientX, e.clientY);\n sessions.delete(e.pointerId);\n const { doubleClick } = recognizer.release(sampleOf(e));\n if (doubleClick) claimedDoubleClick = doubleClick === 'handled' || opts.onDoubleClick() !== undefined;\n // Everything this release synthesizes has been dispatched, so the pointer's view can be unpinned.\n routeRelease(e.pointerId);\n opts.hover.released(e);\n };\n\n // Every way a gesture ends without a release.\n const onCancel = (pointerId: number): void => {\n // On teardown every session is canceled at once, and `cancelAll` ends\n // those gestures: dispatching here would end them twice.\n if (core.disposed()) return;\n const at = recognizer.positionOf(pointerId);\n if (!at) return;\n sessions.delete(pointerId);\n routeAt(pointerId, at.x, at.y);\n recognizer.cancel(pointerId);\n routeRelease(pointerId);\n };\n\n return {\n onPointerDown(e) {\n claimedDoubleClick = false;\n // Only the primary button drives gesture dispatch; the others are left\n // for the consumer's own tools and the browser context menu. An absent\n // `button` (synthetic events) counts as primary.\n if ((e.button ?? 0) !== 0) return;\n if (!canvas) return;\n // A button or field laid over the canvas handles its own press: opening a\n // session here would capture the pointer and retarget its click.\n if (isInControlWithin(e.target, canvas)) return;\n routeDown(e.pointerId, e.clientX, e.clientY);\n const w = toWorld(e.clientX, e.clientY);\n const where = underPointer(target(), e, w);\n // The session owns the rest of this pointer: capture, the moves, the\n // release, and recovery from a release that never arrives. A press on a\n // pointer one is already open for cancels that stale gesture before this\n // handler runs: its `pointerdown` listener is on the document, in the\n // capture phase, ahead of this one on the canvas.\n sessions.set(e.pointerId, openPointerSession(canvas, e, {\n onMove, onEnd: onUp, onCancel: () => { onCancel(e.pointerId); },\n }));\n recognizer.press({ ...sampleOf(e), x: w.x, y: w.y, pointerType: e.pointerType, ...where });\n },\n onHoverMove(e) {\n if (!sessions.has(e.pointerId)) onMove(e);\n },\n onNativeDoubleClick(e) {\n if (!claimedDoubleClick) return;\n claimedDoubleClick = false;\n e.preventDefault();\n },\n takeNativeHold: () => {\n hold.routeToPress();\n return recognizer.takeHold();\n },\n cancelHeld() {\n for (const session of [...sessions.values()]) session.cancel();\n },\n dispose() {\n recognizer.reset();\n for (const session of sessions.values()) session.cancel();\n sessions.clear();\n },\n };\n}\n","/** The WebKit trackpad pinch channel: `gesturestart` / `gesturechange` / `gestureend` as `pinch` steps. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\nexport function webkitPinchInput(core: DispatchCore): {\n onGestureStart: (e: Event) => void;\n onGestureChange: (e: Event) => void;\n onGestureEnd: (e: Event) => void;\n /** Whether a claimed pinch is live, in which case it is the only driver. */\n live: () => boolean;\n end: () => void;\n} {\n const { canvas, routeAt, toWorld, target, dispatch, dispatcherNow, ctxNow } = core;\n\n // Set on a `gesturestart` some binding claims, cleared on its end. `scale`\n // and `rotation` on a GestureEvent are cumulative from the start; these\n // hold the previous sample's so each dispatched `pinch` is a step.\n let pinchLive = false;\n let pinchScale = 1;\n let pinchRotation = 0;\n\n const endPinch = (): void => {\n pinchLive = false;\n pinchScale = 1;\n pinchRotation = 0;\n };\n\n const pinchEventOf = (e: Event, scale: number, rotation: number): InputEvent => {\n const g = e as Event & {\n clientX?: number; clientY?: number;\n altKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean;\n };\n // A focal point is part of the WebKit shape; the canvas center stands\n // in for an embedder that leaves it off.\n const rect = typeof g.clientX === 'number' && typeof g.clientY === 'number'\n ? undefined : canvas?.getBoundingClientRect();\n const cx = typeof g.clientX === 'number' ? g.clientX : (rect ? rect.left + rect.width / 2 : 0);\n const cy = typeof g.clientY === 'number' ? g.clientY : (rect ? rect.top + rect.height / 2 : 0);\n routeAt(null, cx, cy);\n const local = core.toCanvasLocal(cx, cy);\n const hitPoint = toWorld(cx, cy);\n const mods = {\n altKey: g.altKey === true, ctrlKey: g.ctrlKey === true,\n metaKey: g.metaKey === true, shiftKey: g.shiftKey === true,\n };\n return {\n kind: 'pinch',\n scale,\n rotation,\n clientX: local.x,\n clientY: local.y,\n ...underPointer(target(), mods, hitPoint),\n };\n };\n\n const onGestureStart = (e: Event) => {\n endPinch();\n // Claimed up front, with a probe at unit scale: Safari starts its own\n // page zoom from an unprevented start, before any change arrives.\n // `direction`-filtered bindings cannot match a unit step, so they are\n // resolved per change instead and do not claim the start.\n const probe = pinchEventOf(e, 1, 0);\n if (dispatcherNow().resolveOnly(probe, ctxNow()) === null) return;\n pinchLive = true;\n e.preventDefault();\n };\n\n const onGestureChange = (e: Event) => {\n const g = e as Event & { scale?: number; rotation?: number };\n const scale = typeof g.scale === 'number' && g.scale > 0 ? g.scale : pinchScale;\n const rotation = typeof g.rotation === 'number' ? g.rotation : pinchRotation;\n const step = scale / pinchScale;\n const turn = rotation - pinchRotation;\n pinchScale = scale;\n pinchRotation = rotation;\n if (dispatch(pinchEventOf(e, step, turn)) === 'handled') {\n pinchLive = true;\n e.preventDefault();\n } else if (pinchLive) {\n // The start was claimed; letting one change through would hand the\n // rest of the pinch to Safari's page zoom mid-gesture.\n e.preventDefault();\n }\n };\n\n const onGestureEnd = (e: Event) => {\n if (pinchLive) e.preventDefault();\n endPinch();\n };\n\n return { onGestureStart, onGestureChange, onGestureEnd, live: () => pinchLive, end: endPinch };\n}\n","/** The wheel channel. */\nimport type { DispatchCore } from '../dispatchCore';\nimport type { InputEvent } from '../matcher';\nimport { underPointer } from '../underPointer';\n\n/** A line's height in CSS pixels, as browsers that report pixels scroll one. */\nconst LINE_PX = 16;\n\n/** What one unit of `e`'s deltas is in CSS pixels. Firefox counts a mouse\n * wheel's notches in lines, and every rate downstream is per pixel. */\nfunction pixelsPer(e: WheelEvent, canvas: HTMLElement | null): number {\n if (e.deltaMode === 1) return LINE_PX;\n if (e.deltaMode === 2) return canvas?.clientHeight || LINE_PX * 20;\n return 1;\n}\n\nexport function wheelInput(core: DispatchCore, pinchLive: () => boolean): (e: WheelEvent) => void {\n const { routeAt, toWorld, target, dispatch } = core;\n\n const onWheel = (e: WheelEvent) => {\n core.activate();\n // Safari can report one trackpad pinch as both a gesture stream and\n // ctrl+wheel. While a claimed gesture is live it is the only driver.\n if (pinchLive() && e.ctrlKey) {\n e.preventDefault();\n e.stopPropagation();\n return;\n }\n routeAt(null, e.clientX, e.clientY);\n // Canvas-local, not client: an anchored wheel zoom would otherwise drift\n // by the canvas's offset from the viewport's top-left.\n const local = core.toCanvasLocal(e.clientX, e.clientY);\n const hitPoint = toWorld(e.clientX, e.clientY);\n const toPx = pixelsPer(e, core.canvas);\n const ev: InputEvent = {\n kind: 'wheel',\n deltaX: e.deltaX * toPx,\n deltaY: e.deltaY * toPx,\n clientX: local.x,\n clientY: local.y,\n ...underPointer(target(), e, hitPoint),\n };\n const result = dispatch(ev);\n // A claimed wheel neither scrolls the page nor reaches the canvas's other listeners\n // (a host's camera would zoom under a loupe); capture phase lets this run first.\n if (result === 'handled') {\n e.preventDefault();\n e.stopImmediatePropagation();\n }\n };\n\n return onWheel;\n}\n","/**\n * One listener set for `useGestureDispatcher`: builds the input channels over a\n * shared dispatch core, binds the DOM listeners the enabled channels need, and\n * returns the teardown.\n */\nimport { heldPointers } from '@weasel-js/gestures';\nimport type { CursorSink, PaintedCursorState } from '@weasel-js/cursor';\nimport { createDispatchCore, type DispatchCoreSources } from './dispatchCore';\nimport type { Dispatcher } from './dispatcherApi';\nimport { dispatcherWatch } from './dispatcherWatch';\nimport { carryInput } from './channels/carry';\nimport { contextMenuInput } from './channels/contextMenu';\nimport { hoverCursorInput } from './channels/hoverCursor';\nimport { DROPOVER_CLASS, ingestInput } from './channels/ingest';\nimport { keyboardInput } from './channels/keyboard';\nimport { listenerSet } from './channels/listeners';\nimport { pointerInput, type PointerInput, type PointerInputOptions } from './channels/pointer';\nimport { webkitPinchInput } from './channels/webkitPinch';\nimport { wheelInput } from './channels/wheel';\n\n/** What a listener set reads. Each thunk answers for the hook's latest render. */\nexport interface InputSources\n extends Pick<DispatchCoreSources, 'root' | 'views' | 'clientToLocal' | 'context' | 'actions'>,\n Pick<PointerInputOptions, 'longPress' | 'kitSettings' | 'onClick' | 'onDoubleClick' | 'clicks'> {\n /** Every live dispatcher — what a cancel-everything has to reach. */\n dispatchers(): Dispatcher[];\n requestRedraw(): void;\n paintedCursor(): PaintedCursorState | undefined;\n cursorSink(): CursorSink | undefined;\n}\n\n/** Which channels bind listeners. Fixed for the life of a listener set. */\nexport interface InputChannels {\n keyboard: boolean | 'first';\n pointer: boolean;\n /** Hovers alone. Read only with `pointer` off, which carries them itself. */\n hover: boolean;\n wheel: boolean;\n pinch: boolean;\n contextMenu: boolean;\n ingest: boolean;\n carry: boolean;\n}\n\nexport function attachInput(\n canvas: HTMLElement | null,\n src: InputSources,\n channels: InputChannels,\n): () => void {\n let disposed = false;\n // Dispatcher-only overlays (marquee, lasso) repaint on nothing else, and\n // the event that closes a gesture still has to clear its overlay.\n const redraw = dispatcherWatch(src.requestRedraw);\n redraw.sync(src.dispatchers());\n const core = createDispatchCore({\n canvas,\n root: src.root,\n views: src.views,\n clientToLocal: src.clientToLocal,\n context: src.context,\n actions: src.actions,\n uses: () => { redraw.sync(src.dispatchers()); },\n disposed: () => disposed,\n });\n const keys = keyboardInput(core);\n const pinch = webkitPinchInput(core);\n const ingest = ingestInput(core);\n const held = canvas ? heldPointers(canvas) : null;\n const hover = hoverCursorInput(core, src.paintedCursor, () => held?.count() ?? 0, src.cursorSink);\n const pointer: PointerInput = pointerInput(core, {\n longPress: src.longPress,\n kitSettings: src.kitSettings,\n onClick: src.onClick,\n onDoubleClick: src.onDoubleClick,\n clicks: src.clicks,\n hover,\n });\n\n // A window that loses focus never delivers the keyup, so without this every\n // in-flight key-held handle stays engaged until that key is pressed again.\n // Nor can a drag trust the release it may or may not see later.\n const onWindowBlur = (): void => {\n pinch.end();\n pointer.cancelHeld();\n keys.releaseAll();\n };\n\n const listeners = listenerSet();\n const keyCapture = channels.keyboard === 'first';\n if (channels.keyboard) {\n listeners.on(window, 'keydown', keys.onKeyDown, keyCapture);\n listeners.on(window, 'keyup', keys.onKeyUp, keyCapture);\n }\n listeners.on(window, 'blur', onWindowBlur);\n // Ahead of the pointer channel's own listener, and whether or not that\n // channel is on: a press with any button makes this the scope chrome and\n // keys reach.\n listeners.on(canvas, 'pointerdown', () => { src.actions().activate(); });\n // Whether or not the pointer channel is on: it is what an `over` key binding asks.\n const setOver = (on: boolean) => () => { core.setPointerOver(on); };\n listeners.on(canvas, 'pointerenter', setOver(true));\n listeners.on(canvas, 'pointermove', setOver(true));\n listeners.on(canvas, 'pointerleave', setOver(false));\n if (channels.pointer) {\n // Separate from the key channel's listeners, so the cursor also tracks\n // modifiers when `keyboard: false` turns gesture key dispatch off.\n listeners.on(window, 'keydown', hover.onKey);\n listeners.on(window, 'keyup', hover.onKey);\n listeners.on(canvas, 'pointerleave', hover.onLeave);\n listeners.on(canvas, 'pointerdown', pointer.onPointerDown);\n listeners.on(canvas, 'pointermove', pointer.onHoverMove);\n listeners.on(canvas, 'dblclick', pointer.onNativeDoubleClick);\n } else if (channels.hover) {\n listeners.on(window, 'keydown', hover.onKey);\n listeners.on(window, 'keyup', hover.onKey);\n listeners.on(canvas, 'pointerleave', hover.onLeave);\n listeners.on(canvas, 'pointermove', (e: PointerEvent) => {\n core.routeAt(null, e.clientX, e.clientY);\n hover.moved(e);\n });\n }\n if (channels.wheel) {\n listeners.on(canvas, 'wheel', wheelInput(core, pinch.live), { passive: false, capture: true });\n }\n if (channels.pinch) {\n listeners.on(canvas, 'gesturestart', pinch.onGestureStart);\n listeners.on(canvas, 'gesturechange', pinch.onGestureChange);\n listeners.on(canvas, 'gestureend', pinch.onGestureEnd);\n }\n if (channels.contextMenu) {\n listeners.on(canvas, 'contextmenu', contextMenuInput(core, pointer.takeNativeHold));\n }\n if (channels.ingest) {\n listeners.on(canvas, 'dragenter', ingest.onDragOver);\n listeners.on(canvas, 'dragover', ingest.onDragOver);\n listeners.on(canvas, 'dragleave', ingest.onDragLeave);\n listeners.on(canvas, 'drop', ingest.onDrop);\n listeners.on(window, 'paste', ingest.onPaste);\n }\n const offCarry = channels.carry ? carryInput(core) : null;\n\n return () => {\n listeners.removeAll();\n offCarry?.();\n canvas?.classList.remove(DROPOVER_CLASS);\n // The registry in use at teardown is the one holding the keys.\n src.actions().dropKeys();\n hover.clear();\n // `disposed` first: the sessions' cancels must not re-enter dispatch on\n // the way out, and `cancelAll` below is what ends the gestures.\n disposed = true;\n pointer.dispose();\n held?.release();\n redraw.stop();\n for (const d of src.dispatchers()) d.cancelAll('cancel');\n };\n}\n","/**\n * Mounts the gesture dispatcher: composes the input channels (keys, wheel,\n * WebKit gesture events, pointer events, and multi-touch synthesized from\n * them) and routes each event to the dispatcher for the view it landed in.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { isApplePlatform, type ClickMemory } from '@weasel-js/gestures';\nimport { useKitSettings, useLatest } from '@weasel-js/react';\nimport { useActiveToolContext } from '../actions/activeToolContext';\nimport { actionsNodeOf } from '../actions/ActionsProvider';\nimport type { ActionSource } from '../actions/action';\nimport { useDepRegistry } from '../actions/depRegistry';\nimport { useToolLifecycle } from '../../tools/useToolLifecycle';\nimport { createDispatcher, createDispatchTrace, type Dispatcher, type DispatcherContext } from './dispatcher';\nimport { attachInput } from './attachInput';\nimport type { DispatcherViewTarget, UseGestureDispatcherOptions } from './gestureDispatcherOptions';\n\nexport type {\n DispatcherChannels, DispatcherViewTarget, UseGestureDispatcherOptions, ViewIdResolver,\n} from './gestureDispatcherOptions';\n\n/**\n * Attach the input pipeline to a canvas: DOM pointer, wheel, keyboard, and\n * multitouch listeners in, normalized input events out, routed through the\n * dispatcher to whichever action a binding names.\n *\n * The active tool and the dep registry come from context, so it must be\n * mounted inside `<SceneCanvas>`'s providers.\n */\nexport function useGestureDispatcher(opts: UseGestureDispatcherOptions): void {\n const { canvasRef, actions, entriesById, enabled = true, keyboard = true, affordanceAt, classifyTarget, dispatcher: dispatcherOpt, trace: traceOpt, clientToWorld, clientToLocal, requestRedraw, paintedCursor, cursorSink, getRuleCtx, onClick, onDoubleClick, views, channels, longPress, claimKeys = false, hears = 'scope' } = opts;\n // Read out as booleans, not the object: the attach effect depends on\n // them, and an inline `channels={{...}}` would re-bind every listener on\n // every render.\n const pointerChannel = channels?.pointer !== false;\n const hoverChannel = channels?.hover ?? pointerChannel;\n const wheelChannel = channels?.wheel !== false;\n const pinchChannel = channels?.pinch !== false;\n const contextMenuChannel = channels?.contextMenu !== false;\n const ingestChannel = channels?.ingest !== false;\n const carryChannel = channels?.carry !== false;\n const onClickRef = useLatest(onClick);\n const onDoubleClickRef = useLatest(onDoubleClick);\n const activeTool = useActiveToolContext();\n const depRegistry = useDepRegistry();\n const [isMac] = useState(isApplePlatform);\n\n const [ownTrace] = useState(createDispatchTrace);\n const trace = traceOpt ?? ownTrace;\n useEffect(() => depRegistry.register('dispatchTrace', () => trace), [depRegistry, trace]);\n\n const dispatcherRef = useRef<Dispatcher | null>(null);\n if (!dispatcherRef.current) {\n dispatcherRef.current = dispatcherOpt ?? createDispatcher();\n }\n\n // No `getRuleCtx` here: eligibility is a per-view answer, so it rides on the\n // dispatch record and the core installs the routed view's.\n const registryRef = useLatest(actions);\n const heard = useMemo<ActionSource>(() => {\n const node = hears === 'own' ? actionsNodeOf(actions) : null;\n return node ? { list: () => node.ownActions() } : actions;\n }, [actions, hears]);\n const ctxRef = useLatest<DispatcherContext>({\n actions: heard,\n depRegistry,\n activeToolId: activeTool.active,\n hotkeyStack: activeTool.hotkeyStack,\n entriesById,\n isMac,\n trace,\n });\n\n // The flat options are view zero.\n const rootTargetRef = useLatest<DispatcherViewTarget>({\n id: null, dispatcher: dispatcherRef.current, affordanceAt, classifyTarget, clientToWorld,\n getRuleCtx,\n });\n const viewsRef = useLatest(views);\n const clientToLocalRef = useLatest(clientToLocal);\n\n /** Every live dispatcher — what a cancel-everything has to reach. */\n const allDispatchers = useCallback((): Dispatcher[] => [\n rootTargetRef.current.dispatcher,\n ...(viewsRef.current?.targets() ?? []).map((t) => t.dispatcher),\n ], [rootTargetRef, viewsRef]);\n const requestRedrawRef = useLatest(requestRedraw);\n const cursorRef = useLatest({ painted: paintedCursor, sink: cursorSink });\n const longPressRef = useLatest(longPress);\n const kitSettingsRef = useLatest(useKitSettings());\n\n // Held here rather than in the effect: a re-bind of the listeners between\n // two clicks would otherwise drop the double click.\n const clicksRef = useRef<ClickMemory>({ last: null });\n\n useToolLifecycle({\n entriesById,\n active: activeTool.active,\n hotkeyStack: activeTool.hotkeyStack,\n // The incoming tool must not inherit a live gesture.\n onSwitch: () => { for (const d of allDispatchers()) d.cancelAll('cancel'); },\n });\n\n useEffect(() => {\n if (enabled && claimKeys) registryRef.current.activate();\n }, [enabled, claimKeys, registryRef]);\n\n useEffect(() => {\n if (!enabled) return;\n return attachInput(canvasRef.current, {\n root: () => rootTargetRef.current,\n views: () => viewsRef.current,\n clientToLocal: () => clientToLocalRef.current,\n context: () => ctxRef.current,\n actions: () => registryRef.current,\n dispatchers: allDispatchers,\n requestRedraw: () => { requestRedrawRef.current?.(); },\n paintedCursor: () => cursorRef.current.painted?.(),\n cursorSink: () => cursorRef.current.sink?.(),\n longPress: () => longPressRef.current,\n kitSettings: () => kitSettingsRef.current,\n onClick: () => onClickRef.current,\n onDoubleClick: () => onDoubleClickRef.current,\n clicks: clicksRef.current,\n }, {\n keyboard,\n pointer: pointerChannel,\n hover: hoverChannel,\n wheel: wheelChannel,\n pinch: pinchChannel,\n contextMenu: contextMenuChannel,\n ingest: ingestChannel,\n carry: carryChannel,\n });\n }, [enabled, keyboard, canvasRef, pointerChannel, hoverChannel, wheelChannel, pinchChannel, contextMenuChannel, ingestChannel, carryChannel,\n allDispatchers, clientToLocalRef, ctxRef, kitSettingsRef, longPressRef, onClickRef, onDoubleClickRef, cursorRef, registryRef, requestRedrawRef, rootTargetRef, viewsRef]);\n}\n","import { useMemo } from 'react';\nimport type { IconRef } from '@weasel-js/icons';\nimport { useLatest, useStableByContent } from '@weasel-js/react';\nimport { deepEqual } from '@weasel-js/registry';\nimport type { Action, ActionDisabledReason, ActionVariant } from './action';\nimport type { BoundGesture } from './binding';\nimport { useAction } from './ActionsProvider';\n\n/** What a command offers besides its id, label and callback. */\nexport interface CommandOptions {\n /** True when the command can run, else why not. Read each time it is asked. */\n enabled?: () => true | ActionDisabledReason;\n /** Whether it reads as held down. Read each time it is asked. */\n active?: () => boolean;\n /** The gestures that run it. The `{ spec, opts: { params } }` form gives one variant its own key. */\n keys?: BoundGesture | readonly BoundGesture[];\n /** Shown beside the label. */\n icon?: IconRef;\n /** Words a palette finds it by and a tagged bar or menu gathers it under. */\n tags?: readonly string[];\n /** One entry each in a bar, menu or palette; `run` receives the chosen one's params. */\n variants?: readonly ActionVariant[];\n}\n\n/**\n * Register `run` as an action under `id` on the nearest `<ActionsProvider>`\n * for the calling component's lifetime, so a menu, toolbar, palette or key\n * can run it. Callbacks and option functions may be new on every render: the\n * latest are read when used, and the action is replaced only when `id`,\n * `label`, `icon`, `keys`, `tags` or `variants` change by value.\n */\nexport function useCommand(\n id: string,\n label: string,\n run: (params?: Readonly<Record<string, unknown>>) => void,\n options?: CommandOptions,\n): void {\n const latest = useLatest({ run, options });\n const keys = useStableByContent(options?.keys, deepEqual);\n const tags = useStableByContent(options?.tags, deepEqual);\n const variants = useStableByContent(options?.variants, deepEqual);\n const hasEnabled = options?.enabled !== undefined;\n const hasActive = options?.active !== undefined;\n const icon = options?.icon;\n const action = useMemo<Action>(() => {\n const read = () => latest.current.options;\n const a: Action = {\n id,\n label,\n invoker: { timing: 'immediate', run: (_deps, params) => latest.current.run(params) },\n };\n if (keys !== undefined) a.defaultBinding = bindingOf(keys);\n if (tags !== undefined) a.tags = tags;\n if (variants !== undefined) a.variants = variants;\n if (hasEnabled) a.enabled = () => read()?.enabled?.() ?? true;\n if (hasActive) a.active = () => read()?.active?.() ?? false;\n if (icon !== undefined) a.icon = icon;\n return a;\n }, [id, label, icon, keys, tags, variants, hasEnabled, hasActive, latest]);\n useAction(action);\n}\n\nfunction bindingOf(keys: BoundGesture | readonly BoundGesture[]): Action['defaultBinding'] {\n if (isList(keys)) return [...keys];\n return 'spec' in keys ? [keys] : keys;\n}\n\nconst isList = (keys: BoundGesture | readonly BoundGesture[]): keys is readonly BoundGesture[] => Array.isArray(keys);\n","/**\n * Input scopes and yokes: the tiers between a root registry and a canvas.\n */\nimport { useContext, useEffect, useMemo, type ReactElement, type ReactNode } from 'react';\nimport { ActionsContext, ActionsNode, actionsNodeOf, useActionsRegistry } from './ActionsProvider';\nimport { DepNode, DepRegistryContext, depNodeOf, useOptionalDepRegistry } from './depRegistry';\nimport { ActiveToolNodeContext, ToolNode } from './activeToolContext';\nimport { MenuHostContext } from '../../menus/MenuHostContext';\n\n/**\n * Canvases that share input on purpose: the active tool, the gesture in\n * flight, history, and yoke-wide actions. Made once with `useYoke()`, and\n * passed to each canvas that joins it (`yoke={yoke}`) and to\n * `<Yoke value={yoke}>` around anything else that should reach it — a\n * toolbar, say. The members can sit anywhere in the tree.\n */\nexport interface Yoke {\n /** @internal */\n readonly actions: ActionsNode;\n /** @internal */\n readonly deps: DepNode;\n /** @internal */\n readonly tools: ToolNode;\n}\n\n/** The three nodes of a tier, under `parent`'s or the ones in scope, with\n * activation carried across all three. */\nfunction useNodes(\n descends: boolean,\n ownsTool: boolean,\n parent: Yoke | undefined,\n): Yoke {\n const parentActions = useActionsRegistry();\n const parentDeps = useOptionalDepRegistry();\n const parentTools = useContext(ActiveToolNodeContext);\n const pa = parent ? parent.actions : actionsNodeOf(parentActions);\n const pd = parent ? parent.deps : depNodeOf(parentDeps);\n const pt = parent ? parent.tools : parentTools;\n const nodes = useMemo<Yoke>(() => {\n const deps = new DepNode(pd, descends);\n const tools = new ToolNode(pt, descends, ownsTool, null);\n const actions = new ActionsNode(pa, descends, () => deps.registry);\n actions.onActivate.push(() => deps.activate(), () => tools.activate());\n return { actions, deps, tools };\n }, [pa, pd, pt, descends, ownsTool]);\n useEffect(() => {\n const leave = [nodes.deps.mount(), nodes.tools.mount(), nodes.actions.mount()];\n return () => {\n for (const f of leave) f();\n };\n }, [nodes]);\n return nodes;\n}\n\n/** Puts a tier's nodes in scope, and its tree's menu host when no\n * `<ActionsProvider>` above has put one there. */\nfunction Provide({ nodes, children }: { nodes: Yoke; children: ReactNode }): ReactElement {\n const menuHost = useContext(MenuHostContext) ?? nodes.actions.menuHost();\n return (\n <DepRegistryContext.Provider value={nodes.deps.registry}>\n <ActionsContext.Provider value={nodes.actions.registry}>\n <ActiveToolNodeContext.Provider value={nodes.tools}>\n <MenuHostContext.Provider value={menuHost}>{children}</MenuHostContext.Provider>\n </ActiveToolNodeContext.Provider>\n </ActionsContext.Provider>\n </DepRegistryContext.Provider>\n );\n}\n\n/** Props for `<InputScope>`. */\nexport interface InputScopeProps {\n /** The yoke this scope joins. Omitted, it sits under the registries in\n * scope and keeps a tool of its own. */\n yoke?: Yoke;\n children: ReactNode;\n}\n\n/**\n * One canvas's input: actions, deps and a tool of its own, under whichever\n * registries are in scope (or its yoke's). What the canvas registers stays\n * here; what it looks up is answered here first, then by the tiers above.\n * With nothing in scope it is a root, and makes the menu host\n * `<ActionsProvider>` would have.\n *\n * Chrome above calls `trigger` / `begin` / `useActiveToolContext` on its own\n * registries, and those reach the active scope: the one last activated — by a\n * pointerdown, wheel or contextmenu — or the newest where none has been. Keys are stricter:\n * one that reaches the page goes to the canvas last pressed or scrolled in,\n * across every root on the page, and to none before the first.\n */\nexport function InputScope({ yoke, children }: InputScopeProps): ReactElement {\n const nodes = useNodes(false, yoke === undefined, yoke);\n return <Provide nodes={nodes}>{children}</Provide>;\n}\n\n/**\n * Make a yoke for canvases to join, under the registries in scope where it is\n * called. It lives as long as the calling component.\n */\nexport function useYoke(): Yoke {\n return useNodes(true, true, undefined);\n}\n\n/** Props for `<Yoke>`. */\nexport interface YokeProps {\n value: Yoke;\n children: ReactNode;\n}\n\n/**\n * Put `value` in scope for what is not a canvas — a toolbar, a status bar — so\n * its actions, deps and tool reads reach the yoke and, through it, the member\n * canvas last used.\n */\nexport function Yoke({ value, children }: YokeProps): ReactElement {\n return <Provide nodes={value}>{children}</Provide>;\n}\n","import { useEffect, useMemo, useRef } from 'react';\nimport { useActionsRegistry } from './ActionsProvider';\nimport type { ActionsRegistry, UiOngoingControl } from './registry';\nimport { useLatest } from '@weasel-js/react';\n\n/**\n * One UI control's hold on an ongoing action — the handle a color picker, a\n * slider or a swatch drives the action through, the way a drag drives one\n * through a gesture.\n *\n * - `input(params)` opens the action on the first call and moves it on every\n * later one: the live preview.\n * - `commit(params?)` moves it to `params`, if given, and ends it as one\n * undoable edit. With nothing open, a commit carrying params is a whole edit\n * on its own — a click on a swatch, a switch of paint kind.\n * - `cancel()` ends an open edit without keeping it.\n *\n * An edit the dispatcher ended first — a tool switch, Escape, another control\n * committing the same action — counts as not open: the next `input` opens a\n * new one.\n *\n * All three are no-ops when no action is reachable, so a control renders the\n * same with or without a canvas in scope.\n */\nexport interface OngoingAction {\n input(params: Record<string, unknown>): void;\n commit(params?: Record<string, unknown>): void;\n cancel(): void;\n}\n\n/**\n * Drive the ongoing action `actionId` from a UI control: {@link OngoingAction}.\n *\n * An edit left open when the control unmounts, or when `actionId` changes, is\n * committed — it is what the user was looking at when the control went away.\n * On unmount that happens a microtask later.\n * The returned object is stable for the life of the component.\n */\nexport function useOngoingAction(actionId: string): OngoingAction {\n const reg = useActionsRegistry();\n const regRef = useLatest<ActionsRegistry | null>(reg);\n const idRef = useLatest(actionId);\n const ctrlRef = useRef<UiOngoingControl | null>(null);\n\n const edit = useMemo<OngoingAction>(() => {\n const end = (reason: 'commit' | 'cancel'): void => {\n const ctrl = ctrlRef.current;\n ctrlRef.current = null;\n ctrl?.end(reason);\n };\n /** Move the open edit to `params`, or open one there: the dispatcher may\n * have ended the one this control held. */\n const drive = (params: Record<string, unknown>): void => {\n if (ctrlRef.current?.active) ctrlRef.current.update(params);\n else ctrlRef.current = regRef.current?.begin(idRef.current, params) ?? null;\n };\n return {\n input: drive,\n commit(params) {\n if (params !== undefined) drive(params);\n end('commit');\n },\n cancel() {\n end('cancel');\n },\n };\n }, [regRef, idRef]);\n\n // The commit waits a microtask so that StrictMode's rehearsal unmount, which\n // remounts with the same id before then, does not end an edit opened in an effect.\n const leaving = useRef<string | null>(null);\n useEffect(() => {\n const left = leaving.current;\n leaving.current = null;\n if (left !== null && left !== actionId) edit.commit();\n return () => {\n leaving.current = actionId;\n queueMicrotask(() => {\n if (leaving.current !== actionId) return;\n leaving.current = null;\n edit.commit();\n });\n };\n }, [edit, actionId]);\n\n return edit;\n}\n","/**\n * PointerContext — the world-space position of the canvas pointer, and the\n * view it is over, refreshed on every `pointermove` and cleared on\n * `pointerleave`.\n *\n * It is an external store rather than React state, so a consumer that only\n * reads on demand (paste at the pointer) does not re-render on every move.\n * Readers that need to follow it subscribe, or use `usePointerPosition()`.\n *\n * `<SceneCanvas>` publishes automatically, and defers to a provider already in\n * scope, so several surfaces under one provider share one pointer.\n */\nimport { createEmitter } from '@weasel-js/registry';\nimport {\n createContext, useContext, useState, useSyncExternalStore, type ReactNode,\n} from 'react';\n\n/** World-space pointer position and the view it is over — a\n * view id, or `null` for a surface's own camera. `null` as a whole when the\n * pointer is over no publishing surface. */\nexport type PointerWorldPos = { worldX: number; worldY: number; viewId: string | null } | null;\n\n/** A pointer store: the latest position, a way to publish one, and change notification. */\nexport interface PointerContextValue {\n /** The latest position. */\n get(): PointerWorldPos;\n /** Publish a position. Subscribers hear only a changed value. */\n set(next: PointerWorldPos): void;\n /** Called after every change; returns the unsubscribe. */\n subscribe(fn: () => void): () => void;\n /** Bumps on every change. */\n getVersion(): number;\n /** `get()` as a stable thunk, for hooks taking a drop-point option. */\n readonly getDropPoint: () => PointerWorldPos;\n}\n\nfunction samePos(a: PointerWorldPos, b: PointerWorldPos): boolean {\n if (a === null || b === null) return a === b;\n return a.worldX === b.worldX && a.worldY === b.worldY && a.viewId === b.viewId;\n}\n\n/** A pointer store with no provider around it. */\nexport function createPointerStore(): PointerContextValue {\n let current: PointerWorldPos = null;\n let version = 0;\n const changed = createEmitter();\n const get = (): PointerWorldPos => current;\n return {\n get,\n set(next) {\n if (samePos(current, next)) return;\n current = next;\n version++;\n changed.emit();\n },\n subscribe: changed.subscribe,\n getVersion: () => version,\n getDropPoint: get,\n };\n}\n\nconst PointerContext = createContext<PointerContextValue | null>(null);\n\n/**\n * Wrap the part of the React tree that should share one pointer.\n * `<SceneCanvas>` mounts one when none is in scope, so mount it yourself only\n * when two surfaces should share a pointer. Pass `store` to publish into one\n * you hold elsewhere (`createPointerStore()`).\n */\nexport function PointerContextProvider(\n { children, store }: { children: ReactNode; store?: PointerContextValue },\n): ReactNode {\n const [own] = useState(createPointerStore);\n return <PointerContext.Provider value={store ?? own}>{children}</PointerContext.Provider>;\n}\n\n/** The surrounding pointer store, or `null` when no provider is\n * in scope. */\nexport function usePointerContext(): PointerContextValue | null {\n return useContext(PointerContext);\n}\n\nconst noSubscribe = (): (() => void) => () => {};\nconst noPointer = (): PointerWorldPos => null;\n\n/** The pointer, re-rendering the caller whenever it changes.\n * `null` outside a provider. */\nexport function usePointerPosition(): PointerWorldPos {\n const store = usePointerContext();\n return useSyncExternalStore(\n store ? store.subscribe : noSubscribe,\n store ? store.get : noPointer,\n store ? store.get : noPointer,\n );\n}\n","/**\n * SelectionContext — an ambient context that publishes \"what's currently\n * selected\" so non-canvas UI (command palette, status bar) can read it without\n * threading a selection prop through the tree.\n *\n * **Single slot:** the context holds one selection array. Whichever publisher\n * calls `publishSelection` most recently owns it, so a multi-canvas page gets\n * last-writer-wins. `<SceneCanvas>` publishes automatically.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { NodeId } from '../vocabulary';\n\n/** The ambient selection store a canvas publishes into and non-canvas UI reads. */\nexport interface SelectionContextValue {\n /** The most-recently-published selection. Empty array when no canvas\n * has published or when the active canvas's selection is empty. */\n readonly selection: readonly NodeId[];\n /** Optional per-id kind label, parallel to `selection` (e.g. `'rectangle'`,\n * `'path'`, `'group'`). Sparse entries (`undefined`) are allowed; treat it\n * as best-effort. */\n readonly kinds?: readonly (string | undefined)[];\n /** Publish the calling canvas's selection. Calling with the same content\n * does not re-render the consumer tree. */\n publishSelection(ids: readonly NodeId[], kinds?: readonly (string | undefined)[]): void;\n}\n\nconst SelectionContext = createContext<SelectionContextValue | null>(null);\n\n/**\n * Wrap the part of the React tree that should share a selection context.\n * Usually placed at the demo / app root, alongside `<ActionsProvider>`.\n */\nexport function SelectionContextProvider({ children }: { children: ReactNode }): ReactNode {\n const [state, setState] = useState<{\n selection: readonly NodeId[];\n kinds: readonly (string | undefined)[] | undefined;\n }>({ selection: [], kinds: undefined });\n const lastSerializedRef = useRef<string>('');\n\n const publishSelection = useCallback((\n ids: readonly NodeId[],\n kinds?: readonly (string | undefined)[],\n ): void => {\n const next = JSON.stringify([ids, kinds]);\n if (next === lastSerializedRef.current) return;\n lastSerializedRef.current = next;\n setState({ selection: ids, kinds });\n }, []);\n\n const value = useMemo<SelectionContextValue>(\n () => ({\n selection: state.selection,\n ...(state.kinds !== undefined ? { kinds: state.kinds } : {}),\n publishSelection,\n }),\n [state, publishSelection],\n );\n\n return <SelectionContext.Provider value={value}>{children}</SelectionContext.Provider>;\n}\n\n/**\n * The current selection-context value, or `null` when no\n * `<SelectionContextProvider>` is in scope.\n */\nexport function useSelectionContext(): SelectionContextValue | null {\n return useContext(SelectionContext);\n}\n\n/**\n * Mounts a `<SelectionContextProvider>` only when no parent provider is in\n * scope; otherwise renders children unwrapped.\n */\nexport function SelectionContextProviderIfRoot({\n children,\n}: {\n children: ReactNode;\n}): ReactNode {\n const parent = useContext(SelectionContext);\n if (parent !== null) return <>{children}</>;\n return <SelectionContextProvider>{children}</SelectionContextProvider>;\n}\n\n/**\n * Publishes `ids` into the surrounding `<SelectionContextProvider>` whenever\n * their content changes, and clears the slot on unmount unless another\n * publisher has written it since. No-op when there's no provider in scope.\n */\nexport function usePublishSelection(\n ids: readonly NodeId[],\n kinds?: readonly (string | undefined)[],\n): void {\n const ctx = useContext(SelectionContext);\n // Track latest values via refs so the effect's deps array can use a stable\n // serialization — avoids re-firing on identity-only changes.\n const idsRef = useLatest(ids);\n const kindsRef = useLatest(kinds);\n const serialized = JSON.stringify([ids, kinds]);\n // Depend on `publishSelection` rather than `ctx`: the provider mints a new\n // context value on every publish, so keying on `ctx` refires this effect for\n // every publisher whenever any one of them publishes.\n const publish = ctx?.publishSelection;\n useEffect(() => {\n if (!publish) return;\n publish(idsRef.current, kindsRef.current);\n }, [publish, serialized, idsRef, kindsRef]);\n // A publisher that goes away takes its selection with it, unless another\n // has written the slot since.\n const ctxRef = useLatest(ctx);\n const serializedRef = useLatest(serialized);\n useEffect(() => () => {\n const slot = ctxRef.current;\n if (slot && JSON.stringify([slot.selection, slot.kinds]) === serializedRef.current) {\n slot.publishSelection([]);\n }\n }, [ctxRef, serializedRef]);\n}\n","// src/contributions/useContributions.ts\nimport { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport { activeModeOf, type ModeRegistry } from '@weasel-js/modes';\nimport { useActiveToolContext } from '../interactions/actions/activeToolContext';\nimport { useActionsRegistry } from '../interactions/actions/ActionsProvider';\nimport {\n buildToolOffhandBindings,\n makeToolOffhandAction,\n offhandKeyFor,\n type ToolOffhandBindingSpec,\n} from '../interactions/actions/toolOffhand';\nimport { reportRouteConflicts } from '../tools/routing/reflection/conflicts';\nimport type { HotkeyTrigger } from './types';\nimport { assembleEntries } from './assemble';\nimport { liveScope } from './eligibility';\nimport type { Contribution, OverlayPosition } from './types';\nimport { isDev } from '@weasel-js/react';\nimport { sameList, useStableByContent } from '@weasel-js/react';\nimport type { KernelOverlay } from '../index';\n\nconst NO_MODES = (): (() => void) => () => {};\n\n/** Options for {@link useContributions}. */\nexport interface UseContributionsOptions<TOverlay = KernelOverlay> {\n /** Every registry entry, in declaration order. Order decides which of two\n * same-specificity bindings in one scope tier wins. */\n entries: readonly Contribution<TOverlay>[];\n /** Desired focused entry id, or `null` for none. First-mount-wins against\n * the shared `ActiveToolContext` — see `useTools` for the full semantics. */\n focused: string | null;\n /** The modes the canvas can be in. The active one decides which tagged\n * entries draw their overlays, and the dev-time route-conflict check reads\n * them all to decide whether two gated actions can ever compete; without a\n * registry nothing is barred and the check uses the kit's `DEFAULT_MODES`. */\n modes?: ModeRegistry;\n}\n\n/** The assembled registry {@link useContributions} returns. */\nexport interface ContributionsApi<TOverlay = KernelOverlay> {\n /** Every entry, as passed in. */\n entries: readonly Contribution<TOverlay>[];\n /** Currently focused entry id, or `null` when nothing is focused. */\n focused: string | null;\n /** Focus an entry, or pass `null` to focus none. Writes through to the\n * shared `ActiveToolContext`. */\n setFocused: (id: string | null) => void;\n /** Overlays of every live entry declaring `position`, ordered active, then\n * hotkey, then ambient. Live is what the dispatcher routes to: an entry the\n * active mode bars draws nothing. */\n overlays(position?: OverlayPosition): TOverlay[];\n}\n\n/**\n * Assembles one registry: every entry's bindings and overlays, each tiered by\n * what the entry declares about its own eligibility rather than by which\n * argument a consumer passed it in.\n *\n * Requires `<ActiveToolContextProvider>` (or `<WeaselProvider>` /\n * `<SceneCanvas>`, which mount one internally): focus and held-key state live\n * in the context so the gesture dispatcher and every sibling caller read the\n * same source of truth.\n */\nexport function useContributions<TOverlay = KernelOverlay>(\n opts: UseContributionsOptions<TOverlay>,\n): ContributionsApi<TOverlay> {\n const ctx = useActiveToolContext();\n const actionsRegistry = useActionsRegistry();\n\n // First-mount sync: if the context's slot is still unseeded and the caller\n // wants a tool, push it. Captured at first render; the setState runs in a\n // post-commit effect so it never updates state during render.\n const firstMountRef = useRef<{ sync: boolean } | null>(null);\n const isFirstRender = firstMountRef.current == null;\n if (firstMountRef.current == null) firstMountRef.current = { sync: ctx.active === null && opts.focused !== null };\n useEffect(() => {\n const first = firstMountRef.current;\n if (!first?.sync) return;\n first.sync = false;\n ctx.setActive(opts.focused);\n // First-mount sync only — deliberately runs once after mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const focused = isFirstRender && ctx.active === null && opts.focused !== null\n ? opts.focused\n : ctx.active;\n\n // Consumers commonly rebuild the entry list every render; identity follows\n // its contents, so everything keyed on it below changes only when they do.\n const entries = useStableByContent(opts.entries, sameList);\n const engaged = ctx.hotkeyStack;\n\n const setFocused = useCallback((id: string | null) => { ctx.setActive(id); }, [ctx]);\n\n // The active mode's capability set gates overlays as it gates bindings. Read\n // as state so `overlays` changes identity when the mode does.\n const modes = opts.modes;\n const modeVersion = useSyncExternalStore(\n modes ? modes.subscribe : NO_MODES,\n () => modes?.getVersion() ?? 0,\n );\n const snapshot = useCallback(() => assembleEntries(entries, {\n focusedId: focused,\n hotkeyStack: engaged,\n ...(modes ? { allowedCapabilities: activeModeOf(modes.current()).allowedCapabilities } : {}),\n // The version is what changes; `modes` is one object for the registry's life.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [entries, focused, engaged, modes, modeVersion]);\n\n const overlays = useCallback((position: OverlayPosition = 'top'): TOverlay[] => {\n const { ordered, state } = snapshot();\n const active: TOverlay[] = [];\n const hotkey: TOverlay[] = [];\n const ambient: TOverlay[] = [];\n for (const entry of ordered) {\n if (!entry.overlay) continue;\n if ((entry.overlayPosition ?? 'top') !== position) continue;\n const layers = Array.isArray(entry.overlay) ? entry.overlay : [entry.overlay];\n const scope = liveScope(entry.id, entry.eligibility ?? {}, state);\n if (scope === 'active') active.push(...layers);\n else if (scope === 'hotkey') hotkey.push(...layers);\n else if (scope === 'ambient') ambient.push(...layers);\n }\n return [...active, ...hotkey, ...ambient];\n }, [snapshot]);\n\n useOffhandAction(entries);\n\n // Route-conflict check. Two entries declaring the same (phase, gesture, arg,\n // target, modifiers) tuple in one scope are resolved by declaration order and\n // almost certainly not as either author intended. This is where the entry set\n // is assembled, so this is where it looks.\n //\n // Dev-only, and deduped on a signature of the entry set: the check walks\n // every binding of every entry, and consumers usually rebuild the entry list\n // each render. Actions are read inside the effect, after the registrations\n // that ran in child effects have landed.\n const lastConflictSigRef = useRef<{ sig: string; modes: ModeRegistry | undefined } | null>(null);\n const entrySig = entries.map((e) => e.id).join(',');\n const modesRegistry = opts.modes;\n useEffect(() => {\n if (!isDev()) return;\n const last = lastConflictSigRef.current;\n if (last?.sig === entrySig && last.modes === modesRegistry) return;\n lastConflictSigRef.current = { sig: entrySig, modes: modesRegistry };\n // An entry can be in both buckets and usually is: every tool `defineTool`\n // builds declares `focus: true`, and an ambient one carries `always: true`\n // on top of that. Sorting on \"not focus-eligible\" put ambient tools in the\n // registry bucket, which is never compared against itself — registry tools\n // take turns in the active slot — so ambient-vs-ambient went unreported.\n const registry: Contribution<TOverlay>[] = [];\n const ambient: Contribution<TOverlay>[] = [];\n for (const entry of entries) {\n if (entry.eligibility?.focus) registry.push(entry);\n if (entry.eligibility?.always || entry.eligibility?.claimed) ambient.push(entry);\n }\n reportRouteConflicts({\n registry,\n ambient,\n actions: actionsRegistry?.list() ?? [],\n ...(modesRegistry ? { modes: modesRegistry.list().map(activeModeOf) } : {}),\n });\n }, [entrySig, entries, actionsRegistry, modesRegistry]);\n\n // Memoized so consumers using the result as an effect dep don't see identity\n // churn every render — which loops infinitely when the consumer setStates\n // from inside such an effect.\n return useMemo(\n () => ({ entries, focused, setFocused, overlays }),\n [entries, focused, setFocused, overlays],\n );\n}\n\n/**\n * Registers the consolidated `tool.offhand` action for every entry declaring\n * an `offhand` trigger, into the nearest `<ActionsProvider>`; its invoker\n * reads `params.toolId` off the matched binding. `useContributions` calls it,\n * and so does any host that assembles its entries above its own provider —\n * `<SceneCanvas>` does — since a null registry here registers nothing.\n */\nexport function useOffhandAction(entries: readonly Contribution<unknown>[]): void {\n const actionsRegistry = useActionsRegistry();\n const offhandSig = JSON.stringify(entries\n .filter((e) => e.eligibility?.offhand)\n .map((e) => [e.id, e.eligibility.offhand]));\n useEffect(() => {\n const pairs = JSON.parse(offhandSig) as [string, HotkeyTrigger][];\n if (!actionsRegistry || pairs.length === 0) return;\n const specs: ToolOffhandBindingSpec[] = pairs.map(([toolId, trigger]) => (\n { toolId, key: offhandKeyFor(trigger) }\n ));\n return actionsRegistry.register(makeToolOffhandAction(buildToolOffhandBindings(specs)));\n }, [actionsRegistry, offhandSig]);\n}\n","// src/tools/useTools.ts\nimport { useCallback, useMemo } from 'react';\nimport type { ModeRegistry } from '@weasel-js/modes';\nimport { dlog } from '../dlog';\nimport type { AnyTool, Tool } from './types';\nimport type { HotkeyTrigger } from '../contributions/types';\nimport { useActiveToolContext } from '../interactions/actions/activeToolContext';\nimport { useContributions } from '../contributions/useContributions';\nimport type { Contribution, Eligibility, OverlayPosition } from '../contributions/types';\nimport type { KernelOverlay } from '../index';\nimport { sameList, useLatest, useStableByContent } from '@weasel-js/react';\n\n/** Options for `useTools`: which tools exist, which one starts active, and\n * which run continuously regardless of the active one. */\nexport interface UseToolsOptions<TOverlay = KernelOverlay> {\n /** Initial active-slot tool id, which must exist in `registry`. Omit, or\n * pass `null`, for no active tool: only hotkey and ambient bindings run. */\n active?: string | null;\n /** Tools eligible for the active slot or hotkey slot. The keys are the\n * tool ids; the values are the tool records. A tool with `hotkey` set\n * is wired into the hotkey slot whenever the engagement state matches. */\n registry: Record<string, Tool<TOverlay>>;\n /** Always-on entries — tools or other contributions, live regardless of\n * the active slot. */\n ambient?: readonly Contribution<TOverlay>[];\n /** The modes the canvas can be in, read by the dev-time route-conflict\n * check; without a registry it checks against the kit's `DEFAULT_MODES`. */\n modes?: ModeRegistry;\n}\n\n/** The tool registry's runtime surface: which tool is active, which is\n * temporarily held by a hotkey, and how to change either. */\nexport interface ToolsApi<TOverlay = KernelOverlay> {\n /** Current active-slot tool id, or `null` when no tool is active. */\n active: string | null;\n /** Set the active-slot tool, or `null` to clear it. The gesture dispatcher\n * watches the active tool and cancels any in-flight handle itself. */\n setActive: (id: string | null) => void;\n /** Currently hotkey-engaged tool id (or `null`): the top of the hotkey stack. */\n hotkeyEngaged: string | null;\n /** Engage a hotkey-slot tool by id. */\n engageHotkey: (id: string) => void;\n /** Disengage the hotkey-slot tool, if any. */\n disengageHotkey: () => void;\n /** All always-on entries, in registration order. */\n ambient: readonly Contribution<TOverlay>[];\n /** Full registry — for userland UI (palette buttons, etc.). */\n registry: Readonly<Record<string, Tool<TOverlay>>>;\n /** Returns true if a tool with the given id is in the registry or ambient list. */\n has(id: string): boolean;\n /** Overlay layers from currently-engaged tools that declare `position`.\n * Order: active, then hotkey (if engaged), then ambient (registration order). */\n getActiveOverlays(position?: OverlayPosition): TOverlay[];\n}\n\n/** The slot a caller passed a tool in, restated as declared eligibility.\n * A tool that already declares what its slot implies is returned as-is:\n * `ToolsApi.registry` hands back the objects the caller passed, and\n * consumers compare identity. */\nfunction declareSlot<T extends Contribution<unknown>>(tool: T, slot: 'focus' | 'always'): T {\n const hotkey = (tool.def as { hotkey?: HotkeyTrigger } | undefined)?.hotkey;\n const eligibility: Eligibility = {\n ...tool.eligibility,\n [slot]: true,\n ...(hotkey ? { offhand: hotkey } : {}),\n };\n return sameEligibility(tool.eligibility, eligibility) ? tool : { ...tool, eligibility };\n}\n\nconst NO_AMBIENT: readonly never[] = [];\n\n/** `registry` and `ambient` as last passed, kept by identity for as long as\n * every tool in them is the same object under the same id. */\nfunction useStableSources<T extends AnyTool, A extends Contribution<unknown>>(\n registry: Record<string, T>,\n ambient: readonly A[] | undefined,\n): { registry: Record<string, T>; ambient: readonly A[] } {\n return useStableByContent(\n { registry, ambient: ambient ?? NO_AMBIENT },\n (a, b) => sameRecord(a.registry, b.registry) && sameList(a.ambient, b.ambient),\n );\n}\n\nfunction sameRecord<T>(a: Record<string, T>, b: Record<string, T>): boolean {\n const ak = Object.keys(a);\n if (ak.length !== Object.keys(b).length) return false;\n return ak.every((k) => k in b && a[k] === b[k]);\n}\n\nfunction sameEligibility(a: Eligibility | undefined, b: Eligibility): boolean {\n if (!a) return false;\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof Eligibility>;\n for (const key of keys) if (a[key] !== b[key]) return false;\n return true;\n}\n\n/**\n * Manages the active tool and hotkey slot; a thin shim over\n * {@link useContributions}.\n *\n * Requires `<ActiveToolContextProvider>` (or `<WeaselProvider>` /\n * `<SceneCanvas>`, which mount one internally) in scope: active/hotkey state\n * lives in the context.\n *\n * **First mount wins**: if the context's slot is unseeded on first mount,\n * `useTools` pushes `opts.active` to the context. Subsequent mounts respect\n * whatever the context currently holds.\n */\nexport function useTools<TOverlay = KernelOverlay>(\n opts: UseToolsOptions<TOverlay>,\n): ToolsApi<TOverlay> {\n const initialActive = opts.active ?? null;\n if (initialActive !== null && !(initialActive in opts.registry)) {\n throw new Error(`useTools: active \"${initialActive}\" not in registry`);\n }\n\n const ctx = useActiveToolContext();\n\n // Rebuilt when the tools themselves change, not the objects holding them:\n // callers commonly pass `opts.registry` / `opts.ambient` as literals made\n // every render, while a tool redefined under an existing id must replace it.\n const sources = useStableSources(opts.registry, opts.ambient);\n const slotted = useMemo(() => {\n const registry: Record<string, Tool<TOverlay>> = {};\n for (const [id, tool] of Object.entries(sources.registry)) {\n registry[id] = declareSlot(tool, 'focus');\n }\n const ambient = sources.ambient.map((t) => declareSlot(t, 'always'));\n const byId = new Map<string, Contribution<TOverlay>>();\n for (const tool of [...Object.values(registry), ...ambient]) {\n const prior = byId.get(tool.id);\n if (prior) byId.set(tool.id, { ...tool, eligibility: { ...prior.eligibility, ...tool.eligibility } });\n else byId.set(tool.id, tool);\n }\n return { registry, ambient, entries: [...byId.values()] };\n }, [sources]);\n\n const contributions = useContributions<TOverlay>({\n entries: slotted.entries,\n focused: initialActive,\n ...(opts.modes ? { modes: opts.modes } : {}),\n });\n\n const hotkeyEngaged = ctx.hotkeyStack.at(-1) ?? null;\n\n // Refs so the memoized callbacks below see latest values without\n // re-creating themselves.\n const slottedRef = useLatest(slotted);\n const activeRef = useLatest(contributions.focused);\n const hotkeyRef = useLatest(hotkeyEngaged);\n\n const setFocused = contributions.setFocused;\n const setActive = useCallback(\n (id: string | null) => {\n if (id !== null && !(id in slottedRef.current.registry)) {\n throw new Error(`setActive: \"${id}\" not in registry`);\n }\n dlog('tools', 'active:', activeRef.current, '→', id);\n setFocused(id);\n },\n [setFocused, slottedRef, activeRef],\n );\n\n const engageHotkey = useCallback(\n (id: string) => {\n if (!(id in slottedRef.current.registry)) {\n throw new Error(`engageHotkey: \"${id}\" not in registry`);\n }\n dlog('tools', 'hotkey engaged:', id);\n ctx.pushHotkey(id);\n },\n [ctx, slottedRef],\n );\n\n const disengageHotkey = useCallback(() => {\n if (hotkeyRef.current) dlog('tools', 'hotkey disengaged:', hotkeyRef.current);\n ctx.popHotkey();\n }, [ctx, hotkeyRef]);\n\n // May be called while rendering, so it reads this render's tools, not a ref.\n const has = useCallback(\n (id: string): boolean =>\n id in slotted.registry\n || slotted.ambient.some((t) => t.id === id),\n [slotted],\n );\n\n // Memoized: a consumer using `tools` as an effect dep loops infinitely on\n // identity churn when it setStates from inside that effect.\n const active = contributions.focused;\n const getActiveOverlays = contributions.overlays;\n return useMemo(\n () => ({\n active,\n setActive,\n hotkeyEngaged,\n engageHotkey,\n disengageHotkey,\n ambient: slotted.ambient,\n registry: slotted.registry,\n has,\n getActiveOverlays,\n }),\n [active, setActive, hotkeyEngaged, engageHotkey, disengageHotkey, has, getActiveOverlays, slotted],\n );\n}\n"]}