@weasel-js/core 1.0.3 → 1.0.4
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/CHANGELOG.md +147 -0
- package/dist/{chunk-U45SODC2.js → chunk-4Z6J4IVH.js} +43 -27
- package/dist/chunk-4Z6J4IVH.js.map +1 -0
- package/dist/{chunk-SMCZRSYB.js → chunk-AYGSXNY3.js} +460 -212
- package/dist/chunk-AYGSXNY3.js.map +1 -0
- package/dist/{chunk-3KGMJMOS.js → chunk-CSMF654J.js} +3 -3
- package/dist/{chunk-3KGMJMOS.js.map → chunk-CSMF654J.js.map} +1 -1
- package/dist/{chunk-TR3HZN34.js → chunk-J3YC3GVF.js} +5 -4
- package/dist/chunk-J3YC3GVF.js.map +1 -0
- package/dist/{chunk-3JYFAQIB.js → chunk-J7LUY47N.js} +3 -3
- package/dist/{chunk-3JYFAQIB.js.map → chunk-J7LUY47N.js.map} +1 -1
- package/dist/index.d.ts +8 -38
- package/dist/index.js +5 -5
- package/dist/insert.js +1 -1
- package/dist/move.js +3 -3
- package/dist/move.js.map +1 -1
- package/dist/{registry-CxnkXbG8.d.ts → registry-QRg8KiNM.d.ts} +1 -1
- package/dist/renderer.d.ts +29 -13
- package/dist/renderer.js +5 -5
- package/dist/resize.js +2 -2
- package/dist/routing.d.ts +1 -1
- package/dist/routing.js +1 -1
- package/package.json +6 -6
- package/dist/chunk-SMCZRSYB.js.map +0 -1
- package/dist/chunk-TR3HZN34.js.map +0 -1
- package/dist/chunk-U45SODC2.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/interactions/actions/depRegistry.tsx","../src/interactions/actions/buildDeps.ts","../src/interactions/actions/registry.tsx","../src/tools/routing/reflection/registry.ts","../src/tools/routing/reflection/conflicts.ts"],"names":["createContext","useRef","useMemo","jsx","useContext","useEffect"],"mappings":";;;;;;AAgCA,IAAM,kBAAA,GAAqB,cAAkC,IAAI,CAAA;AA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AA,OAAO,GAAA;AACT;AAWO,SAAS,eAAe,QAAA,EAA4B;AACzD,EAAA,MAAM,QAAQ,WAAA,CAAY;AAAA,IACxB,MAAA,EAAQ,CAAC,EAAE,OAAA,EAAS,GAAA,EAAK,KAAA,EAAO,QAAA,CAAS,KAAA,KAAU,KAAA,GAAQ,GAAA,GAAM,QAAA,CAAS,KAAA,EAAO,CAAA;AAAA,IACjF,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,KAAK,QAAA,CAAS,GAAA;AAAA,IACd,QAAQ,QAAA,CAAS,MAAA;AAAA,IACjB,WAAW,QAAA,CAAS;AAAA,GACrB,CAAA;AACD,EAAA,OAAO,GAAG,KAAK,CAAA,oBAAA,EAAkB,SAAS,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA;AAC9D;AAmBO,SAAS,oBAAA,CACd,QACA,IAAA,GAAkC,CAAC,MAAM,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,EAC3C;AACZ,EAAA,MAAM,SAAA,GAAY,oBAAoB,MAAM,CAAA;AAC5C,EAAA,KAAA,MAAW,KAAK,SAAA,EAAW;AACzB,IAAA,IAAA;AAAA,MACE,CAAA;AAAA,EAAA,EAC+E,cAAA,CAAe,CAAC,CAAC,CAAA;AAAA,KAClG;AAAA,EACF;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-TR3HZN34.js","sourcesContent":["/**\n * Dep registry for registry unification.\n *\n * Holds named \"live source\" thunks. Actions declare `requires: ['selection']`;\n * the dispatcher calls `registry.get('selection')` at invocation time to\n * build a typed Deps bag.\n *\n * `DepSchema` — the map of dep name → value type — is the single source of\n * truth for what `requires`/`register`/`get` accept. Its concrete fields live\n * in `./depSchema` (co-located with the dep value types). It is declared there\n * as a plain `export interface` rather than via a cross-module\n * `declare module './depRegistry'` augmentation: that augmentation does NOT\n * merge once rollup-plugin-dts flattens both files into one `.d.ts` chunk,\n * which silently emptied `DepSchema` for consumers. Consumers still extend it\n * via `declare module '@weasel-js/core'` augmentation.\n */\nimport {\n createContext, useContext, useEffect, useMemo, useRef,\n type ReactNode,\n} from 'react';\nimport type { DepSchema, DepName } from './depSchema';\n\nexport type { DepSchema, DepName };\n\n/** Holds the live sources an action's declared dependencies resolve to.\n * Sources are thunks, read at invocation time, so an action never captures\n * stale state. */\nexport interface DepRegistry {\n register<K extends DepName>(name: K, source: () => DepSchema[K]): () => void;\n get<K extends DepName>(name: K): DepSchema[K] | undefined;\n}\n\nconst 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 sourcesRef = useRef(new Map<DepName, () => unknown>() as Map<string, () => unknown>);\n\n const registry = useMemo<DepRegistry>(() => ({\n register: <K extends DepName>(name: K, source: () => DepSchema[K]) => {\n sourcesRef.current.set(name as string, source as () => unknown);\n return () => { sourcesRef.current.delete(name as string); };\n },\n get: <K extends DepName>(name: K) =>\n sourcesRef.current.get(name as string)?.() as DepSchema[K] | undefined,\n }), []);\n\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 = useRef(source);\n sourceRef.current = source;\n useEffect(() => {\n return registry.register(name, () => sourceRef.current());\n }, [name, registry]);\n}\n","/**\n * Shared dep-bag builder — the single implementation behind both the gesture\n * dispatcher's per-invocation `buildDeps` and `ActionsRegistry.trigger`'s\n * `requires` branch. Reads the action's declared `requires`, resolves each\n * name against the `DepRegistry`, and (dev builds only) wraps the bag in a\n * Proxy that warns on undeclared reads.\n */\nimport type { Action } from './registry';\nimport type { DepRegistry } from './depRegistry';\nimport type { ActionDeps } from './invoker';\n\n/** True in dev builds; false in production. Tree-shakes the Proxy out of\n * prod entirely. (Mirrors the dispatcher's own `DEV` const.) */\nconst DEV: 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/** Build the deps bag for an action from its declared `requires`. */\nexport function buildDepsFromRequires(action: Action, depRegistry: DepRegistry): ActionDeps {\n const requires = action.requires ?? [];\n const entries = requires.map((name) => [name, depRegistry.get(name)]);\n const deps = Object.fromEntries(entries) as ActionDeps;\n\n // Dev-only: wrap deps in a Proxy that warns when the invoker reads a\n // key not declared in `requires`. Catches silent-failure-by-typo or\n // forgotten-requires (the #1 bug class in this codebase pre-Phase-14e).\n // Production builds: bypass the Proxy entirely (zero overhead).\n if (DEV) {\n const declared = new Set<string>(requires);\n return new Proxy(deps as Record<string, unknown>, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !declared.has(prop) && prop !== 'then') {\n const message =\n `[weasel:dispatcher] action \"${action.id}\" read deps.${prop} but did not declare it in \\`requires\\`. ` +\n `Add \\`requires: [...'${prop}']\\` to the descriptor or the dep will be undefined at runtime.`;\n // Warn first so the console trail survives even when the throw is\n // swallowed by a caller, then throw so the gesture fails visibly\n // instead of silently running without the dep.\n // eslint-disable-next-line no-console\n console.warn(message);\n throw new Error(message);\n }\n return Reflect.get(target, prop, receiver);\n },\n }) as ActionDeps;\n }\n return deps;\n}\n","/**\n * @experimental\n * Actions Registry — owns the registered `Action` descriptors and the\n * imperative `trigger` path. Keystrokes reach actions through the gesture\n * dispatcher matching their `defaultBinding`, not through a listener here.\n * Spec: docs/superpowers/specs/2026-05-09-actions-registry-design.md\n */\nimport {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n type ReactElement,\n type ReactNode,\n} from 'react';\nimport type { GestureSpec, PhaseSpec } from '../gestures/spec';\nimport type { ActionDeps, BindingOpts, Invoker } from './invoker';\nimport type { GestureBinding } from './binding';\nimport { useOptionalDepRegistry, type DepRegistry, type DepName } from './depRegistry';\nimport { buildDepsFromRequires } from './buildDeps';\nimport { RESERVED_ID_NAMES, RESERVED_ID_PREFIXES, type PhaseAtom } from '../../tools/routing/routeGrammar';\nimport type { Dispatcher, UiOngoingControl } from '../dispatcher/dispatcher';\nexport type { UiOngoingControl } from '../dispatcher/dispatcher';\n\n/**\n * @experimental\n * A single entry in `Action.defaultBinding[]`. Either a bare `GestureSpec`\n * (no per-binding opts) or an object form that pairs a spec with\n * `BindingOpts` for parametric actions (e.g. `{ params: { axis: 'x' } }`).\n * Use the object form when two bindings for the same action differ only in\n * a runtime parameter — the dispatcher extracts `opts.params` and passes\n * them to `ImmediateInvoker.run` as its second argument.\n */\nexport type BoundGesture = GestureSpec | { spec: GestureSpec; opts: BindingOpts };\n\n/**\n * @experimental\n * Flatten an action's `defaultBinding` into `GestureBinding`s. A bare\n * `GestureSpec` has `kind` at top level; the object form has `spec`.\n */\nexport function actionBindings(action: Action): GestureBinding[] {\n const gs = action.defaultBinding;\n if (!gs) return [];\n const raw: BoundGesture[] = Array.isArray(gs) ? gs : [gs as BoundGesture];\n return raw.map((entry) => {\n const isBoundObj = !('kind' in entry);\n const spec = isBoundObj ? (entry as { spec: GestureSpec }).spec : (entry as GestureSpec);\n const opts = isBoundObj ? (entry as { opts: BindingOpts }).opts : undefined;\n return { spec, actionId: action.id, ...(opts !== undefined ? { opts } : {}) };\n });\n}\n\n/**\n * @experimental\n * Single registered action. v1: one binding per action.\n */\nexport interface Action {\n id: string;\n label: string;\n /** The gesture-spec form of the binding, read by the gesture dispatcher.\n * May be a single `GestureSpec`, a bare `GestureSpec[]` (any-of semantics),\n * or a `BoundGesture[]` where each entry is either a bare `GestureSpec` or\n * `{ spec, opts }` — use the object form for parametric actions where two\n * bindings for the same action differ only by `opts.params` (e.g. `flip`\n * with `axis: 'x'` vs `'y'`). The dispatcher extracts `opts.params` and\n * passes them to `ImmediateInvoker.run` as its second argument. */\n defaultBinding?: GestureSpec | BoundGesture[];\n /** Names of the deps this action's invoker reads (keys of `DepSchema`).\n * The dispatcher (and `trigger`, when `requires` is present) resolves\n * each name against the `DepRegistry` at invocation time and passes the\n * resulting bag to the invoker. Dev builds warn when the invoker reads a\n * dep it didn't declare here — see `buildDepsFromRequires`. */\n requires?: readonly DepName[];\n /** Inline-SVG icon for palette / toolbar surfaces. Mirrors\n * `ToolPresentation.icon` so a generic `<ActionBar>` can render from\n * action metadata the same way `<ToolPalette>` renders from tool\n * metadata. May be a static `ReactNode` or a function (rare; useful\n * for state-aware icons like a \"lock\" toggle). */\n icon?: ReactNode | (() => ReactNode);\n /** Grouping key for palette/menu surfaces. Free-form string; the kit\n * ships defaults for `'align'` (six edges/centers), `'distribute'`\n * (two axes), and recommends `'pathfinder'` for boolean ops. */\n group?: string;\n /** Display override for the keyboard shortcut. When omitted, palette\n * surfaces derive a label from `defaultBinding` via their own\n * formatter. */\n shortcut?: string;\n /** Pluggable invocation strategy. The gesture dispatcher routes matched\n * bindings through `invoker.start` / `invoker.run` depending on timing.\n * All kit-standard descriptors ship one; consumer-supplied actions\n * without an invoker can still register but won't be triggered. */\n invoker?: Invoker;\n /** When set to `'hotkey'`, this action's `defaultBinding` rides the hotkey\n * `BindingScope` instead of the ambient scope — meaning it beats any\n * active-tool binding on the same input shape. Use for tool-switch\n * shortcuts and global held-key triggers. Default: ambient. */\n scope?: 'hotkey';\n /**\n * @experimental\n * Optional predicate the command palette consults when rendering. Return\n * `true` when the action is currently triggerable. Return a reason string\n * (e.g. `'Selection required'`) when disabled — the palette greys out\n * the row, skips it in keyboard nav, ignores clicks, and shows the\n * reason next to the label. Keystroke dispatch (the registered binding)\n * is unaffected; the action's own `run` should self-guard.\n *\n * **Contract:** must be pure (no side effects), fast (< 4ms in dev), and\n * must not throw. If a call throws or exceeds the budget in dev mode,\n * `evaluateEnabled` logs a one-time warning per action id; throws are\n * caught and treated as disabled with reason `'(predicate threw)'`.\n *\n * Snapshot-on-open semantics: the palette evaluates `enabled` once when\n * opened and does NOT re-evaluate on selection changes while open. Live\n * reactive updates are deferred — palette is short-lived.\n *\n * The reason set is a closed enum — to add a new reason, edit\n * `ActionDisabledReason` and the consumer's display map.\n *\n * The optional `deps` argument is the same bag passed to\n * `ImmediateInvoker.run`; callers (`evaluateEnabled` / the ActionBar) may\n * synthesize it from the surrounding `DepRegistry` so predicates can\n * inspect selection / scene / etc. Predicates that don't need deps just\n * ignore the arg.\n */\n enabled?: (deps?: ActionDeps) => true | ActionDisabledReason;\n /**\n * Declarative eligibility rule, evaluated against the current\n * `RuleCtx` by the dispatcher before invoking `start()`. Omitted =\n * always eligible.\n *\n * Accepts either a fluent `Condition` (callable with `.rule`) or a\n * raw `Rule` tree; the dispatcher normalizes via `.rule` unwrap.\n *\n * Prefer `capability:`-based rules (e.g. `{ capability: 'transforms-selection' }`)\n * over `mode:` rules — capability rules survive new modes being added\n * that allow the same capability.\n */\n eligible?:\n | import('../../features/chrome-caps').Rule\n | import('../../features/chrome-caps').Condition;\n /**\n * CSS cursor shown while the pointer hovers a spot where this action\n * would win the drag. The hover-cursor pump (in `useGestureDispatcher`)\n * runs `Dispatcher.resolveOnly` on each idle pointermove — the same\n * match walk a real pointerdown takes — and applies the winning\n * action's `cursor`, so the hint and the actual click target stay in\n * sync by construction. Omitted = no override (the active tool's\n * `Tool.cursor` shows). Affordance hits are resolved earlier in the\n * pump via `AffordanceRegion.cursor` and never reach this field.\n *\n * Static string only. Prediction runs `enabled()` but cannot run the\n * invoker, so an action that matches yet bails at `start()` (empty\n * handle) may still show its cursor — keep `enabled` accurate for\n * actions that declare one.\n */\n cursor?: string;\n /**\n * CSS cursor shown while THIS action's ongoing handle is in flight —\n * grabbing while panning, `move` while dragging a selection, `crosshair`\n * while pulling a marquee.\n *\n * Separate from `cursor` because the two answer different questions:\n * `cursor` is a prediction (\"a drag from here would pan\"), this is a state\n * (\"you are panning\"). An action can declare either, both, or neither;\n * with only `cursor` set, the hover hint holds for the duration of the\n * gesture.\n *\n * This is where mid-gesture cursors live now. They used to come from the\n * tool side — `ViewportToolDef.engaged.cursor` for a phase-gated string,\n * or a function-form `Tool.cursor` reading the gesture scratch out of the\n * tool-routing dispatcher. Both belonged to a pipeline whose whole job was\n * being taken over by bindings, and neither could describe a cursor for an\n * action a tool doesn't own.\n */\n activeCursor?: string;\n}\n\n/**\n * @experimental\n * Closed enum of reasons an action might report itself as disabled. The\n * consumer (palette, menu, etc.) maps these symbolic values to display\n * strings via its own label map — see `demo/CommandPalette.tsx` for the\n * canonical mapping.\n */\nexport const ActionDisabledReason = {\n SelectionRequired: 'selection-required',\n SceneEmpty: 'scene-empty',\n NotApplicable: 'not-applicable',\n /** Sentinel: the predicate threw. Surfaced by `evaluateEnabled`'s catch. */\n PredicateThrew: 'predicate-threw',\n} as const;\n/** Why an action is unavailable right now. */\nexport type ActionDisabledReason =\n (typeof ActionDisabledReason)[keyof typeof ActionDisabledReason];\n\n/**\n * @experimental\n * Result of evaluating an Action's `enabled` predicate.\n */\nexport interface ActionEnabledResult {\n enabled: boolean;\n reason?: ActionDisabledReason;\n}\n\nconst enabledSlowWarned = new Set<string>();\nconst enabledThrewWarned = new Set<string>();\nconst ENABLED_BUDGET_MS = 4;\n/**\n * @experimental\n * Safely evaluate an action's `enabled` predicate. Returns `{enabled: true}`\n * when no predicate is supplied. Catches throws and treats them as disabled\n * with reason `'(predicate threw)'`. In dev mode, warns once per action id\n * when a single call exceeds 4ms (single frame at 240fps — generous; real\n * predicates should be sub-millisecond).\n */\nexport function evaluateEnabled(\n action: Action,\n deps?: ActionDeps,\n): ActionEnabledResult {\n if (!action.enabled) return { enabled: true };\n const isDev = typeof process !== 'undefined' ? process.env.NODE_ENV !== 'production' : true;\n const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')\n ? () => performance.now()\n : () => Date.now();\n const start = isDev ? now() : 0;\n try {\n const result = action.enabled(deps);\n if (isDev) {\n const elapsed = now() - start;\n if (elapsed > ENABLED_BUDGET_MS && !enabledSlowWarned.has(action.id)) {\n enabledSlowWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" took ${elapsed.toFixed(2)}ms ` +\n `(budget ${ENABLED_BUDGET_MS}ms). The predicate must be pure and fast — see Action.enabled JSDoc.`,\n );\n }\n }\n if (result === true) return { enabled: true };\n return { enabled: false, reason: result };\n } catch (e) {\n if (isDev && !enabledThrewWarned.has(action.id)) {\n enabledThrewWarned.add(action.id);\n console.warn(\n `weasel actions: enabled() for action \"${action.id}\" threw; treating as disabled. ` +\n `The predicate must not throw — see Action.enabled JSDoc.`,\n e,\n );\n }\n return { enabled: false, reason: ActionDisabledReason.PredicateThrew };\n }\n}\n\n/** @internal Test helper: reset warn-once dedup so tests can repro-fire warnings. */\nexport function _resetEnabledWarnsForTests(): void {\n enabledSlowWarned.clear();\n enabledThrewWarned.clear();\n}\n\n/**\n * @experimental\n * Partial override or full descriptor passed via `<SceneCanvas actions={...}>`.\n * `null` disables a default at this id.\n */\nexport type ActionEntry = null | Partial<Action> | Action;\n\n/**\n * @experimental\n * Shape of the `actions` prop on `<SceneCanvas>`. `null` disables all defaults.\n */\nexport type ActionsProp = null | Record<string, ActionEntry>;\n\n/**\n * @experimental\n * Imperative API exposed by `useActionsRegistry()`.\n */\nexport interface ActionsRegistry {\n register(action: Action): () => void;\n unregister(id: string): void;\n list(): readonly Action[];\n /** Fire an immediate-invoker action by id. The optional `params` arg is\n * forwarded to `ImmediateInvoker.run` as its second argument — use it for\n * parametric actions (e.g. `trigger('tool.activate', { toolId: 'rect' })`).\n * Ongoing-invoker actions are not reachable from `trigger`. */\n trigger(id: string, params?: Record<string, unknown>): boolean;\n /**\n * Subscribe to registry mutations. The callback fires after any\n * `register`/`unregister` that changes the version. Returns an\n * unsubscribe function. Designed for `useSyncExternalStore`-driven\n * surfaces (e.g. `<ActionBar>` in `@weasel-js/ui`) that need to\n * re-render when the action set changes.\n */\n subscribe(listener: () => void): () => void;\n\n /**\n * Start an ongoing action driven by UI (color picker, opacity slider).\n * Returns a control object with `update(params)` and `end(reason)`.\n *\n * Returns `null` if no dispatcher is wired into this registry, the\n * action is unknown, or its invoker is not ongoing.\n *\n * See `Dispatcher.beginUiOngoing` for full semantics including\n * auto-commit when a prior UI handle for the same action is in flight.\n */\n begin(id: string, params?: Record<string, unknown>): UiOngoingControl | null;\n\n /** Wire a dispatcher into the registry so `begin()` can delegate to it.\n * Call with `null` to detach. Idempotent. */\n setDispatcher(d: Dispatcher | null): void;\n\n /** Wire a `DepRegistry` into the registry so `trigger()` / `begin()` can\n * resolve action deps even when this provider is mounted ABOVE the dep\n * registry (e.g. a consumer's root `<ActionsProvider>` reused by\n * SceneCanvas's `ActionsProviderIfRoot`). Takes precedence over the dep\n * registry read from context at the provider's own level. Call with\n * `null` to detach. */\n setDepRegistry(r: DepRegistry | null): void;\n}\n\n// ─── Registration-time validation ─────────────────────────────────────────\n\n/** Validate that `id` is usable as an action id in the route grammar.\n * Rejects ids that start with a reserved sigil (would shadow future\n * grammar extensions) and ids that collide with phase keywords (would\n * parse as the bare-phase shorthand). Mirrors `defineTool`'s tool-id\n * validation. */\nfunction validateActionId(id: string): void {\n if (id.length === 0) {\n throw new Error(`weasel: action id may not be empty`);\n }\n if (RESERVED_ID_PREFIXES.has(id[0]!)) {\n throw new Error(\n `weasel: action id \"${id}\" starts with reserved sigil \"${id[0]}\" ` +\n `(reserved set: ${[...RESERVED_ID_PREFIXES].join(' ')})`,\n );\n }\n if (RESERVED_ID_NAMES.has(id)) {\n throw new Error(\n `weasel: action id \"${id}\" collides with a reserved phase keyword ` +\n `(reserved: ${[...RESERVED_ID_NAMES].join(', ')})`,\n );\n }\n}\n\n/** Reject any '&'-channel phase atom in an Action's defaultBinding —\n * actions have no owning tool, so '&' can't resolve. Tool-side bindings\n * (Tool.bindings) are the right place for '&' atoms. */\nfunction validateActionDefaultBinding(action: Action): void {\n const gs = action.defaultBinding;\n if (!gs) return;\n const entries: BoundGesture[] = Array.isArray(gs) ? gs : [gs as BoundGesture];\n for (const entry of entries) {\n const spec = ('kind' in entry ? entry : entry.spec) as GestureSpec;\n const phase: PhaseSpec | undefined = spec.phase;\n if (phase === undefined) continue;\n const atoms: readonly PhaseAtom[] = Array.isArray(phase)\n ? phase\n : [{ channel: '&', phase: phase }];\n for (const atom of atoms) {\n if (atom.channel === '&') {\n throw new Error(\n `weasel: action \"${action.id}\" defaultBinding uses '&' channel ` +\n `which has no owning tool to resolve to. Use a named tool channel ` +\n `(e.g. '[rect:engaged]') or '*' instead, or move this binding to ` +\n `the tool's own Tool.bindings.`,\n );\n }\n }\n }\n}\n\nconst ActionsContext = createContext<ActionsRegistry | null>(null);\n\n/**\n * @experimental\n * Mounts an `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 const actionsRef = useRef<Map<string, Action>>(new Map());\n const versionRef = useRef(0);\n const cachedRef = useRef<readonly Action[]>([]);\n const cachedVerRef = useRef(-1);\n const listenersRef = useRef<Set<() => void>>(new Set());\n\n // Trigger() consults the optional dep registry so actions can be fired\n // imperatively from ActionBar / palette callers — the registered\n // `invoker.run` receives a deps bag built fresh from the registry.\n const depReg = useOptionalDepRegistry();\n const depRegRef = useRef<DepRegistry | null>(depReg);\n depRegRef.current = depReg;\n\n // Dep registry wired via setDepRegistry — set by SceneCanvas's registrar\n // when this provider sits above the dep-registry scope (consumer root\n // <ActionsProvider>). Preferred over the context read above.\n const wiredDepRegRef = useRef<DepRegistry | null>(null);\n\n // Dispatcher ref — wired from SceneCanvas via setDispatcher so that\n // begin() can delegate to beginUiOngoing.\n const dispatcherRef = useRef<Dispatcher | null>(null);\n\n // The legacy keystroke loop that walked every action's\n // `defaultBinding: KeyBinding` and matched against keydown is gone, along\n // with the per-action consumer hooks (`useEscape`, `useDelete`, ...) that\n // carried their own `useKeybinding` listener. Every kit-standard descriptor\n // now routes through the gesture dispatcher via `defaultBinding`.\n\n const registry = useMemo<ActionsRegistry>(() => {\n const snapshot = (): readonly Action[] => {\n const v = versionRef.current;\n if (cachedVerRef.current === v) return cachedRef.current;\n const out = Object.freeze(Array.from(actionsRef.current.values()));\n cachedRef.current = out;\n cachedVerRef.current = v;\n return out;\n };\n const notify = (): void => {\n for (const l of listenersRef.current) {\n try {\n l();\n } catch (err) {\n console.error('weasel ActionsRegistry: subscriber threw', err);\n }\n }\n };\n return {\n register: (action: Action) => {\n validateActionId(action.id);\n validateActionDefaultBinding(action);\n actionsRef.current.set(action.id, action);\n versionRef.current++;\n notify();\n return () => {\n const cur = actionsRef.current.get(action.id);\n // Only unregister if the current entry is still us (last-writer-wins\n // means a later registrant should not be clobbered by our cleanup).\n if (cur === action) {\n actionsRef.current.delete(action.id);\n versionRef.current++;\n notify();\n }\n };\n },\n unregister: (id: string) => {\n if (actionsRef.current.delete(id)) {\n versionRef.current++;\n notify();\n }\n },\n list: () => snapshot(),\n trigger: (id: string, params?: Record<string, unknown>) => {\n const a = actionsRef.current.get(id);\n if (!a) return false;\n try {\n if (a.invoker && a.invoker.timing === 'immediate') {\n const r = wiredDepRegRef.current ?? depRegRef.current;\n // Prefer the action's declared `requires` (same contract the\n // dispatcher uses — shared `buildDepsFromRequires`, including\n // the dev-mode undeclared-read guard); legacy fixed bag\n // otherwise.\n const deps = !r\n ? {}\n : a.requires\n ? buildDepsFromRequires(a, r)\n : {\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 pointer: r.get('pointer' as DepName),\n activeTool: r.get('activeTool' as DepName),\n booleansAdapter: r.get('booleansAdapter' as DepName),\n };\n a.invoker.run(deps as never, params);\n }\n } catch (err) {\n console.error(`weasel ActionsRegistry: action \"${id}\" threw`, err);\n }\n return true;\n },\n subscribe: (listener: () => void) => {\n listenersRef.current.add(listener);\n return () => {\n listenersRef.current.delete(listener);\n };\n },\n setDispatcher: (d: Dispatcher | null) => {\n dispatcherRef.current = d;\n },\n setDepRegistry: (r: DepRegistry | null) => {\n wiredDepRegRef.current = r;\n },\n begin: (id: string, params?: Record<string, unknown>) => {\n const disp = dispatcherRef.current;\n if (!disp) return null;\n const r = wiredDepRegRef.current ?? depRegRef.current;\n const deps = r\n ? {\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 pointer: r.get('pointer' as DepName),\n activeTool: r.get('activeTool' as DepName),\n booleansAdapter: r.get('booleansAdapter' as DepName),\n }\n : {};\n return disp.beginUiOngoing(id, deps as never, params);\n },\n };\n }, []);\n\n return <ActionsContext.Provider value={registry}>{children}</ActionsContext.Provider>;\n}\n\n/**\n * @experimental\n * Returns the parent `ActionsRegistry`, or `null` when no provider is in scope.\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 when\n * no `ActionsProvider` is in scope. Re-registers on `action` reference change\n * (consumers should memoize stable identities to avoid churn).\n */\nexport function useAction(action: Action): void {\n const reg = useActionsRegistry();\n useEffect(() => {\n if (!reg) return;\n return reg.register(action);\n }, [reg, action]);\n}\n","import type { Tool } from '../../types';\nimport type { GestureSpec, ModSpec, TargetSpec, PhaseSpec } from '@weasel-js/gestures';\nimport type { ParsedModifiers, ModifierKey } from '../routeGrammar';\nimport { getGestureDescriptor, isKnownGestureName, type GestureName } from '../gestures';\n\n/**\n * One row in the route registry — a single `GestureBinding` on one tool,\n * flattened into the route grammar's vocabulary so the inspector, the\n * conflict checker, and `describeRoute` can all read the same shape.\n *\n * Multiple rows can share (gesture, arg, target, modifiers) if different tools\n * declare them; consumers walk the list and group client-side.\n */\nexport interface RegistryEntry {\n toolId: string;\n /** Which phase the binding's `phase` spec restricts it to. `'any'` when it\n * declares none, declares `'*'`, or declares an atom list whose atoms\n * don't agree on one phase — such a binding fires in either phase, and\n * reporting it as `'initial'` made it collide with genuinely-initial\n * bindings in `findConflicts`' bucket key. */\n phase: 'initial' | 'engaged' | 'any';\n /** Structured v3 modifier requirements. Empty object = \"no modifiers\n * held\" (the strict default). */\n modifiers: ParsedModifiers;\n gesture: GestureName;\n /** Resolved arg value for arg-bearing gestures (wheel direction,\n * key name, multiTouchTap fingers). Undefined for gestures whose\n * descriptor has no `arg`. */\n arg: string | undefined;\n /** Target class for hit-testing gestures. `undefined` when the descriptor\n * has `hasTarget: false` or the spec declares no target;\n * {@link PREDICATE_TARGET} when the spec uses a `kindOf` predicate, which\n * the route grammar has no notation for. */\n target: string | undefined;\n /** The action this binding fires. */\n actionId: string;\n /** The `GestureSpec` this row was flattened from, by reference. Reflection\n * consumers that need something the grammar doesn't capture — the\n * specificity tuple, a `kindOf` predicate identity — read it here rather\n * than re-walking `Tool.bindings`. */\n spec: GestureSpec;\n}\n\n/**\n * Stand-in target for a `{ kindOf }` predicate spec.\n *\n * The route grammar can name target *classes* (`empty`, `selected-body`,\n * `kind:rect`) but not arbitrary predicates, so three distinct select-tool\n * bindings all render as this one token. Narrowing it would mean giving the\n * grammar a way to describe a function, which is a real design question and\n * not one this reflection layer should answer by inventing syntax.\n */\nexport const PREDICATE_TARGET = 'predicate';\n\n/** `GestureSpec.kind` → route-grammar gesture name. `multiTouch` has no\n * route-grammar gesture (only its tap synthesis does), so specs of that kind\n * are skipped. */\nconst SPEC_KIND_TO_GESTURE: Record<GestureSpec['kind'], GestureName | undefined> = {\n key: 'keyDown',\n 'key-held': 'keyHeld',\n wheel: 'wheel',\n click: 'click',\n doubleClick: 'dblTap',\n contextMenu: 'contextMenu',\n longPress: 'longPress',\n drag: 'drag',\n pointerDown: 'pointerDown',\n multiTouch: undefined,\n multiTouchTap: 'multiTouchTap',\n drop: 'drop',\n paste: 'paste',\n};\n\n/**\n * Flatten every tool's `bindings` into route-registry rows.\n *\n * This was `buildActionRegistry`, and it walked `ToolDef.initial` /\n * `.engaged` phase tables — the grammar that no longer exists. It was also\n * blind to `Tool.bindings` the entire time the two lived side by side, which\n * is why the inspector under-reported select by more than half. The rename\n * fixes a second thing: it never had anything to do with the Actions\n * Registry, and reading `buildActionRegistry` next to `ActionsRegistry`\n * suggested otherwise.\n */\nexport function buildRouteRegistry(\n tools: readonly Tool<unknown>[],\n): RegistryEntry[] {\n const out: RegistryEntry[] = [];\n for (const tool of tools) {\n for (const binding of tool.bindings ?? []) {\n const entry = entryFor(tool.id, binding.spec, binding.actionId);\n if (entry) out.push(entry);\n }\n }\n return out;\n}\n\nfunction entryFor(\n toolId: string,\n spec: GestureSpec,\n actionId: string,\n): RegistryEntry | null {\n const gesture = SPEC_KIND_TO_GESTURE[spec.kind];\n if (!gesture || !isKnownGestureName(gesture)) return null;\n const descriptor = getGestureDescriptor(gesture);\n return {\n toolId,\n actionId,\n gesture,\n phase: phaseOf('phase' in spec ? spec.phase : undefined),\n modifiers: parseModSpec('mods' in spec ? spec.mods : undefined),\n arg: descriptor.arg ? argOf(spec, descriptor.arg.default) : undefined,\n target: descriptor.hasTarget\n ? targetOf('target' in spec ? spec.target : undefined)\n : undefined,\n spec,\n };\n}\n\n/** Collapse a `PhaseSpec` to the single phase a binding is restricted to, or\n * `'any'` when it isn't restricted to one.\n *\n * `PhaseAtom.channel` says which channel's phase state the binding reads,\n * not which phase it fires in, so it plays no part in this collapse — only\n * the set of distinct `atom.phase` values matters. */\nfunction phaseOf(phase: PhaseSpec | undefined): 'initial' | 'engaged' | 'any' {\n if (phase === undefined || phase === '*') return 'any';\n if (phase === 'initial' || phase === 'engaged') return phase;\n const distinct = new Set(phase.map((atom) => atom.phase));\n if (distinct.size !== 1) return 'any';\n const only = [...distinct][0];\n return only === 'initial' || only === 'engaged' ? only : 'any';\n}\n\n/** `ModSpec` (per-key tri-state) → `ParsedModifiers`. `false` and absent both\n * mean \"must not be held\", which the parsed form spells as an absent key. */\nfunction parseModSpec(mods: ModSpec | undefined): ParsedModifiers {\n if (!mods) return {};\n const out: ParsedModifiers = {};\n for (const [name, req] of Object.entries(mods)) {\n if (req === true) out[name as ModifierKey] = 'required';\n else if (req === 'optional') out[name as ModifierKey] = 'optional';\n }\n return out;\n}\n\nfunction targetOf(target: TargetSpec | undefined): string | undefined {\n if (target === undefined) return undefined;\n return typeof target === 'string' ? target : PREDICATE_TARGET;\n}\n\nfunction argOf(spec: GestureSpec, fallback: string | undefined): string | undefined {\n if ('key' in spec) {\n return Array.isArray(spec.key) ? spec.key.join('|') : spec.key;\n }\n if ('fingers' in spec) return String(spec.fingers);\n if ('direction' in spec) return spec.direction ?? fallback;\n if ('types' in spec) return spec.types?.length ? spec.types.join('|') : fallback;\n return fallback;\n}\n\n// Re-export for downstream consumers.\nexport { getGestureDescriptor };\nexport type { GestureName };\n","import type { Tool } from '../../types';\nimport { actionBindings, type Action } from '../../../interactions/actions/registry';\nimport type { ParsedModifiers } from '../routeGrammar';\nimport { canonicalModifiers, formatRoute } from '../routeGrammar';\nimport { buildRouteRegistry, PREDICATE_TARGET, type RegistryEntry, type GestureName } from './registry';\n\n/** Two or more tools declare the same exact (phase, gesture, arg, target,\n * modifiers) tuple — the dispatcher's slot precedence picks one\n * arbitrarily (well, deterministically by slot order, but the author\n * probably didn't intend the duplication). */\nexport interface Conflict {\n phase: 'initial' | 'engaged' | 'any';\n gesture: GestureName;\n arg: string | undefined;\n target: string | undefined;\n modifiers: ParsedModifiers;\n /** All tool ids that registered the same tuple. At least 2 by\n * construction. Order matches the input tools[] order. */\n toolIds: string[];\n}\n\n/** Detect exact-tuple overlaps across a tool registration set.\n *\n * Intentionally NOT flagged:\n * - Broad vs. narrow targets (e.g. an untargeted `click` alongside\n * `click` on `empty`) — the dispatcher's specificity ordering resolves\n * those cleanly, and the broad one is usually the intended fallback.\n * - Different modifier requirements on the same target — they fire on\n * different inputs.\n * - A binding whose action declines via `enabled()` so a lower-priority\n * one can take the gesture. Detecting that intent would mean evaluating\n * the action; consumers can suppress known-intentional compositions in\n * their UI layer.\n *\n * - Two `{ kindOf }` predicate targets. The route grammar renders every\n * predicate as the single token {@link PREDICATE_TARGET}, so bucketing on\n * the rendered target alone reported select's `resize` / `rotate` / `move`\n * drags — three genuinely different predicates — as a three-way conflict.\n * Predicate entries bucket by function identity instead, which means two\n * *separately written but equivalent* predicates go unflagged. That's the\n * right way to be wrong here: this check has to be silent when nothing is\n * wrong or nobody will keep it on.\n *\n * Note that two bindings sharing a tuple on the SAME tool are now possible\n * (bindings are an array, where phase tables were objects with unique\n * keys) — so a conflict may name one tool twice.\n *\n * This is the raw same-tuple detector. Feeding it a whole tool *registry*\n * over-reports, because registry tools take turns in the active slot and\n * can't collide with each other — see {@link findScopedConflicts}.\n */\nexport function findConflicts(\n tools: readonly Tool<unknown>[],\n): Conflict[] {\n const entries = buildRouteRegistry(tools);\n const groups = new Map<string, RegistryEntry[]>();\n for (const entry of entries) {\n const key = `${entry.phase}|${entry.gesture}|${entry.arg ?? ''}|${targetKey(entry)}|${canonicalModifiers(entry.modifiers)}`;\n const bucket = groups.get(key);\n if (bucket) bucket.push(entry);\n else groups.set(key, [entry]);\n }\n const conflicts: Conflict[] = [];\n for (const bucket of groups.values()) {\n if (bucket.length < 2) continue;\n const first = bucket[0];\n conflicts.push({\n phase: first.phase,\n gesture: first.gesture,\n arg: first.arg,\n target: first.target,\n modifiers: first.modifiers,\n toolIds: bucket.map((e) => e.toolId),\n });\n }\n return conflicts;\n}\n\n/** Bucket key for an entry's target slot. Predicate targets all render as\n * the same grammar token, so they're keyed by the predicate's identity —\n * two different functions are two different targets. */\nfunction targetKey(entry: RegistryEntry): string {\n if (entry.target !== PREDICATE_TARGET) return entry.target ?? '';\n const spec = entry.spec as { target?: unknown };\n const pred = spec.target;\n if (typeof pred !== 'object' || pred === null) return PREDICATE_TARGET;\n return `${PREDICATE_TARGET}#${predicateId(pred)}`;\n}\n\nconst PREDICATE_IDS = new WeakMap<object, number>();\nlet nextPredicateId = 0;\n\nfunction predicateId(pred: object): number {\n let id = PREDICATE_IDS.get(pred);\n if (id === undefined) {\n id = nextPredicateId++;\n PREDICATE_IDS.set(pred, id);\n }\n return id;\n}\n\n/**\n * The tool scopes as the dispatcher sees them — which is what decides whether\n * two same-tuple bindings can actually collide.\n */\nexport interface ToolScopes {\n /** Tools eligible for the active slot, keyed by id or as a flat list. */\n registry: readonly Tool<unknown>[] | Readonly<Record<string, Tool<unknown>>>;\n /** Always-on tools. Every one of these is live at once. */\n ambient?: readonly Tool<unknown>[];\n /** Registered actions. Their `defaultBinding`s assemble at ambient scope\n * (hotkey scope when `Action.scope` says so), alongside the tools above. */\n actions?: readonly Action[];\n}\n\n/** An action's `defaultBinding`s in the shape the route registry reads, so a\n * tool-vs-action collision buckets with the tool-vs-tool ones. */\nfunction actionAsTool(action: Action): Tool<unknown> {\n return { id: action.id, eligibility: {}, bindings: actionBindings(action) };\n}\n\n/**\n * Detect the same-tuple overlaps that are *reachable* — the ones where the\n * dispatcher really does fall back on declaration order.\n *\n * `matchSorted` walks scopes in strict priority (hotkey > active > ambient)\n * and only sorts by specificity *within* a scope. So a cross-scope tie isn't\n * a tie at all: an ambient tool losing a tuple to the active tool is the\n * documented design, not an accident. Likewise two registry tools sharing a\n * tuple — `rect` and `ellipse` both binding a bare `drag` — can never both be\n * in the active slot, so they never compete.\n *\n * What's left, and what this reports:\n * - a single tool colliding with **itself** (possible since bindings became\n * an array), which is ambiguous in whichever slot it occupies;\n * - two **ambient** tools, all of which are live simultaneously and are\n * ordered only by registration;\n * - two **hotkey-capable** tools, which can stack.\n *\n * Registered actions join the same two buckets: their `defaultBinding`s\n * assemble at ambient scope (hotkey scope when `Action.scope` says so), so an\n * ambient tool and an action claiming one tuple really do fall back on\n * declaration order.\n */\nexport function findScopedConflicts(scopes: ToolScopes): Conflict[] {\n const registry = Array.isArray(scopes.registry)\n ? (scopes.registry as readonly Tool<unknown>[])\n : Object.values(scopes.registry as Readonly<Record<string, Tool<unknown>>>);\n const actions = scopes.actions ?? [];\n const ambientActions = actions.filter((a) => a.scope !== 'hotkey').map(actionAsTool);\n const hotkeyActions = actions.filter((a) => a.scope === 'hotkey').map(actionAsTool);\n const ambient = [...(scopes.ambient ?? []), ...ambientActions];\n\n const out: Conflict[] = [];\n const seen = new Set<string>();\n const add = (conflicts: readonly Conflict[]): void => {\n for (const c of conflicts) {\n const key = `${c.phase}|${c.gesture}|${c.arg ?? ''}|${c.target ?? ''}`\n + `|${canonicalModifiers(c.modifiers)}|${c.toolIds.join(',')}`;\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(c);\n }\n };\n\n // Self-collisions: every tool, whichever slot it lands in.\n for (const tool of [...registry, ...(scopes.ambient ?? [])]) add(findConflicts([tool]));\n // Ambient tools and ambient-scope actions are all live together.\n if (ambient.length > 1) add(findConflicts(ambient));\n // Hotkey-capable tools can stack on each other. `hotkey` is declared on the\n // authored `ToolDef`, not carried onto the runtime `Tool` — `Tool.def` is\n // the reflection handle for exactly this kind of read, and it's typed\n // `unknown` so consumers cast at the use site.\n const hotkey = [\n ...registry.filter((t) => (t.def as { hotkey?: unknown } | undefined)?.hotkey !== undefined),\n ...hotkeyActions,\n ];\n if (hotkey.length > 1) add(findConflicts(hotkey));\n\n return out;\n}\n\n/**\n * Render a conflict as one line of human-readable text.\n *\n * The tuple is printed through {@link formatRoute}, so the message names the\n * collision in the same grammar the author wrote the binding in — modulo the\n * phase slot, which prints as a bare `'&'`-channel atom because the bucket key\n * collapses channel-bearing phase specs (`sel:engaged` and `&:engaged` collide\n * with each other, and the collapse is what made them collide).\n */\nexport function formatConflict(conflict: Conflict): string {\n const route = formatRoute({\n phases: [{ channel: '&', phase: conflict.phase === 'any' ? '*' : conflict.phase }],\n gesture: conflict.gesture,\n arg: conflict.arg,\n target: conflict.target,\n modifiers: conflict.modifiers,\n });\n return `${route} — declared by ${conflict.toolIds.join(', ')}`;\n}\n\n/**\n * Detect reachable route conflicts in an assembled tool set and report each one.\n *\n * This is the wiring `findConflicts` spent its first life without: the kit\n * could detect the one class of genuine routing ambiguity it has and never\n * looked. Call it once wherever a tool set is assembled (`useTools` does),\n * behind a `process.env.NODE_ENV !== 'production'` guard.\n *\n * **Warn, never throw.** A conflict between a consumer's tool and a kit tool\n * is a design question — sometimes deliberate, since the loser can still take\n * the gesture by declining through `enabled()` — and exploding in a running\n * app is the wrong way to raise it. A conflict between two *kit* tools is\n * always a bug, but the place to fail on that is the kit's own test suite\n * (`canvas/SceneCanvas.routeConflicts.test.tsx`), not a consumer's console.\n *\n * @returns The conflicts found, so callers can dedupe repeat reports.\n */\nexport function reportRouteConflicts(\n scopes: ToolScopes,\n warn: (message: string) => void = (m) => console.warn(m),\n): Conflict[] {\n const conflicts = findScopedConflicts(scopes);\n for (const c of conflicts) {\n warn(\n `[weasel] route conflict: two bindings declare the same (phase, gesture, arg, target, modifiers) tuple `\n + `in the same scope, so declaration order alone decides which one fires.\\n ${formatConflict(c)}`,\n );\n }\n return conflicts;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/units.ts","../src/core/geometry/path.ts","../src/features/paths/bounds.ts","../src/features/paths/flatten.ts","../src/features/paths/hitTest.ts","../src/features/paths/builder.ts","../src/features/paths/transformPath.ts","../src/features/paths/transform.ts","../src/interactions/actions/resize/geometry.ts","../src/features/paths/poseDescriptor.ts","../src/interactions/actions/resize/autoPoseDescriptor.ts","../src/interactions/gestures/shared/strategies/grid.ts","../src/core/viewport/pxExtent.ts","../src/interactions/gestures/shared/strategies/guides.ts"],"names":["ex","ey","COORD_COUNT"],"m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I,SAAA,KAAc,QAAA,IAAY,SAAA,KAAc,QAAA,EAAU,OAAO,IAAA;AAC7D,MAAA,MAAM,EAAA,GAAK,SAAA,KAAc,QAAA,GAAW,CAAA,GAAI,MAAA;AACxC,MAAA,MAAM,EAAA,GAAK,SAAA,KAAc,QAAA,GAAW,CAAA,GAAI,MAAA;AACxC,MAAA,IAAI,EAAA,KAAO,CAAA,IAAK,EAAA,KAAO,CAAA,EAAG,OAAO,IAAA;AACjC,MAAA,OAAO,IAAA,CAAK,SAAA,CAAU,IAAA,EAAM,EAAA,EAAI,EAAE,CAAA;AAAA,IACpC;AAAA,GACF;AACF","file":"chunk-U45SODC2.js","sourcesContent":["/**\n * Units — a tiny customizable unit system for canvas-kit APIs.\n *\n * The kit stores all coordinates as bare numbers in a single base unit\n * chosen by the consumer app. To make API call sites self-documenting,\n * the public surface accepts `UnitValue` — either a bare number (interpreted\n * as base units) or a `{ value, unit }` tag that's resolved against a\n * `UnitSystem` at the API boundary. Internals never see units.\n *\n * Linear factors only. No per-axis units. No mixed-unit arithmetic.\n */\n\n/** A unit name (e.g. `'in'`, `'ft'`, `'mm'`). Looked up in a `UnitSystem`. */\nexport type Unit = string;\n\n/** Conversion table mapping unit names to factors against a base unit. */\nexport interface UnitSystem {\n /** Name of the base unit, e.g. 'in'. All conversions resolve to this. */\n base: Unit;\n /** Factor to multiply a value in `unit` by to get base units. base unit's factor is 1. */\n units: Record<Unit, number>;\n}\n\n/** Value at a unit-aware API boundary: bare number (in base units) or `{ value, unit }` tag. */\nexport type UnitValue = number | { value: number; unit: Unit };\n\n/**\n * Resolve a UnitValue to a number in base units.\n * - bare number: returned as-is (assumed base)\n * - tagged: looks up factor; throws if unit not in unit system\n */\nexport function resolveUnit(v: UnitValue, unitSystem?: UnitSystem): number {\n if (typeof v === 'number') return v;\n if (!unitSystem) {\n throw new Error(\n `resolveUnit: tagged value { value: ${v.value}, unit: '${v.unit}' } requires a UnitSystem`,\n );\n }\n const factor = unitSystem.units[v.unit];\n if (factor === undefined) {\n const known = Object.keys(unitSystem.units).join(', ') || '(none)';\n throw new Error(\n `resolveUnit: unknown unit '${v.unit}' (system base: '${unitSystem.base}', known units: ${known})`,\n );\n }\n return v.value * factor;\n}\n\n/**\n * Format a base-unit number as a string in the named display unit.\n * e.g. formatUnit(36, 'ft', IMPERIAL_INCHES) => '3ft'\n * Default precision: 2. Trailing zeros trimmed.\n */\nexport function formatUnit(\n baseValue: number,\n displayUnit: Unit,\n unitSystem: UnitSystem,\n opts?: { precision?: number; suffix?: boolean },\n): string {\n const factor = unitSystem.units[displayUnit];\n if (factor === undefined) {\n const known = Object.keys(unitSystem.units).join(', ') || '(none)';\n throw new Error(\n `formatUnit: unknown unit '${displayUnit}' (system base: '${unitSystem.base}', known units: ${known})`,\n );\n }\n const precision = opts?.precision ?? 2;\n const suffix = opts?.suffix ?? true;\n const display = baseValue / factor;\n // Trim trailing zeros (and a dangling decimal point) without losing precision.\n let s = display.toFixed(precision);\n if (s.includes('.')) {\n s = s.replace(/0+$/, '').replace(/\\.$/, '');\n }\n return suffix ? `${s}${displayUnit}` : s;\n}\n\n/** Imperial unit system with base 'in'. */\nexport const IMPERIAL_INCHES: UnitSystem = {\n base: 'in',\n units: { in: 1, ft: 12, yd: 36, mi: 63360 },\n};\n\n/** Metric unit system with base 'mm'. */\nexport const METRIC_MM: UnitSystem = {\n base: 'mm',\n units: { mm: 1, cm: 10, m: 1000, km: 1_000_000 },\n};\n\n/** Pixel unit system — sole unit is the base. */\nexport const PIXELS: UnitSystem = {\n base: 'px',\n units: { px: 1 },\n};\n","/**\n * Path data model. Vector-graphics primitive used kit-wide as the canonical\n * shape (replacing per-shape ad-hoc poses). SVG-style command stream so we\n * cover lines, polygons, beziers, and multi-contour shapes (think the inner\n * hole of an \"O\") under one type.\n *\n * Storage: command codes in a `Uint8Array`, parameters in a `Float32Array`.\n * Each command consumes a fixed number of float coords from the parameter\n * array; the parser walks both arrays in lockstep. This keeps interaction\n * hot loops monomorphic and keeps GC pressure low under heavy edits.\n *\n * Two path subtypes are distinguished at the type level so common-case\n * machinery (selection AABBs, area-select intersection, hit-testing rect\n * silhouettes) can short-circuit on `RectPath` without paying the polygon\n * kernel cost. Polymorphic kernels accept either via the `Path` union and\n * dispatch on `kind`.\n */\n\n/** Command code: moveTo. */\nexport const PATH_M = 0;\n/** Command code: lineTo. */\nexport const PATH_L = 1;\n/** Command code: cubic bezier (`bezierCurveTo`). */\nexport const PATH_C = 2;\n/** Command code: quadratic bezier (`quadraticCurveTo`). */\nexport const PATH_Q = 3;\n/** Command code: close subpath. */\nexport const PATH_Z = 4;\n\n/** Float coords consumed by each command, indexed by command code. */\nexport const PATH_CMD_LENGTHS: readonly number[] = [2, 2, 6, 4, 0];\n\n/** Fill rule used by polygon path hit-testing and `ctx.fill()`. */\nexport type PathFillRule = 'nonzero' | 'evenodd';\n\n/**\n * Polygon path with arbitrary contours and optional bezier segments.\n * Multi-contour: each `M` opens a new subpath; `Z` closes the current one.\n * Open subpaths (no `Z`) render as polylines and don't contribute to fills.\n */\nexport interface PolygonPath {\n kind: 'polygon';\n commands: Uint8Array;\n coords: Float32Array;\n fillRule: PathFillRule;\n}\n\n/**\n * Axis-aligned rectangle. Fast path for the (very common) case where the\n * shape is just a rect — preserves O(1) bounds and hit-test, avoids the\n * polygon kernel entirely. Promote to `PolygonPath` only when the shape\n * grows beyond what a rect can express.\n */\nexport interface RectPath {\n kind: 'rect';\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** Canonical path shape — either an axis-aligned rect (fast path) or a polygon command stream. */\nexport type Path = PolygonPath | RectPath;\n","/**\n * AABB bounds of a `Path`. Returned as `RectPath` for direct reuse with the\n * rect fast path machinery (selection AABB, area-select intersection).\n *\n * `RectPath` is its own bounds — O(1). For `PolygonPath`, walk segment by\n * segment, computing the tight bound per segment:\n *\n * - `M` / `L`: just the endpoint.\n * - `Q`: quadratic Bezier — endpoints plus axis-aligned extrema (one\n * possible inflection per axis).\n * - `C`: cubic Bezier — endpoints plus axis-aligned extrema (up to two\n * possible inflections per axis, found via the quadratic formula on\n * the derivative).\n *\n * Control points are NOT included directly; they're used only to compute\n * extrema that actually lie on the curve. This avoids the classic \"AABB\n * extends past where the curve visibly reaches\" bug for curved paths whose\n * control points poke outside the visible extent.\n *\n * Empty paths (no commands) return a zero-size rect anchored at the\n * origin — the convention used elsewhere in the kit for missing geometry.\n */\n\nimport { cubicBounds, elevateQuadraticToCubic } from '@weasel-js/geom';\nimport {\n PATH_C,\n PATH_L,\n PATH_M,\n PATH_Q,\n PATH_Z,\n type Path,\n type RectPath,\n} from './types';\n\n/** AABB of a `Path`, returned as a `RectPath` for direct reuse with rect-fast-path machinery. */\nexport function boundsOfPath(path: Path): RectPath {\n if (path.kind === 'rect') return path;\n\n const { commands, coords } = path;\n if (commands.length === 0) {\n return { kind: 'rect', x: 0, y: 0, width: 0, height: 0 };\n }\n\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n let ci = 0;\n let seen = false;\n // Pen position carried across segments — needed because curves are\n // defined relative to the previous endpoint, which is itself the start\n // of the next segment but not re-encoded in `coords`.\n let px = 0, py = 0;\n\n const include = (x: number, y: number) => {\n if (x < minX) minX = x;\n if (x > maxX) maxX = x;\n if (y < minY) minY = y;\n if (y > maxY) maxY = y;\n seen = true;\n };\n\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i];\n switch (cmd) {\n case PATH_M:\n case PATH_L: {\n const x = coords[ci], y = coords[ci + 1];\n include(x, y);\n px = x; py = y;\n ci += 2;\n break;\n }\n case PATH_C: {\n const x1 = coords[ci], y1 = coords[ci + 1];\n const x2 = coords[ci + 2], y2 = coords[ci + 3];\n const x3 = coords[ci + 4], y3 = coords[ci + 5];\n const [bMinX, bMinY, bMaxX, bMaxY] = cubicBounds(px, py, x1, y1, x2, y2, x3, y3);\n include(bMinX, bMinY);\n include(bMaxX, bMaxY);\n px = x3; py = y3;\n ci += 6;\n break;\n }\n case PATH_Q: {\n const qx1 = coords[ci], qy1 = coords[ci + 1];\n const qx2 = coords[ci + 2], qy2 = coords[ci + 3];\n const [c1x, c1y, c2x, c2y] = elevateQuadraticToCubic(px, py, qx1, qy1, qx2, qy2);\n const [bMinX, bMinY, bMaxX, bMaxY] = cubicBounds(px, py, c1x, c1y, c2x, c2y, qx2, qy2);\n include(bMinX, bMinY);\n include(bMaxX, bMaxY);\n px = qx2; py = qy2;\n ci += 4;\n break;\n }\n case PATH_Z:\n break;\n default:\n throw new Error(`boundsOfPath: unknown command ${cmd}`);\n }\n }\n\n if (!seen) return { kind: 'rect', x: 0, y: 0, width: 0, height: 0 };\n return { kind: 'rect', x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n","/**\n * Bezier flattening — subdivide cubic and quadratic segments into polyline\n * approximations within a flatness tolerance. Used by hit-testing and\n * (eventually) any kernel that doesn't want to special-case curves.\n *\n * The flatness metric is the maximum perpendicular distance from any\n * control point to the chord between endpoints. When that distance falls\n * below `tolerance`, the segment is \"flat enough\" and emitted as a single\n * line segment.\n *\n * Tolerance is in world units. 0.5 is a sensible default for screen-rate\n * rendering at 1× zoom; consumers that zoom in heavily should pass a\n * tighter tolerance.\n */\n\nexport const DEFAULT_FLATTEN_TOLERANCE = 0.5;\n\n/** Distance from point P to line AB (perpendicular). */\nfunction distPointToLine(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) {\n const ex = px - ax;\n const ey = py - ay;\n return Math.sqrt(ex * ex + ey * ey);\n }\n const cross = (px - ax) * dy - (py - ay) * dx;\n return Math.abs(cross) / Math.sqrt(len2);\n}\n\n/**\n * Recursively subdivide a cubic bezier (P0..P3) and append `lineTo`-style\n * vertices to `out` (interleaved x,y). The starting endpoint is *not*\n * appended — callers usually emitted it as the segment's previous vertex.\n */\nexport function flattenCubic(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n x3: number, y3: number,\n tolerance: number,\n out: number[],\n): void {\n const d1 = distPointToLine(x1, y1, x0, y0, x3, y3);\n const d2 = distPointToLine(x2, y2, x0, y0, x3, y3);\n if (Math.max(d1, d2) <= tolerance) {\n out.push(x3, y3);\n return;\n }\n // De Casteljau split at t=0.5\n const x01 = (x0 + x1) * 0.5, y01 = (y0 + y1) * 0.5;\n const x12 = (x1 + x2) * 0.5, y12 = (y1 + y2) * 0.5;\n const x23 = (x2 + x3) * 0.5, y23 = (y2 + y3) * 0.5;\n const x012 = (x01 + x12) * 0.5, y012 = (y01 + y12) * 0.5;\n const x123 = (x12 + x23) * 0.5, y123 = (y12 + y23) * 0.5;\n const x0123 = (x012 + x123) * 0.5, y0123 = (y012 + y123) * 0.5;\n flattenCubic(x0, y0, x01, y01, x012, y012, x0123, y0123, tolerance, out);\n flattenCubic(x0123, y0123, x123, y123, x23, y23, x3, y3, tolerance, out);\n}\n\n/** Recursively subdivide a quadratic bezier (P0, P1, P2). */\nexport function flattenQuadratic(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n tolerance: number,\n out: number[],\n): void {\n const d = distPointToLine(x1, y1, x0, y0, x2, y2);\n if (d <= tolerance) {\n out.push(x2, y2);\n return;\n }\n const x01 = (x0 + x1) * 0.5, y01 = (y0 + y1) * 0.5;\n const x12 = (x1 + x2) * 0.5, y12 = (y1 + y2) * 0.5;\n const x012 = (x01 + x12) * 0.5, y012 = (y01 + y12) * 0.5;\n flattenQuadratic(x0, y0, x01, y01, x012, y012, tolerance, out);\n flattenQuadratic(x012, y012, x12, y12, x2, y2, tolerance, out);\n}\n\n/**\n * Like `flattenCubic` but also appends, for each new flattened point, its\n * arc-length fraction `t` (relative to the polyline distance accumulated so\n * far inside this curve) to `arcOut`. Caller then post-processes the segment's\n * `arcOut` range by dividing each by the segment's total flattened arc length\n * to yield t ∈ (0, 1].\n *\n * The returned values are *cumulative distance from the segment start*, not\n * normalized fractions. Two-pass design (accumulate, then divide) keeps the\n * recursive splitter simple — it doesn't need to know the total length up\n * front.\n */\nexport function flattenCubicWithArcLen(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n x3: number, y3: number,\n tolerance: number,\n out: number[],\n arcOut: number[],\n): number {\n return flattenCubicArcRec(x0, y0, x1, y1, x2, y2, x3, y3, tolerance, out, arcOut, 0);\n}\n\nfunction flattenCubicArcRec(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n x3: number, y3: number,\n tolerance: number,\n out: number[],\n arcOut: number[],\n accum: number,\n): number {\n const d1 = distPointToLine(x1, y1, x0, y0, x3, y3);\n const d2 = distPointToLine(x2, y2, x0, y0, x3, y3);\n if (Math.max(d1, d2) <= tolerance) {\n const lastX = out.length >= 2 ? out[out.length - 2] : x0;\n const lastY = out.length >= 2 ? out[out.length - 1] : y0;\n const seg = Math.hypot(x3 - lastX, y3 - lastY);\n accum += seg;\n out.push(x3, y3);\n arcOut.push(accum);\n return accum;\n }\n const x01 = (x0 + x1) * 0.5, y01 = (y0 + y1) * 0.5;\n const x12 = (x1 + x2) * 0.5, y12 = (y1 + y2) * 0.5;\n const x23 = (x2 + x3) * 0.5, y23 = (y2 + y3) * 0.5;\n const x012 = (x01 + x12) * 0.5, y012 = (y01 + y12) * 0.5;\n const x123 = (x12 + x23) * 0.5, y123 = (y12 + y23) * 0.5;\n const x0123 = (x012 + x123) * 0.5, y0123 = (y012 + y123) * 0.5;\n accum = flattenCubicArcRec(x0, y0, x01, y01, x012, y012, x0123, y0123, tolerance, out, arcOut, accum);\n accum = flattenCubicArcRec(x0123, y0123, x123, y123, x23, y23, x3, y3, tolerance, out, arcOut, accum);\n return accum;\n}\n\n/** Flatten a quadratic bezier into line segments within `tolerance`, appending\n * points to `out` and their cumulative arc lengths to `arcOut`. The arc\n * lengths are what lets per-anchor color and dash phase be interpolated\n * evenly along the curve rather than per segment. */\nexport function flattenQuadraticWithArcLen(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n tolerance: number,\n out: number[],\n arcOut: number[],\n): number {\n return flattenQuadraticArcRec(x0, y0, x1, y1, x2, y2, tolerance, out, arcOut, 0);\n}\n\nfunction flattenQuadraticArcRec(\n x0: number, y0: number,\n x1: number, y1: number,\n x2: number, y2: number,\n tolerance: number,\n out: number[],\n arcOut: number[],\n accum: number,\n): number {\n const d = distPointToLine(x1, y1, x0, y0, x2, y2);\n if (d <= tolerance) {\n const lastX = out.length >= 2 ? out[out.length - 2] : x0;\n const lastY = out.length >= 2 ? out[out.length - 1] : y0;\n const seg = Math.hypot(x2 - lastX, y2 - lastY);\n accum += seg;\n out.push(x2, y2);\n arcOut.push(accum);\n return accum;\n }\n const x01 = (x0 + x1) * 0.5, y01 = (y0 + y1) * 0.5;\n const x12 = (x1 + x2) * 0.5, y12 = (y1 + y2) * 0.5;\n const x012 = (x01 + x12) * 0.5, y012 = (y01 + y12) * 0.5;\n accum = flattenQuadraticArcRec(x0, y0, x01, y01, x012, y012, tolerance, out, arcOut, accum);\n accum = flattenQuadraticArcRec(x012, y012, x12, y12, x2, y2, tolerance, out, arcOut, accum);\n return accum;\n}\n\n","/**\n * Point-in-path hit-testing. `RectPath` short-circuits to AABB compare\n * (O(1)). `PolygonPath` walks the command stream, flattening any bezier\n * segments to line segments, then runs ray-casting (even-odd) or\n * winding-number (non-zero) per the path's `fillRule`.\n *\n * Open subpaths (no `Z`) are skipped for filled hit-testing — they have\n * no enclosed area. For open polylines (strokes), use `strokeHitTest`\n * which computes point-to-segment distance against the flattened\n * polyline and returns true within a configurable threshold.\n */\n\nimport { flattenCubic, flattenQuadratic, DEFAULT_FLATTEN_TOLERANCE } from './flatten';\nimport {\n PATH_C,\n PATH_L,\n PATH_M,\n PATH_Q,\n PATH_Z,\n type Path,\n type PolygonPath,\n} from './types';\n\n/** Options for `pointInPath`. */\nexport interface PointInPathOptions {\n /** Bezier flattening tolerance in world units. Default 0.5. */\n tolerance?: number;\n}\n\n/** Filled-region hit-test for a `Path`. Rect short-circuits to AABB; polygons run ray-cast / winding per `fillRule`. */\nexport function pointInPath(\n path: Path,\n x: number,\n y: number,\n opts: PointInPathOptions = {},\n): boolean {\n if (path.kind === 'rect') {\n return x >= path.x && x <= path.x + path.width && y >= path.y && y <= path.y + path.height;\n }\n return pointInPolygonPath(path, x, y, opts.tolerance ?? DEFAULT_FLATTEN_TOLERANCE);\n}\n\nfunction pointInPolygonPath(path: PolygonPath, x: number, y: number, tolerance: number): boolean {\n const { commands, coords, fillRule } = path;\n if (commands.length === 0) return false;\n\n // Walk the command stream; flatten beziers into per-subpath vertex arrays.\n // For each closed subpath, accumulate winding/crossings against (x, y).\n let crossings = 0;\n let winding = 0;\n\n let subStartX = 0, subStartY = 0;\n let curX = 0, curY = 0;\n let subVerts: number[] = []; // flat [x, y, x, y, ...] for current subpath\n let subOpen = false;\n\n const flushSubpath = (closed: boolean) => {\n if (closed && subVerts.length >= 4) {\n // Close the subpath back to its start.\n subVerts.push(subStartX, subStartY);\n // Now subVerts is a closed polyline; tally crossings/winding.\n for (let i = 0; i < subVerts.length - 2; i += 2) {\n const ax = subVerts[i], ay = subVerts[i + 1];\n const bx = subVerts[i + 2], by = subVerts[i + 3];\n if (segmentCrossesRayRight(x, y, ax, ay, bx, by)) {\n crossings++;\n if (ay <= y && by > y) winding++;\n else if (by <= y && ay > y) winding--;\n }\n }\n }\n subVerts = [];\n subOpen = false;\n };\n\n let ci = 0;\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i];\n switch (cmd) {\n case PATH_M: {\n if (subOpen) flushSubpath(false);\n subStartX = coords[ci]; subStartY = coords[ci + 1];\n curX = subStartX; curY = subStartY;\n subVerts.push(curX, curY);\n subOpen = true;\n ci += 2;\n break;\n }\n case PATH_L: {\n curX = coords[ci]; curY = coords[ci + 1];\n subVerts.push(curX, curY);\n ci += 2;\n break;\n }\n case PATH_C: {\n const x1 = coords[ci], y1 = coords[ci + 1];\n const x2 = coords[ci + 2], y2 = coords[ci + 3];\n const x3 = coords[ci + 4], y3 = coords[ci + 5];\n flattenCubic(curX, curY, x1, y1, x2, y2, x3, y3, tolerance, subVerts);\n curX = x3; curY = y3;\n ci += 6;\n break;\n }\n case PATH_Q: {\n const x1 = coords[ci], y1 = coords[ci + 1];\n const x2 = coords[ci + 2], y2 = coords[ci + 3];\n flattenQuadratic(curX, curY, x1, y1, x2, y2, tolerance, subVerts);\n curX = x2; curY = y2;\n ci += 4;\n break;\n }\n case PATH_Z: {\n flushSubpath(true);\n curX = subStartX; curY = subStartY;\n break;\n }\n default:\n throw new Error(`pointInPath: unknown command ${cmd}`);\n }\n }\n if (subOpen) flushSubpath(false);\n\n return fillRule === 'evenodd' ? (crossings & 1) === 1 : winding !== 0;\n}\n\n/**\n * Does the rightward horizontal ray from (x, y) cross segment (ax,ay)→(bx,by)?\n * Standard half-open rule (segments touching from above count, from below\n * don't) — avoids double-counting at shared vertices.\n */\nfunction segmentCrossesRayRight(\n x: number, y: number,\n ax: number, ay: number,\n bx: number, by: number,\n): boolean {\n if ((ay > y) === (by > y)) return false;\n const xCross = ax + ((y - ay) / (by - ay)) * (bx - ax);\n return x < xCross;\n}\n\n/** Options for {@link strokeHitTest}. */\nexport interface StrokeHitTestOptions {\n /** Bezier flattening tolerance in world units. Default 0.5. */\n tolerance?: number;\n}\n\n/**\n * Stroke-distance hit-test. Returns true when (x, y) lies within\n * `threshold` world units of the path's outline — i.e. when a stroke\n * of total width `2 * threshold` drawn along the path would cover the\n * point.\n *\n * Works for both closed and open subpaths — unlike {@link pointInPath},\n * which only tests filled regions. Use this for picking on open\n * polylines / curves and for adding stroke-clickability to closed\n * shapes (logical OR with `pointInPath` when both behaviors are\n * desired).\n *\n * `threshold` is typically the stroke's half-width plus a small slop\n * (e.g. `strokeWidth / 2 + 4`). Cap segments are approximated by the\n * threshold radius around each anchor — the test treats every flattened\n * segment as a capsule of width `2 * threshold`.\n */\nexport function strokeHitTest(\n path: Path,\n x: number,\n y: number,\n threshold: number,\n opts: StrokeHitTestOptions = {},\n): boolean {\n const t2 = threshold * threshold;\n if (path.kind === 'rect') {\n const { x: rx, y: ry, width: w, height: h } = path;\n return (\n pointSegmentDist2(x, y, rx, ry, rx + w, ry) <= t2\n || pointSegmentDist2(x, y, rx + w, ry, rx + w, ry + h) <= t2\n || pointSegmentDist2(x, y, rx + w, ry + h, rx, ry + h) <= t2\n || pointSegmentDist2(x, y, rx, ry + h, rx, ry) <= t2\n );\n }\n return polylineWithinThreshold(path, x, y, t2, opts.tolerance ?? DEFAULT_FLATTEN_TOLERANCE);\n}\n\nfunction polylineWithinThreshold(\n path: PolygonPath,\n px: number, py: number,\n t2: number,\n tolerance: number,\n): boolean {\n const { commands, coords } = path;\n if (commands.length === 0) return false;\n\n // Reuse pointInPath's command-stream + flatten walk; check distance from\n // (px, py) to each emitted segment instead of accumulating crossings.\n let subStartX = 0, subStartY = 0;\n let curX = 0, curY = 0;\n let subVerts: number[] = [];\n let subOpen = false;\n\n const checkSegments = (closed: boolean): boolean => {\n if (closed && subVerts.length >= 4) subVerts.push(subStartX, subStartY);\n for (let i = 0; i < subVerts.length - 2; i += 2) {\n if (pointSegmentDist2(px, py, subVerts[i], subVerts[i + 1], subVerts[i + 2], subVerts[i + 3]) <= t2) {\n return true;\n }\n }\n return false;\n };\n\n let ci = 0;\n for (let i = 0; i < commands.length; i++) {\n const cmd = commands[i];\n switch (cmd) {\n case PATH_M: {\n if (subOpen) {\n if (checkSegments(false)) return true;\n subVerts = [];\n }\n subStartX = coords[ci]; subStartY = coords[ci + 1];\n curX = subStartX; curY = subStartY;\n subVerts.push(curX, curY);\n subOpen = true;\n ci += 2;\n break;\n }\n case PATH_L: {\n curX = coords[ci]; curY = coords[ci + 1];\n subVerts.push(curX, curY);\n ci += 2;\n break;\n }\n case PATH_C: {\n const x1 = coords[ci], y1 = coords[ci + 1];\n const x2 = coords[ci + 2], y2 = coords[ci + 3];\n const x3 = coords[ci + 4], y3 = coords[ci + 5];\n flattenCubic(curX, curY, x1, y1, x2, y2, x3, y3, tolerance, subVerts);\n curX = x3; curY = y3;\n ci += 6;\n break;\n }\n case PATH_Q: {\n const x1 = coords[ci], y1 = coords[ci + 1];\n const x2 = coords[ci + 2], y2 = coords[ci + 3];\n flattenQuadratic(curX, curY, x1, y1, x2, y2, tolerance, subVerts);\n curX = x2; curY = y2;\n ci += 4;\n break;\n }\n case PATH_Z: {\n if (checkSegments(true)) return true;\n subVerts = [];\n subOpen = false;\n curX = subStartX; curY = subStartY;\n break;\n }\n default:\n throw new Error(`strokeHitTest: unknown command ${cmd}`);\n }\n }\n if (subOpen && checkSegments(false)) return true;\n return false;\n}\n\n/** Squared distance from (px, py) to the closest point on segment (ax,ay)→(bx,by). */\nfunction pointSegmentDist2(\n px: number, py: number,\n ax: number, ay: number,\n bx: number, by: number,\n): number {\n const dx = bx - ax;\n const dy = by - ay;\n const len2 = dx * dx + dy * dy;\n if (len2 === 0) {\n const ex = px - ax, ey = py - ay;\n return ex * ex + ey * ey;\n }\n let t = ((px - ax) * dx + (py - ay) * dy) / len2;\n if (t < 0) t = 0; else if (t > 1) t = 1;\n const cx = ax + t * dx;\n const cy = ay + t * dy;\n const ex = px - cx, ey = py - cy;\n return ex * ex + ey * ey;\n}\n","/**\n * Fluent builder for `PolygonPath`. Hides the `Uint8Array` / `Float32Array`\n * encoding behind move/line/curve/close calls and a final `build()`. Use\n * this to construct paths in tests and demos; production callers that need\n * to mutate large paths in place should reach for the raw arrays directly.\n *\n * Numeric capacity grows by doubling — typical for amortized O(1) push.\n *\n * Also exposes `rectPath` / `polygonFromPoints` shortcuts for the common\n * cases. `rectPath` returns the lighter `RectPath` subtype, not a polygon.\n */\n\nimport {\n PATH_C,\n PATH_L,\n PATH_M,\n PATH_Q,\n PATH_Z,\n type PathFillRule,\n type PolygonPath,\n type RectPath,\n} from './types';\n\n/** Fluent builder for `PolygonPath`; hides the `Uint8Array`/`Float32Array` encoding behind move/line/curve/close calls. */\nexport class PathBuilder {\n private cmds: number[] = [];\n private xs: number[] = [];\n private fillRule: PathFillRule = 'nonzero';\n\n /** Seed a builder with an existing `PolygonPath`. Useful for extending\n * an in-flight path with another segment (e.g. appending a cubic to\n * the end of a curve in response to a user action) without hand-\n * reaching into the `commands` / `coords` typed arrays.\n *\n * ```ts\n * const next = PathBuilder.fromPath(current).curveTo(...).build();\n * ```\n */\n static fromPath(path: PolygonPath): PathBuilder {\n const b = new PathBuilder();\n b.cmds = Array.from(path.commands);\n b.xs = Array.from(path.coords);\n b.fillRule = path.fillRule;\n return b;\n }\n\n setFillRule(rule: PathFillRule): this {\n this.fillRule = rule;\n return this;\n }\n\n moveTo(x: number, y: number): this {\n this.cmds.push(PATH_M);\n this.xs.push(x, y);\n return this;\n }\n\n lineTo(x: number, y: number): this {\n this.cmds.push(PATH_L);\n this.xs.push(x, y);\n return this;\n }\n\n /** Cubic bezier to (x, y) with control points (x1, y1) and (x2, y2). */\n curveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): this {\n this.cmds.push(PATH_C);\n this.xs.push(x1, y1, x2, y2, x, y);\n return this;\n }\n\n /** Quadratic bezier to (x, y) with control point (x1, y1). */\n quadTo(x1: number, y1: number, x: number, y: number): this {\n this.cmds.push(PATH_Q);\n this.xs.push(x1, y1, x, y);\n return this;\n }\n\n close(): this {\n this.cmds.push(PATH_Z);\n return this;\n }\n\n build(): PolygonPath {\n return {\n kind: 'polygon',\n commands: new Uint8Array(this.cmds),\n coords: new Float32Array(this.xs),\n fillRule: this.fillRule,\n };\n }\n}\n\n/** Construct a `RectPath` (the fast-path subtype). */\nexport function rectPath(x: number, y: number, width: number, height: number): RectPath {\n return { kind: 'rect', x, y, width, height };\n}\n\n/** Build a closed polygon from a flat list of points. */\nexport function polygonFromPoints(\n points: readonly { x: number; y: number }[],\n opts: { fillRule?: PathFillRule } = {},\n): PolygonPath {\n if (points.length === 0) {\n return {\n kind: 'polygon',\n commands: new Uint8Array(),\n coords: new Float32Array(),\n fillRule: opts.fillRule ?? 'nonzero',\n };\n }\n const b = new PathBuilder();\n if (opts.fillRule) b.setFillRule(opts.fillRule);\n b.moveTo(points[0].x, points[0].y);\n for (let i = 1; i < points.length; i++) b.lineTo(points[i].x, points[i].y);\n b.close();\n return b.build();\n}\n\n/** Cubic-Bezier kappa for circular-quadrant approximation (<1% max error). */\nconst ELLIPSE_KAPPA = 0.5522847498307936;\n\n/** Closed ellipse inscribed in `bounds`, as a 4-cubic-Bezier `PolygonPath`.\n * Matches the geometry `useEllipseTool`'s overlay paints. */\nexport function ellipsePath(\n bounds: { x: number; y: number; width: number; height: number },\n): PolygonPath {\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n const rx = bounds.width / 2;\n const ry = bounds.height / 2;\n const ox = rx * ELLIPSE_KAPPA;\n const oy = ry * ELLIPSE_KAPPA;\n const b = new PathBuilder();\n b.moveTo(cx + rx, cy);\n b.curveTo(cx + rx, cy + oy, cx + ox, cy + ry, cx, cy + ry);\n b.curveTo(cx - ox, cy + ry, cx - rx, cy + oy, cx - rx, cy);\n b.curveTo(cx - rx, cy - oy, cx - ox, cy - ry, cx, cy - ry);\n b.curveTo(cx + ox, cy - ry, cx + rx, cy - oy, cx + rx, cy);\n b.close();\n return b.build();\n}\n\n/** Closed regular n-gon centered at `center`, circumscribed by `radius`.\n * `rotation` is in radians; default 0 puts the first vertex on the +x axis. */\nexport function regularPolygonPath(\n center: { x: number; y: number },\n radius: number,\n sides: number,\n rotation = 0,\n): PolygonPath {\n const b = new PathBuilder();\n for (let i = 0; i < sides; i++) {\n const a = rotation + (i / sides) * Math.PI * 2;\n const x = center.x + radius * Math.cos(a);\n const y = center.y + radius * Math.sin(a);\n if (i === 0) b.moveTo(x, y); else b.lineTo(x, y);\n }\n b.close();\n return b.build();\n}\n\n/** Closed n-pointed star centered at `center`, alternating `outerRadius` and\n * `innerRadius` (default `outerRadius / 2`). `rotation` is in radians. */\nexport function starPath(\n center: { x: number; y: number },\n outerRadius: number,\n points = 5,\n innerRadius: number = outerRadius / 2,\n rotation = 0,\n): PolygonPath {\n const b = new PathBuilder();\n const n = points * 2;\n for (let i = 0; i < n; i++) {\n const a = rotation + (i / n) * Math.PI * 2;\n const r = i % 2 === 0 ? outerRadius : innerRadius;\n const x = center.x + r * Math.cos(a);\n const y = center.y + r * Math.sin(a);\n if (i === 0) b.moveTo(x, y); else b.lineTo(x, y);\n }\n b.close();\n return b.build();\n}\n\n/** Open 2-vertex polyline from `a` to `b` — strokeable, not fillable. */\nexport function linePath(\n a: { x: number; y: number },\n b: { x: number; y: number },\n): PolygonPath {\n const pb = new PathBuilder();\n pb.moveTo(a.x, a.y);\n pb.lineTo(b.x, b.y);\n return pb.build();\n}\n","import { type Mat3, transformCoords } from '@weasel-js/geom';\nimport { PathBuilder } from './builder';\nimport { type Path, type PolygonPath } from './types';\n\n/** Apply an affine `Mat3` to a path's geometry.\n *\n * Axis-aligned maps (no rotation/shear, i.e. `m[1] === 0 && m[2] === 0`) keep a\n * `RectPath` a rect — the four corners stay axis-aligned, so we transform the\n * two diagonal corners and normalize negative extent (mirror). Rotation or\n * shear promotes the rect's four corners to a `PolygonPath`. Polygon paths map\n * every coord via the kernel's `transformCoords`, preserving the command stream\n * and `fillRule`. Never mutates the input.\n *\n * `Mat3` here is the 6-tuple `number[]` from `@weasel-js/geom` (DOMMatrix order:\n * `[a, b, c, d, e, f]` where `x' = a·x + c·y + e`, `y' = b·x + d·y + f`),\n * not the renderer's 9-element `Float32Array`. */\nexport function transformPath(path: Path, m: Mat3): Path {\n const [a, b, c, d, e, f] = m;\n if (path.kind === 'rect') {\n if (b === 0 && c === 0) {\n // Pure scale + translate — corners remain axis-aligned.\n const x0 = a * path.x + e;\n const y0 = d * path.y + f;\n const x1 = a * (path.x + path.width) + e;\n const y1 = d * (path.y + path.height) + f;\n return {\n kind: 'rect',\n x: Math.min(x0, x1),\n y: Math.min(y0, y1),\n width: Math.abs(x1 - x0),\n height: Math.abs(y1 - y0),\n };\n }\n // Rotation / shear — promote to polygon with the four rect corners.\n const poly = new PathBuilder()\n .moveTo(path.x, path.y)\n .lineTo(path.x + path.width, path.y)\n .lineTo(path.x + path.width, path.y + path.height)\n .lineTo(path.x, path.y + path.height)\n .close()\n .build();\n return transformPolygon(poly, m);\n }\n return transformPolygon(path, m);\n}\n\nfunction transformPolygon(path: PolygonPath, m: Mat3): PolygonPath {\n // transformCoords returns Float64Array; PolygonPath.coords is Float32Array.\n const mapped = transformCoords(path.coords, m);\n return { ...path, coords: Float32Array.from(mapped) };\n}\n","/**\n * In-place and copy-out path transforms. Translation is the most common —\n * called every pointermove during a drag — so the polygon variant mutates\n * the float buffer directly to keep allocation pressure off the GC.\n *\n * `scalePathToBounds` is for the resize interaction: given the path's\n * current AABB and the desired new AABB, scales every coordinate\n * proportionally. Degenerate source bounds (zero width/height) collapse\n * the corresponding axis to the new origin — preferable to dividing by\n * zero or refusing to resize.\n */\n\nimport { boxToBox } from '@weasel-js/geom';\nimport { boundsOfPath } from './bounds';\nimport { transformPath } from './transformPath';\nimport { PATH_C, PATH_L, PATH_M, PATH_Q, PATH_Z, type Path, type PolygonPath, type RectPath } from './types';\n\n/**\n * Translate a path by (dx, dy). Returns a new instance — the kit's pose\n * model treats poses as immutable to keep React state-update semantics\n * predictable. Polygon coords are copied into a fresh `Float32Array`.\n */\nexport function translatePath(path: Path, dx: number, dy: number): Path {\n if (path.kind === 'rect') {\n return { kind: 'rect', x: path.x + dx, y: path.y + dy, width: path.width, height: path.height };\n }\n return translatePolygonCopy(path, dx, dy);\n}\n\nfunction translatePolygonCopy(path: PolygonPath, dx: number, dy: number): PolygonPath {\n const next = new Float32Array(path.coords.length);\n const { commands, coords } = path;\n let ci = 0;\n for (let i = 0; i < commands.length; i++) {\n const len = COORD_COUNT[commands[i]];\n for (let k = 0; k < len; k += 2) {\n next[ci + k] = coords[ci + k] + dx;\n next[ci + k + 1] = coords[ci + k + 1] + dy;\n }\n ci += len;\n }\n return { kind: 'polygon', commands: path.commands, coords: next, fillRule: path.fillRule };\n}\n\n/**\n * Translate a polygon path's coords *in place*. Returns the same\n * `PolygonPath` reference. Use only for transient overlay buffers — never\n * for committed scene state, which must remain immutable for React.\n */\nexport function translatePolygonInPlace(path: PolygonPath, dx: number, dy: number): PolygonPath {\n const { commands, coords } = path;\n let ci = 0;\n for (let i = 0; i < commands.length; i++) {\n const len = COORD_COUNT[commands[i]];\n for (let k = 0; k < len; k += 2) {\n coords[ci + k] += dx;\n coords[ci + k + 1] += dy;\n }\n ci += len;\n }\n return path;\n}\n\n/**\n * Scale a path's coords so its current AABB maps to `target`. Resize\n * interactions use this to make a polygon follow a corner-handle drag.\n *\n * Degenerate source axes (width or height == 0) collapse to `target.x` /\n * `target.y` — every coord on that axis becomes the new origin. Avoids\n * division by zero without throwing.\n */\nexport function scalePathToBounds(path: Path, target: RectPath): Path {\n if (path.kind === 'rect') {\n return { kind: 'rect', x: target.x, y: target.y, width: target.width, height: target.height };\n }\n const src = boundsOfPath(path);\n return scalePolygon(path, src, target);\n}\n\nfunction scalePolygon(path: PolygonPath, src: RectPath, dst: RectPath): PolygonPath {\n const m = boxToBox(src.x, src.y, src.width, src.height, dst.x, dst.y, dst.width, dst.height);\n // src/dst are axis-aligned, so the polygon stays a polygon after this pure scale+translate.\n return transformPath(path, m) as PolygonPath;\n}\n\nconst COORD_COUNT: Readonly<Record<number, number>> = {\n [PATH_M]: 2,\n [PATH_L]: 2,\n [PATH_C]: 6,\n [PATH_Q]: 4,\n [PATH_Z]: 0,\n};\n","import type { ResizePose, RotatedPose } from '../../gestures/types';\n\n/**\n * Bridges arbitrary `TPose` shapes into the resize hook's bounds-driven math.\n * The hook reads bounds via `getBounds`, runs anchor-relative math on those\n * bounds, then asks `remapBounds` to project the result back into TPose.\n *\n * `remapBounds(pose, src, dst)` is a single operation that subsumes both\n * \"set my own AABB to dst\" (single-leaf resize) and \"scale me as a leaf\n * inside parent's src→dst rect\" (group resize) — they're the same affine\n * map. For rect-shaped poses the default geometry interprets the pose as\n * its own bounds; for Path or polygon poses the consumer supplies a\n * projection that knows how to read and rewrite the underlying geometry.\n */\nexport interface PoseProjection<TPose> {\n getBounds(pose: TPose): ResizePose;\n remapBounds(pose: TPose, src: ResizePose, dst: ResizePose): TPose;\n /** Translate the pose by (dx, dy). Optional — when omitted, callers fall\n * back to a translation derived from `remapBounds` (origin shifted, no\n * scale). Path-shaped poses should provide this for performance. */\n translate?(pose: TPose, dx: number, dy: number): TPose;\n /** True iff any portion of the pose's geometry intersects `rect`. Optional\n * — when omitted, area-select and similar callers test against `getBounds`\n * AABB (looser, but correct for axis-aligned rect poses). */\n intersectsRect?(pose: TPose, rect: ResizePose): boolean;\n /** Interpolate between two poses. Optional — animation helpers fall back to\n * rect-shape lerp when omitted (which fails for non-rect poses). */\n lerp?(a: TPose, b: TPose, t: number): TPose;\n /** Read the pose's rotation in radians. Pivot is the AABB center\n * (`getBounds(pose)` center). Default 0 when omitted — descriptor\n * declares \"this pose has no rotation.\" When supplied and non-zero,\n * `useResize` projects the drag delta into the leaf's local frame,\n * runs anchor math there, and translates the resulting pose so the\n * diagonally opposite world-space corner is pinned. */\n getRotation?(pose: TPose): number;\n /** True iff this pose shape can carry a rotation. Consulted by the\n * rotation affordance to decide whether to render the rotate cursor /\n * drag-band over a selection. When omitted, the kit assumes `true` for\n * back-compat — descriptors whose poses lack `x/y/width/height/rotation`\n * fields (e.g. polygon Paths) should return `false` so the affordance\n * hides instead of exposing a non-functional rotate cursor. */\n supportsRotation?(pose: TPose): boolean;\n}\n\n/** AABB-vs-AABB overlap. Exported for callers building a default\n * `intersectsRect` from `getBounds`. */\nexport function aabbIntersectsRect(b: ResizePose, r: ResizePose): boolean {\n return b.x < r.x + r.width && b.x + b.width > r.x && b.y < r.y + r.height && b.y + b.height > r.y;\n}\n\n/** Identity geometry for `TPose extends ResizePose`. Treats the pose as its\n * own bounds and remaps via affine scale against `src`/`dst`. */\nexport const RECT_POSE_DESCRIPTOR: PoseProjection<ResizePose> = {\n getBounds: (p) => p,\n remapBounds: (p, src, dst) => {\n const sx = src.width === 0 ? 1 : dst.width / src.width;\n const sy = src.height === 0 ? 1 : dst.height / src.height;\n return {\n ...p,\n x: dst.x + (p.x - src.x) * sx,\n y: dst.y + (p.y - src.y) * sy,\n width: p.width * sx,\n height: p.height * sy,\n };\n },\n translate: (p, dx, dy) => ({ ...p, x: p.x + dx, y: p.y + dy }),\n intersectsRect: (p, r) => aabbIntersectsRect(p, r),\n lerp: (a, b, t) => ({\n ...a,\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n width: a.width + (b.width - a.width) * t,\n height: a.height + (b.height - a.height) * t,\n }),\n};\n\n/** Identity geometry for `RotatedPose`. Inherits rect-shape projection\n * from `RECT_POSE_DESCRIPTOR` (the `RotatedPose extends ResizePose`\n * subtype lets the rect descriptor's methods apply directly; `remapBounds`\n * preserves the `rotation` field via `...p` spread). Adds `getRotation` so\n * `useResize` knows to take the rotation-aware math path. */\nexport const ROTATED_POSE_DESCRIPTOR: PoseProjection<RotatedPose> = {\n getBounds: RECT_POSE_DESCRIPTOR.getBounds as PoseProjection<RotatedPose>['getBounds'],\n remapBounds: RECT_POSE_DESCRIPTOR.remapBounds as PoseProjection<RotatedPose>['remapBounds'],\n translate: RECT_POSE_DESCRIPTOR.translate as PoseProjection<RotatedPose>['translate'],\n intersectsRect: RECT_POSE_DESCRIPTOR.intersectsRect as PoseProjection<RotatedPose>['intersectsRect'],\n lerp: RECT_POSE_DESCRIPTOR.lerp as PoseProjection<RotatedPose>['lerp'],\n getRotation: (p) => p.rotation,\n};\n\n/**\n * Remap a **rotated** leaf inside a group resize.\n *\n * The naive `remapBounds` scales a leaf's axis-aligned `width`/`height` by the\n * group's per-axis factors and carries `rotation` through untouched. That is\n * right when `src`/`dst` are already expressed in the leaf's own frame — the\n * single-leaf resize path, where the drag delta was projected into that frame\n * before the anchor math ran. In a group resize they are world-frame, so the\n * leaf's local axes do not line up with the axes being scaled: at 90° a\n * horizontal stretch should grow the leaf's `height`, and the naive map grows\n * its `width`.\n *\n * What this computes is the group affine applied to the leaf's local frame,\n * with the shear dropped — the pose model is `{x, y, width, height, rotation}`\n * and cannot represent the parallelogram a non-uniform scale of a rotated box\n * actually produces. The centre moves exactly; each local axis takes the\n * length of its own image; the rotation follows the image of the local x-axis.\n *\n * Degenerates to the naive map at `rotation === 0`, and to a plain uniform\n * scale when `sx === sy`, both exactly.\n */\nexport function remapRotatedLeaf<TPose extends RotatedPose>(\n pose: TPose,\n src: ResizePose,\n dst: ResizePose,\n): TPose {\n const sx = src.width === 0 ? 1 : dst.width / src.width;\n const sy = src.height === 0 ? 1 : dst.height / src.height;\n const theta = pose.rotation ?? 0;\n const cos = Math.cos(theta);\n const sin = Math.sin(theta);\n\n // Images of the leaf's local unit axes under the group's diagonal scale.\n const ux = sx * cos, uy = sy * sin;\n const vx = -sx * sin, vy = sy * cos;\n\n const width = pose.width * Math.hypot(ux, uy);\n const height = pose.height * Math.hypot(vx, vy);\n const rotation = Math.atan2(uy, ux);\n\n // The centre is a point, so it takes the group affine directly.\n const cxNew = dst.x + (pose.x + pose.width / 2 - src.x) * sx;\n const cyNew = dst.y + (pose.y + pose.height / 2 - src.y) * sy;\n\n return {\n ...pose,\n x: cxNew - width / 2,\n y: cyNew - height / 2,\n width,\n height,\n rotation,\n };\n}\n","import { boundsOfPath } from './bounds';\nimport { pointInPath } from './hitTest';\nimport { translatePath } from './transform';\nimport { PATH_C, PATH_L, PATH_M, PATH_Q, PATH_Z, type Path, type PolygonPath } from './types';\nimport { aabbIntersectsRect, type PoseProjection } from 'interactions/actions/resize/geometry';\nimport type { ResizePose } from 'interactions/gestures/types';\n\n/**\n * `PoseProjection` for `Path` poses — wires `useResize` to operate\n * on `Path` directly. `getBounds` defers to the same `boundsOfPath` kernel\n * the rest of the kit uses; `remapBounds` does an affine scale of every\n * coord against `src`/`dst`. Degenerate axes (zero src extent) collapse to\n * the new origin so resize from a flat edge doesn't produce NaN.\n *\n * Mirrors `scalePathToBounds` but takes `src` explicitly: the resize hook\n * knows the group's origin AABB and uses it for every leaf, instead of\n * each leaf scaling against its own AABB (which would ignore group context).\n */\nexport const pathPoseDescriptor: PoseProjection<Path> = {\n getBounds: (path) => boundsOfPath(path),\n remapBounds: (path, src, dst) => {\n const sx = src.width === 0 ? 0 : dst.width / src.width;\n const sy = src.height === 0 ? 0 : dst.height / src.height;\n if (path.kind === 'rect') {\n return {\n kind: 'rect',\n x: dst.x + (path.x - src.x) * sx,\n y: dst.y + (path.y - src.y) * sy,\n width: path.width * sx,\n height: path.height * sy,\n };\n }\n return remapPolygon(path, src, dst, sx, sy);\n },\n translate: (path, dx, dy) => translatePath(path, dx, dy),\n // WHY: AABB pre-test is cheap; only fall through to per-corner pointInPath\n // when the rect is fully inside the AABB (silhouette test).\n intersectsRect: (path, rect) => {\n const b = boundsOfPath(path);\n if (!aabbIntersectsRect(b, rect)) return false;\n if (path.kind === 'rect') return true;\n // Sample the rect's four corners; any inside the polygon ⇒ overlap.\n if (\n pointInPath(path, rect.x, rect.y) ||\n pointInPath(path, rect.x + rect.width, rect.y) ||\n pointInPath(path, rect.x, rect.y + rect.height) ||\n pointInPath(path, rect.x + rect.width, rect.y + rect.height)\n ) return true;\n // Conservative fallback: AABB overlap counts. Tighter edge-vs-edge test\n // would be the next step; defer until a demo demands it.\n return true;\n },\n lerp: (a, b, t) => {\n if (a.kind === 'rect' && b.kind === 'rect') {\n return {\n kind: 'rect',\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n width: a.width + (b.width - a.width) * t,\n height: a.height + (b.height - a.height) * t,\n };\n }\n if (a.kind === 'polygon' && b.kind === 'polygon' && a.coords.length === b.coords.length) {\n const next = new Float32Array(a.coords.length);\n for (let i = 0; i < a.coords.length; i++) {\n next[i] = a.coords[i] + (b.coords[i] - a.coords[i]) * t;\n }\n return { kind: 'polygon', commands: a.commands, coords: next, fillRule: a.fillRule };\n }\n throw new Error('pathPoseDescriptor.lerp: incompatible path shapes');\n },\n // Path poses carry no x/y/width/height/rotation fields — the kit's\n // `wrapWithPoseRotation` helper has nothing to bind a rotation to, and\n // `remapBounds` would drop a synthetic rotation field on every commit.\n // Returning false here hides the rotation affordance for Path consumers\n // so the rotate cursor doesn't appear without a working interaction.\n supportsRotation: () => false,\n};\n\nfunction remapPolygon(path: PolygonPath, src: ResizePose, dst: ResizePose, sx: number, sy: number): PolygonPath {\n const next = new Float32Array(path.coords.length);\n const { commands, coords } = path;\n let ci = 0;\n for (let i = 0; i < commands.length; i++) {\n const len = COORD_COUNT[commands[i]];\n for (let k = 0; k < len; k += 2) {\n next[ci + k] = dst.x + (coords[ci + k] - src.x) * sx;\n next[ci + k + 1] = dst.y + (coords[ci + k + 1] - src.y) * sy;\n }\n ci += len;\n }\n return { kind: 'polygon', commands: path.commands, coords: next, fillRule: path.fillRule };\n}\n\nconst COORD_COUNT: Readonly<Record<number, number>> = {\n [PATH_M]: 2,\n [PATH_L]: 2,\n [PATH_C]: 6,\n [PATH_Q]: 4,\n [PATH_Z]: 0,\n};\n","import type { Path } from 'features/paths/types';\nimport { pathPoseDescriptor } from 'features/paths/poseDescriptor';\nimport { RECT_POSE_DESCRIPTOR, type PoseProjection } from './geometry';\n\n/** True for Path-shaped poses (`{kind: 'polygon' | 'rect'}`). Useful for\n * callers that need to fork between `pathPoseDescriptor` and\n * `RECT_POSE_DESCRIPTOR` without forcing the consumer to wire `geometry`\n * explicitly. */\nexport function isPathLike(p: unknown): p is Path {\n return !!p && typeof p === 'object' && 'kind' in p\n && ((p as { kind: unknown }).kind === 'polygon' || (p as { kind: unknown }).kind === 'rect');\n}\n\n/** Per-call dispatch: if the pose looks like a Path, route to\n * `pathPoseDescriptor`; otherwise treat as a plain rect pose. Avoids forcing\n * demos with Path TPose to wire `geometry={pathPoseDescriptor}` explicitly.\n * `getRotation` surfaces a `pose.rotation` field on non-Path poses so demos\n * using rect-with-rotation shapes (e.g. `RotatedPose`) don't have to wire\n * `geometry={ROTATED_POSE_DESCRIPTOR}` just to get rotated selection chrome\n * and rotation-aware corner hit-tests. */\nexport const AUTO_POSE_DESCRIPTOR: PoseProjection<unknown> = {\n getBounds: (p) => isPathLike(p)\n ? pathPoseDescriptor.getBounds(p)\n : RECT_POSE_DESCRIPTOR.getBounds(p as { x: number; y: number; width: number; height: number }),\n remapBounds: (p, src, dst) => isPathLike(p)\n ? pathPoseDescriptor.remapBounds(p, src, dst)\n : RECT_POSE_DESCRIPTOR.remapBounds(p as { x: number; y: number; width: number; height: number }, src, dst),\n translate: (p, dx, dy) => isPathLike(p)\n ? pathPoseDescriptor.translate!(p, dx, dy)\n : RECT_POSE_DESCRIPTOR.translate!(p as { x: number; y: number; width: number; height: number }, dx, dy),\n intersectsRect: (p, rect) => isPathLike(p)\n ? pathPoseDescriptor.intersectsRect!(p, rect)\n : RECT_POSE_DESCRIPTOR.intersectsRect!(p as { x: number; y: number; width: number; height: number }, rect),\n getRotation: (p) => {\n if (isPathLike(p)) return 0;\n const r = (p as { rotation?: unknown }).rotation;\n return typeof r === 'number' ? r : 0;\n },\n // Path-shaped poses can't carry rotation (see `pathPoseDescriptor`).\n // Everything else flows through `wrapWithPoseRotation`'s x/y/w/h gate at\n // paint time, so report `true` and let the wrapper no-op for poses\n // missing AABB fields.\n supportsRotation: (p) => !isPathLike(p),\n};\n","import type { SnapStrategy } from '../../types';\nimport { resolveUnit, type UnitSystem, type UnitValue } from 'core/units';\nimport type { DebugSink } from '../../../../debug/types';\nimport { isPathLike } from 'interactions/actions/resize/autoPoseDescriptor';\nimport { boundsOfPath } from 'features/paths/bounds';\nimport { translatePath } from 'features/paths/transform';\nimport type { Path } from 'features/paths/types';\n\n/**\n * Projection used by `gridSnapStrategy` when `TPose` doesn't expose `{x,y}`\n * directly (Path, polygon, etc.). The strategy reads the snap point via\n * `getOrigin`, rounds it to the grid, then asks `translate` to move the\n * pose by the resulting delta.\n */\nexport interface OriginProjection<TPose> {\n getOrigin(pose: TPose): { x: number; y: number };\n translate(pose: TPose, dx: number, dy: number): TPose;\n}\n\n/** Identity projection for `TPose extends { x; y }`. */\nexport const RECT_ORIGIN_PROJECTION: OriginProjection<{ x: number; y: number }> = {\n getOrigin: (p) => ({ x: p.x, y: p.y }),\n translate: (p, dx, dy) => ({ ...p, x: p.x + dx, y: p.y + dy }),\n};\n\n/** Per-call dispatch: routes Path-shaped poses to the path origin/translate\n * helpers and everything else to `RECT_ORIGIN_PROJECTION`. Default for\n * `gridSnapStrategy` so consumers with Path TPose don't have to thread\n * `pathOriginProjection` explicitly. */\nexport const AUTO_ORIGIN_PROJECTION: OriginProjection<unknown> = {\n getOrigin: (p) => {\n if (isPathLike(p)) {\n const b = boundsOfPath(p as Path);\n return { x: b.x, y: b.y };\n }\n const r = p as { x: number; y: number };\n return { x: r.x, y: r.y };\n },\n translate: (p, dx, dy) => {\n if (isPathLike(p)) return translatePath(p as Path, dx, dy);\n const r = p as { x: number; y: number };\n return { ...r, x: r.x + dx, y: r.y + dy };\n },\n};\n\n/** Snap-strategy that rounds the pose's origin to the nearest multiple of\n * `spacing` (resolved through `unitSystem`). For non-rect TPose pass an\n * `OriginProjection` so the strategy knows how to read/write the origin. */\nexport function gridSnapStrategy<TPose>(\n spacing: UnitValue,\n unitSystem?: UnitSystem,\n): SnapStrategy<TPose>;\n/** As above, additionally reporting each candidate to a debug sink. */\nexport function gridSnapStrategy<TPose>(\n spacing: UnitValue,\n opts: { unitSystem?: UnitSystem; debug?: DebugSink },\n): SnapStrategy<TPose>;\n/** As above, for a `TPose` that is not a rect: `origin` tells the strategy how\n * to read and write the pose's origin. */\nexport function gridSnapStrategy<TPose>(\n spacing: UnitValue,\n opts: { unitSystem?: UnitSystem; origin: OriginProjection<TPose>; debug?: DebugSink },\n): SnapStrategy<TPose>;\n/** Snap-strategy that rounds the pose's origin to the nearest multiple of\n * `spacing` (resolved through `unitSystem`). For non-rect TPose pass an\n * `OriginProjection` so the strategy knows how to read/write the origin. */\nexport function gridSnapStrategy<TPose>(\n spacing: UnitValue,\n arg?: UnitSystem | { unitSystem?: UnitSystem; origin?: OriginProjection<TPose>; debug?: DebugSink },\n): SnapStrategy<TPose> {\n const isOpts =\n typeof arg === 'object' &&\n arg !== null &&\n ('origin' in arg || 'debug' in arg || 'unitSystem' in arg) &&\n !('base' in arg);\n const optsArg = isOpts\n ? (arg as { unitSystem?: UnitSystem; origin?: OriginProjection<TPose>; debug?: DebugSink })\n : null;\n const unitSystem = optsArg ? optsArg.unitSystem : (arg as UnitSystem | undefined);\n const proj: OriginProjection<TPose> = optsArg && optsArg.origin\n ? optsArg.origin\n : (AUTO_ORIGIN_PROJECTION as unknown as OriginProjection<TPose>);\n const debug: DebugSink | undefined = optsArg ? optsArg.debug : undefined;\n const c = resolveUnit(spacing, unitSystem);\n return {\n snap(pose) {\n const o = proj.getOrigin(pose);\n const sx = Math.round(o.x / c) * c;\n const sy = Math.round(o.y / c) * c;\n debug?.recordSnapCandidate({ x: sx, y: sy }, true);\n return proj.translate(pose, sx - o.x, sy - o.y);\n },\n };\n}\n\n/**\n * Compute the integer cell `{col, row}` that contains `point`, given a grid\n * `spacing` and optional `origin` and `unitSystem`. Pair with\n * `createCellHighlightLayer` (its `getCell` callback) to draw a snap-target\n * preview that uses the same spacing as `gridSnapStrategy` — so the visual\n * and behavioral grids stay in lockstep:\n *\n * const SPACING = 20;\n * const snap = gridSnapStrategy(SPACING);\n * // visual grid:\n * createGridLayer({ spacing: SPACING, bounds: () => ... });\n * // hover-preview overlay:\n * createCellHighlightLayer({\n * spacing: SPACING,\n * getCell: () => hoverPoint && pointToGridCell(hoverPoint, SPACING),\n * });\n */\nexport function pointToGridCell(\n point: { x: number; y: number },\n spacing: UnitValue,\n unitSystem?: UnitSystem,\n origin: { x: number; y: number } = { x: 0, y: 0 },\n): { col: number; row: number } {\n const s = resolveUnit(spacing, unitSystem);\n return {\n col: Math.floor((point.x - origin.x) / s),\n row: Math.floor((point.y - origin.y) / s),\n };\n}\n","/**\n * Screen-pixel lengths in world units, per axis.\n *\n * Chrome declares its hit zones in screen pixels — an 8px handle stays 8px at\n * every zoom, because it paints in screen space. Converting one such length to\n * world units with a single scalar (see `meanScale`) is exact only under\n * uniform zoom; per-axis it is too generous on one axis and too mean on the\n * other, so the pickable region stops matching the painted one.\n *\n * Prefer {@link withinPxBox} / {@link withinPxRadius}, which compare in screen\n * space and so can't drift from the paint at all. {@link pxExtent} is for the\n * cases that must stay in world units — a tolerance handed to geometry that\n * doesn't know about the view.\n */\n\nexport interface Scale2 {\n x: number;\n y: number;\n}\n\n/** Guard against a degenerate axis: a zero scale would send the extent to\n * infinity and make every point a hit. */\nconst MIN_SCALE = 1e-9;\n\n/** One screen-pixel length as world-space extents, per axis. */\nexport function pxExtent(px: number, scale: Scale2): { x: number; y: number } {\n return {\n x: px / Math.max(MIN_SCALE, Math.abs(scale.x)),\n y: px / Math.max(MIN_SCALE, Math.abs(scale.y)),\n };\n}\n\n/** World delta → screen delta. Only the scale participates: translation\n * cancels in a difference, and the kit's views carry no skew. */\nexport function scaleDelta(dx: number, dy: number, scale: Scale2): { x: number; y: number } {\n return { x: dx * scale.x, y: dy * scale.y };\n}\n\n/**\n * Is a world-space delta inside a screen-space square of half-extent `px`?\n *\n * The square is axis-aligned **on screen**, which is what a handle painted in\n * screen space actually is — so this stays true under non-uniform zoom and\n * under a rotated target, where an axis-aligned world-space test is a rotated\n * rectangle on screen.\n */\nexport function withinPxBox(dx: number, dy: number, px: number, scale: Scale2): boolean {\n const s = scaleDelta(dx, dy, scale);\n return Math.abs(s.x) <= px && Math.abs(s.y) <= px;\n}\n\n/** Is a world-space delta inside a screen-space circle of radius `px`? */\nexport function withinPxRadius(dx: number, dy: number, px: number, scale: Scale2): boolean {\n const s = scaleDelta(dx, dy, scale);\n return s.x * s.x + s.y * s.y <= px * px;\n}\n","import type { SnapStrategy } from '../../types';\nimport type { Guide } from 'features/guides/types';\nimport type { View } from 'core/viewport/view';\nimport { pxExtent } from 'core/viewport/pxExtent';\nimport type { OriginProjection } from './grid';\nimport { RECT_ORIGIN_PROJECTION } from './grid';\n\n/** Default snap tolerance (screen pixels). */\nexport const DEFAULT_GUIDE_TOLERANCE_PX = 6;\n\n/** Options for `guideSnapStrategy`. */\nexport interface GuideSnapOptions<TPose> {\n /**\n * Tolerance, in screen pixels (CSS px) when `getView` is provided, or in\n * world units otherwise. Defaults to `DEFAULT_GUIDE_TOLERANCE_PX`.\n */\n tolerance?: number;\n /**\n * Read the active view transform. When supplied, `tolerance` is interpreted\n * in screen pixels and divided by `view.scale` so the trigger zone stays\n * the same on screen as the user zooms in/out. Without it, `tolerance`\n * is treated as world units.\n */\n getView?: () => View;\n /**\n * Projection used when `TPose` doesn't expose `{x, y}` directly (Path,\n * polygon, etc.) — same contract as `gridSnapStrategy`. Defaults to the\n * rect-pose identity projection.\n */\n origin?: OriginProjection<TPose>;\n}\n\n/**\n * Snap-strategy that snaps the pose's origin to the nearest guide line on\n * each axis when within tolerance. Each axis is considered independently:\n * a vertical guide (`axis: 'x'`) constrains X, a horizontal guide\n * (`axis: 'y'`) constrains Y. When multiple guides are within range on the\n * same axis, the closest wins.\n *\n * Pair with `useGuides` for storage and `createGuidesLayer` for rendering.\n *\n * **Composition:** combining with `gridSnapStrategy` is left to the\n * consumer in v1 — typically by picking one based on a modifier key, or\n * by stacking two move/resize/insert behaviors in priority order.\n */\nexport function guideSnapStrategy<TPose extends { x: number; y: number }>(\n getGuides: () => readonly Guide[],\n options?: Omit<GuideSnapOptions<TPose>, 'origin'>,\n): SnapStrategy<TPose>;\n/** As above, for a `TPose` that is not a rect: `origin` tells the strategy how\n * to read and write the pose's origin. */\nexport function guideSnapStrategy<TPose>(\n getGuides: () => readonly Guide[],\n options: GuideSnapOptions<TPose> & { origin: OriginProjection<TPose> },\n): SnapStrategy<TPose>;\n/** Snap a pose's origin to the nearest guide line within tolerance, per axis. */\nexport function guideSnapStrategy<TPose>(\n getGuides: () => readonly Guide[],\n options: GuideSnapOptions<TPose> = {},\n): SnapStrategy<TPose> {\n const tolerance = options.tolerance ?? DEFAULT_GUIDE_TOLERANCE_PX;\n const getView = options.getView;\n const proj: OriginProjection<TPose> =\n options.origin ?? (RECT_ORIGIN_PROJECTION as unknown as OriginProjection<TPose>);\n\n return {\n snap(pose) {\n const guides = getGuides();\n if (guides.length === 0) return null;\n\n // Convert tolerance to world units, per axis: a guide on the x axis is\n // matched by a horizontal distance, so it answers to `scale.x` alone.\n // With no view, treat tolerance as already-world.\n const tol = getView ? pxExtent(tolerance, getView().scale) : { x: tolerance, y: tolerance };\n\n const o = proj.getOrigin(pose);\n\n let bestDx = 0;\n let bestAbsDx = Infinity;\n let bestDy = 0;\n let bestAbsDy = Infinity;\n\n for (const g of guides) {\n if (g.axis === 'x') {\n const d = g.offset - o.x;\n const ad = Math.abs(d);\n if (ad <= tol.x && ad < bestAbsDx) {\n bestAbsDx = ad;\n bestDx = d;\n }\n } else {\n const d = g.offset - o.y;\n const ad = Math.abs(d);\n if (ad <= tol.y && ad < bestAbsDy) {\n bestAbsDy = ad;\n bestDy = d;\n }\n }\n }\n\n if (bestAbsDx === Infinity && bestAbsDy === Infinity) return null;\n const dx = bestAbsDx === Infinity ? 0 : bestDx;\n const dy = bestAbsDy === Infinity ? 0 : bestDy;\n if (dx === 0 && dy === 0) return null;\n return proj.translate(pose, dx, dy);\n },\n };\n}\n"]}
|