@weasel-js/core 1.7.3 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/dist/animation/colorHelpers.js +58 -58
  3. package/dist/animation/colorHelpers.js.map +1 -1
  4. package/dist/animation/engine/axes.js +36 -0
  5. package/dist/animation/engine/axes.js.map +1 -0
  6. package/dist/animation/engine/codec.js +170 -0
  7. package/dist/animation/engine/codec.js.map +1 -0
  8. package/dist/animation/engine/integrator.js +12 -0
  9. package/dist/animation/engine/integrator.js.map +1 -0
  10. package/dist/animation/useAnimator.js +209 -160
  11. package/dist/animation/useAnimator.js.map +1 -1
  12. package/dist/{builtins-C-gRyVRx.d.ts → builtins-CMEh6-Oc.d.ts} +81 -8
  13. package/dist/canvas/SceneCanvas/defaultNodeProperties.js +12 -12
  14. package/dist/canvas/SceneCanvas/defaultNodeProperties.js.map +1 -1
  15. package/dist/canvas/pickWalk.js +2 -2
  16. package/dist/canvas/pickWalk.js.map +1 -1
  17. package/dist/canvas/sceneSlotWiring.js +1 -1
  18. package/dist/canvas/sceneSlotWiring.js.map +1 -1
  19. package/dist/canvas/sceneViewRender.js +1 -1
  20. package/dist/canvas/sceneViewRender.js.map +1 -1
  21. package/dist/core/scene/effectivePose.js +1 -1
  22. package/dist/core/scene/effectivePose.js.map +1 -1
  23. package/dist/core/scene/poseOverrides.js +42 -22
  24. package/dist/core/scene/poseOverrides.js.map +1 -1
  25. package/dist/core/scene/scene.js +9 -0
  26. package/dist/core/scene/scene.js.map +1 -1
  27. package/dist/core/scene/types.js.map +1 -1
  28. package/dist/core/selection/useSelection.js +27 -33
  29. package/dist/core/selection/useSelection.js.map +1 -1
  30. package/dist/core/stableStringify.js +8 -0
  31. package/dist/core/stableStringify.js.map +1 -0
  32. package/dist/index.d.ts +35 -25
  33. package/dist/index.js +269 -268
  34. package/dist/renderer/WeaselRenderer.js +4 -1
  35. package/dist/renderer/WeaselRenderer.js.map +1 -1
  36. package/dist/renderer/batchClip.js +46 -0
  37. package/dist/renderer/batchClip.js.map +1 -0
  38. package/dist/renderer/draw.js +367 -294
  39. package/dist/renderer/draw.js.map +1 -1
  40. package/dist/renderer/drawBatch.js +75 -45
  41. package/dist/renderer/drawBatch.js.map +1 -1
  42. package/dist/renderer/shaders/batchFill.js +3 -2
  43. package/dist/renderer/shaders/batchFill.js.map +1 -1
  44. package/dist/renderer.d.ts +1 -1
  45. package/dist/tools/builtin/text/useTextTool.js +8 -8
  46. package/dist/tools/builtin/text/useTextTool.js.map +1 -1
  47. package/dist/tools/prefs.js.map +1 -1
  48. package/dist/version.js +1 -1
  49. package/package.json +17 -15
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":["asNodeId","s"],"sources":["../../../src/core/scene/types.ts"],"sourcesContent":["import type { Path } from '@weasel-js/geom';\nimport type { History, SerializedHistory } from '@weasel-js/history';\nimport type { ParallaxOpts } from '../viewport/parallax';\nimport type { ContainerBounds, LayoutStrategy } from '../../layout/types';\nimport type { PoseComposition } from './composeFrame';\n\n/**\n * Axis-aligned rectangle pose with optional rotation. The canonical pose\n * shape used by `composeRectPose` and the `unionBounds` helper. Rotation is\n * in radians, pivoted on the unrotated AABB center; absent === 0. Kit-side\n * code that consumes rotation already reads `pose.rotation ?? 0`\n * (`wrapNodeOutput`, `rotate/handle.ts`, `pathInWorld.ts`), so\n * the slot exists on every default scene whether or not the consumer\n * populates it.\n */\nexport interface RectPose {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Rotation in radians around the unrotated AABB center. Absent === 0. */\n rotation?: number;\n}\n\n/**\n * # SceneNode — the thing in the scene\n *\n * A `SceneNode` is the single canonical unit of a weasel scene. Everything\n * the user sees on the canvas — a shape, a group, an annotation, a tile —\n * is one of these. Containers and leaves are both nodes; the kit has no\n * other concept of \"scene element.\"\n *\n * ## Three orthogonal slots\n *\n * Every node carries three independent slots, plus its tree position:\n *\n * - **`data: TData`** — app-defined payload. The kit never inspects it.\n * Color, label, kind, glyph, sample-rate, whatever the app's domain\n * calls for. Mutated via `Scene.update(id, { data })`.\n *\n * - **`pose: TPose`** — local transform, relative to the node's direct\n * parent (or world, for root nodes). Default `RectPose` is\n * `{ x, y, width, height }`, but `TPose` is fully generic so apps can\n * use rotated rects, paths, ellipses, etc. The kit composes world\n * poses via `composeWorldPose` when rendering / hit-testing / snapping.\n *\n * - **`layer: TLayer`** — a string tag associating the node with a\n * visual `RenderLayer` at draw time. Separate from `LayerRecord` (the\n * per-layer visible/locked metadata held by the `Scene`).\n *\n * Tree position lives on the node itself: every node has a `parent` (or\n * `null` for roots), and `ContainerNode` adds an ordered `children: NodeId[]`.\n *\n * ## Identity is by `NodeId`, not by reference\n *\n * Nodes are addressed by `NodeId` everywhere outside the scene tree:\n * selection is `NodeId[]`, ops reference `NodeId`s, adapter methods accept\n * `string` ids and look up the node on demand. The `Node` object itself is\n * a snapshot of current state — don't hold references to it across scene\n * updates; look up by id when you need the latest.\n *\n * Picking helpers (`pickBest`, `pickEvery`) likewise return ids, not nodes —\n * they're hit-testing primitives that stay ignorant of node payload shape.\n *\n * ## Vocabulary\n *\n * The kit-internal name is `Node`; the public re-export is `SceneNode`\n * (avoids collision with DOM `Node` at call sites). Adapter methods speak\n * the same vocabulary: `getNode`, `getNodes`, `insertNode`, `removeNode`,\n * `cloneNode`, `addNode`. Older code, demos, and comments may still say\n * \"object\" or \"item\" — those are historical aliases for the same concept.\n */\n\n/** Opaque branded id. Treat as opaque outside the kit. */\nimport type { NodeId } from '@weasel-js/routing';\nexport type { NodeId };\n\n/** Brand a string as a NodeId. */\nexport const asNodeId = (s: string): NodeId => s as NodeId;\n\n/**\n * One dependency, as a derivation reads it: the node itself and the pose it is\n * painted at.\n *\n * The node comes along because a connector legitimately reads more than a box\n * — an edge that thickens with its endpoint's weight, or routes only to nodes\n * on a given layer, is answering off `data` and `layer`. The scene already\n * invalidates dependents on `kit:setData` and `kit:setLayer` for exactly that,\n * so handing over only the pose made the invalidation pay for a read nothing\n * could perform.\n */\nexport interface DerivedDep<TPose> {\n node: Node<unknown, string, TPose>;\n /** Its override when it has one, else its own derived pose, else the pose\n * the document stores — `effectivePose`, the same answer the renderer uses. */\n pose: TPose;\n /** The path it derives, or `null` when it derives none. Read it to place\n * something *along* a dependency rather than beside it — a label on a\n * routed edge, a tick on a curve.\n *\n * Resolved on first read and memoized on the dependency, so a route costs\n * the same whether one node reads it or five, and a dependency nobody asks\n * about costs nothing. */\n readonly path: Path | null;\n}\n\n/** Computes a node's path from its dependencies: the type of a node's\n * `derivePath` and of each entry in `SceneRegistry.derivePath`. */\nexport type DerivePathFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => Path | null;\n\n/** Computes a node's pose from its dependencies: the type of a node's\n * `derivePose` and of each entry in `SceneRegistry.derivePose`. */\nexport type DerivePoseFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => TPose | null;\n\ninterface NodeBase<TData, TLayer extends string, TPose> {\n id: NodeId;\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent: NodeId | null;\n /** Nodes whose poses this node's geometry is computed from. Fixed at add\n * time. Absent or empty means the node's geometry is authored, which is the\n * normal case.\n *\n * `'children'` means \"my own children, in child order\" — a container that\n * hugs its contents, which a fixed id list cannot express because\n * reparenting would have to maintain it. The two forms differ in lifetime\n * as well as in membership: deleting a node deletes everything that names\n * it in `dependsOn`, but a container outlives the children it derives\n * from — an emptied group is still a group. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Whether the hit-test walk can return this node. Default `true`; `false`\n * makes it transparent to picking, so a click on it lands on whatever is\n * behind — normally its own container.\n *\n * For content a container owns rather than content the user selects on its\n * own: the label inside a box, a body's rows. Without it the innermost hit\n * wins, and dragging a labeled box moves the label out of the box. It does\n * not hide the node from anything else — it still paints, still clips, and\n * a consumer can still select it by id. */\n pickable?: boolean;\n /** Computes this node's path from its dependencies, in `dependsOn` order —\n * each one the node and the pose it is painted at.\n * A dependency that has been removed arrives as `undefined`.\n * Returning `null` means \"nothing to draw right now\". Re-evaluated when a\n * dependency's world pose changes, never authored. Absolute-pose `Scene`\n * makes that the dependency's own pose, and an ancestor's move reaches it as\n * a `setPose` of its own from the container cascade.\n * `node` is deliberately widened: naming `TData`/`TLayer` here puts them in\n * a contravariant position, making `Scene` invariant in both and breaking\n * assignment kit-wide. The cost is that a `derivePath` casts to read `node.data`. */\n derivePath?: DerivePathFn<TPose>;\n /** Computes this node's pose from its dependencies' poses, the same way\n * `derivePath` computes its path — same `dependsOn` list, same widened\n * `node`, same registry-keyed serialization.\n *\n * Where a derived path is resolved at paint time and reaches only the\n * painter, a derived pose is what the node *is* at: it feeds bounds,\n * hit-testing, selection chrome, snapping and layout, and every reader\n * gets it through `effectivePose`. A pose override still wins over it —\n * that is what lets a drag preview a node the document says is elsewhere.\n *\n * Returning `null` means \"I have nothing to derive from right now\", and\n * the node falls back to its authored `pose`. `setPose` on a derived node\n * still writes that authored pose; it is simply not what anything reads. */\n derivePose?: DerivePoseFn<TPose>;\n}\n\n/** A node with no children — a shape, a label, an image. */\nexport interface LeafNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'leaf';\n}\n\n/** A node with an ordered list of children. This is the real group: what\n * Cmd+G creates, what SVG `<g>` round-trips to. A container has its own pose,\n * which its children's poses are relative to, and may optionally clip them. */\nexport interface ContainerNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'container';\n children: NodeId[];\n /** Optional clip-path source. Re-evaluated each render. Returning `null`\n * means \"no clip for this container right now\"; an empty / zero-area path\n * means \"clip everything out\" (children render nowhere). When set, the\n * renderer rasterizes the returned path into the stencil buffer and\n * paints descendants only where it covers. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** How this container arranges its children. Whenever the container's\n * child set or order changes, or its bounds change size, the scene hands\n * the change to the strategy — `depart` for children that left it,\n * `arrive` for children that joined it, `childPoses` otherwise — and records the poses it writes in the same\n * undo entry as the change. A drag reads it too: it is the layout `move`\n * reflows and drops against. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A pose a container's layout wrote — reported by {@link Scene.onReflow} —\n * in the node's stored frame. */\nexport interface LayoutMove<TPose> {\n id: NodeId;\n from: TPose;\n to: TPose;\n}\n\n/** How a scene reads a laid-out container's bounds and folds poses to the\n * world frame a {@link LayoutStrategy} works in. */\nexport interface LayoutFrame<TPose> {\n /** The container's bounds, from its world pose. Default: the pose's own\n * `x`/`y`/`width`/`height`; a pose without them is not laid out. */\n bounds?(pose: TPose): ContainerBounds | null;\n /** `pose` resized from bounds `from` to `to`, for a layout that grows its\n * container. Default: `to`'s fields written over the pose. */\n remap?(pose: TPose, from: ContainerBounds, to: ContainerBounds): TPose;\n /** Omit for the absolute-pose model. A scene whose canvas composes poses\n * (`<SceneCanvas poseComposition>`) passes the same strategy here. */\n composition?: PoseComposition<TPose>;\n}\n\n/** A node in the scene tree: either a leaf or a container. Re-exported\n * publicly as `SceneNode`, to avoid colliding with the DOM's `Node`. */\nexport type Node<TData, TLayer extends string, TPose = RectPose> =\n | LeafNode<TData, TLayer, TPose>\n | ContainerNode<TData, TLayer, TPose>;\n\ninterface LayerRecordBase<TLayer extends string> {\n id: TLayer;\n visible: boolean;\n locked: boolean;\n /** Draw this layer as a parallax plane: through a view derived from the\n * camera's (see `deriveParallaxView`), and picked through the same one.\n * Absent means the layer moves with the camera. */\n parallax?: ParallaxOpts;\n}\n\n/** A layer declared when the scene was created. Fixed set, no display name —\n * these are the kit's own render bands, not something a user manages. */\nexport interface SystemLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'system';\n}\n\n/** A layer the user created and can rename, reorder or delete. */\nexport interface UserLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'user';\n name: string;\n}\n\n/** Per-layer metadata held by the scene: whether it is visible and locked,\n * and where it sits in the render stack. Distinct from a node's `layer` tag,\n * which merely names one of these. */\nexport type LayerRecord<TLayer extends string> =\n | SystemLayerRecord<TLayer>\n | UserLayerRecord<TLayer>;\n\n/** What `Scene.add` needs to mint a node. Everything except the id is\n * required; the id is generated unless one is supplied. */\nexport interface AddNodeSpec<TData, TLayer extends string, TPose = RectPose> {\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent?: NodeId | null;\n index?: number;\n /** Explicit id wins over the Scene's `generateId` and the kit default. */\n id?: NodeId;\n /** Mirrors `SceneNode.pickable`. Omit for the default, which is pickable. */\n pickable?: boolean;\n /** Only meaningful when `kind === 'container'`. Attach a clip-path function\n * to the node; ignored for leaves. Mirrors `ContainerNode.clipFromPose`. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** Mirrors `SceneNode.dependsOn`. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Mirrors `SceneNode.derivePath`. Taken as a live function; its registry key is\n * looked up from it, never passed in. */\n derivePath?: DerivePathFn<TPose>;\n /** Mirrors `SceneNode.derivePose`, on the same terms as `derivePath`. */\n derivePose?: DerivePoseFn<TPose>;\n /** Mirrors `ContainerNode.layout`; ignored for leaves. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A custom scene mutation registered with `Scene.registerOp`: how to apply\n * it and how to undo it. The pair is what makes it participate in history. */\nexport interface RegisteredOp<P> {\n apply: (payload: P) => void;\n revert: (payload: P) => void;\n}\n\n/** One of the layers a scene is created with. */\nexport interface SystemLayerSpec<TLayer extends string> {\n id: TLayer;\n visible?: boolean;\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n}\n\n/** Argument to `Scene.addLayer`. Always produces a `UserLayerRecord`\n * (`kind: 'user'`). */\nexport interface AddLayerSpec<TLayer extends string> {\n id: TLayer;\n name: string;\n /** Default `true`. */\n visible?: boolean;\n /** Default `false`. */\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n /** Render-stack position. Default: top of stack (highest render index). */\n index?: number;\n}\n\n/** One layer as it appears in a snapshot. A snapshot written before layer\n * kind was serialized carries neither field, and loads as a system layer —\n * which is what every layer in such a snapshot was. */\nexport interface SerializedLayer<TLayer extends string>\n extends SystemLayerSpec<TLayer> {\n kind?: 'system' | 'user';\n /** Present on a user layer, absent on a system one. */\n name?: string;\n}\n\n/** JSON-serializable shape of a Scene's current state. Produced by\n * `scene.toJSON()`; consumed by `sceneFromJSON()`. Function fields\n * (e.g., `clipFromPose`) appear as string keys (`clipFromPoseKey`) and\n * are resolved through `SceneRegistry` at load time. */\nexport interface SerializedScene<TData, TLayer extends string, TPose> {\n version: 1;\n /** The whole layer stack, system and user alike — the name predates user\n * layers and is kept so existing snapshots still parse. */\n systemLayers: readonly SerializedLayer<TLayer>[];\n nodes: readonly SerializedNode<TData, TLayer, TPose>[];\n}\n\n/** JSON-serializable shape of a single node. Mirrors `AddNodeSpec` but\n * with function fields replaced by registry keys. */\nexport interface SerializedNode<TData, TLayer extends string, TPose> {\n id: string;\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n /** Parent id; omitted for roots. */\n parent?: string;\n /** Registry key for the container's clip-path factory.\n * Containers only; omitted when the container has no clip. */\n clipFromPoseKey?: string;\n /** Ids this node's geometry derives from, or `'children'`. Omitted when it\n * derives from nothing. */\n dependsOn?: readonly string[] | 'children';\n /** Mirrors `SceneNode.pickable`. Omitted when the node is pickable. */\n pickable?: boolean;\n /** Registry key for the node's `derivePath` function. Omitted when it has none. */\n derivePathKey?: string;\n /** Registry key for the node's `derivePose` function. Omitted when it has none. */\n derivePoseKey?: string;\n /** Registry key for the container's layout strategy. Omitted when it has none. */\n layoutKey?: string;\n}\n\n/** Per-scene registry mapping string keys to live function references.\n * Passed to `createScene({ ..., registry })` and `sceneFromJSON(json, { registry })`.\n * Each function-field type has its own keyed map. */\nexport interface SceneRegistry<TPose> {\n /** Maps registry keys to `clipFromPose` factory functions for container nodes. */\n clipFromPose?: Readonly<Record<string, (pose: TPose) => Path | null>>;\n /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */\n derivePath?: Readonly<Record<string, DerivePathFn<TPose>>>;\n /** Maps registry keys to `derivePose` functions for nodes with `dependsOn`. */\n derivePose?: Readonly<Record<string, DerivePoseFn<TPose>>>;\n /** Maps registry keys to container layout strategies. */\n layout?: Readonly<Record<string, LayoutStrategy<TPose>>>;\n // A new function field is a row in `NODE_FN_FIELDS` (core/scene/nodeFnFields.ts)\n // plus its entry here; the field name is the registry key by construction.\n}\n\n/**\n * Decides what one edit's changes to containers do to their children.\n * `arrivals` maps each container to the ids that joined it — by an `add`\n * under it or a `move` into it, whatever op or call made them — in the order\n * they arrived. `changed` names every container whose child set or order\n * changed, or whose pose changed size, arrivals included. Both are read once\n * the edit's other mutations have landed.\n *\n * Return the poses to write, in each node's stored frame; they become part of\n * the same edit, and so of the same undo step. An empty map writes nothing.\n * Return `null` to refuse: the whole edit is reverted (see\n * `SceneArrivalRefused`).\n *\n * Runs only for live edits. Undo, redo and a restored history replay the\n * arrangement that was decided the first time. With none installed, a scene\n * holding declared layouts (`ContainerNode.layout`) runs its own.\n */\nexport type SceneArrivalHandler<TPose> = (\n arrivals: ReadonlyMap<NodeId, readonly NodeId[]>,\n changed: ReadonlySet<NodeId>,\n /** The nodes that left each container in the edit, by the container they\n * left — removed, or moved out. */\n departures: ReadonlyMap<NodeId, readonly NodeId[]>,\n) => ReadonlyMap<NodeId, TPose> | null;\n\n/** Options for `useScene` — the layers the scene has, what it starts out\n * holding, and how its history behaves. */\nexport interface UseSceneOptions<TData, TLayer extends string, TPose = RectPose> {\n systemLayers: readonly SystemLayerSpec<TLayer>[];\n initial?: readonly AddNodeSpec<TData, TLayer, TPose>[];\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n historyLimit?: number;\n /** Window (ms) within which consecutive same-shaped mutations merge into\n * the previous undo entry (matching per-op coalesce keys — e.g. repeated\n * `setPose` on the same node, or repeated `applyBatch` calls whose ops\n * carry matching `coalesceKey` multisets). `0` (default) disables\n * coalescing: every mutation is a discrete undo entry. Undo of a\n * coalesced entry returns to the state before the first merged mutation;\n * redo restores the latest. `scene.batch` entries never coalesce. */\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n /** Per-scene registry for non-serializable function fields (clipFromPose, etc.).\n * Required only when serializing/deserializing scenes that use function fields. */\n registry?: SceneRegistry<TPose>;\n /** How laid-out containers are measured. See {@link LayoutFrame}. */\n layoutFrame?: LayoutFrame<TPose>;\n /** When supplied, `scene.applyOps(ops, label)` consults this on every call.\n * If it returns a non-null `Journal`, ops are routed to the journal's\n * `applyBatch` instead of recording a new parent-history entry. The journal\n * drives adapter mutation internally (via `op.apply(adapter)`), so the\n * scene state changes as normal; only the history tracking differs.\n *\n * The accessor is called on every `applyOps` invocation so the caller can\n * swap the active journal in and out by updating the closure's reference\n * (e.g., an app's mode machine holds `let activeJournal: Journal | null`\n * and the accessor reads that variable).\n *\n * When the accessor isn't known at scene-construction time (typical for\n * mode machines that depend on `scene.history`), pass nothing here and\n * wire it after construction via `scene.setActiveJournalAccessor(fn)`. */\n getActiveJournal?: () => import('@weasel-js/history').Journal | null;\n /** Re-render the host on every scene mutation. Default `true`. Set `false`\n * when the scene is read by a frame loop rather than by a render — a game\n * loop, a simulation — and nothing in the host's DOM derives from it.\n * Read by `useScene`; `createScene` ignores it. */\n subscribe?: boolean;\n}\n\n/**\n * One node's ephemeral presentation override — what a frame loop wants to say\n * about a node without saying it about the document.\n *\n * Not document content: never recorded in history, never in `toJSON`, and\n * writing one does not bump `Scene.getVersion()`. Hoist one entry per node and\n * mutate it in place on a frame loop; `PoseOverrides.commit()` is what makes a\n * mutation visible.\n */\nexport interface PoseOverride<TPose> {\n /** Replaces the node's document pose everywhere the render and hit-test\n * paths read one, including the clip a container derives from its pose, and\n * winning over a `derivePose`. Resolved by `effectivePose` — reading\n * `node.pose` directly is how those paths came to disagree about where a\n * node is. */\n pose?: TPose;\n /** Multiplied into the node's painted alpha, on top of any `alphaFor`. */\n alpha?: number;\n}\n\n/**\n * The scene's ephemeral per-node overrides — see {@link PoseOverride}.\n *\n * The intended shape of a frame is: `set` each node once, mutate the entries\n * in place per frame, `commit()` once. `commit` is not optional bookkeeping —\n * the painter memo keys on pose *reference*, so a mutation without a commit\n * paints the previous frame with no error.\n *\n * To promote a frame to document state (dropping a drag, baking an animation),\n * write it once through `Scene.setPose` and `clear` the override.\n */\nexport interface PoseOverrides<TPose> {\n /** Store `entry` for `id` **by reference**; the caller keeps mutating it. */\n set(id: NodeId, entry: PoseOverride<TPose>): void;\n get(id: NodeId): PoseOverride<TPose> | undefined;\n has(id: NodeId): boolean;\n /** The overridden ids, as a snapshot array. */\n ids(): readonly NodeId[];\n clear(id: NodeId): void;\n clearAll(): void;\n /** Publish this frame's in-place mutations: invalidate the painter memo for\n * every overridden node, then notify subscribers. */\n commit(): void;\n /** Notified after every write. The canvas uses this to repaint without a\n * scene version bump. */\n subscribe(fn: () => void): () => void;\n /** Monotonic write counter. A snapshot for observers that poll. */\n getGeneration(): number;\n}\n\n/**\n * The kit-owned scene tree: nodes, layers, and the undo history over both.\n *\n * A scene is logical, not visual — it says what exists and where, and nothing\n * about how it is painted. Every mutating method is undoable, and reads are\n * snapshots rather than live views. Nodes are addressed by `NodeId`; hold ids\n * across mutations, not node objects.\n *\n * Three type parameters keep it domain-agnostic: `TData` is the app's payload,\n * which the kit never inspects; `TPose` is the transform shape, `RectPose` by\n * default; `TLayer` is the union of layer names.\n */\nexport interface Scene<TData, TLayer extends string, TPose = RectPose> {\n // Reads\n readonly nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;\n readonly roots: readonly NodeId[];\n readonly layers: readonly LayerRecord<TLayer>[];\n /** The registry this scene resolves node functions against — the consumer's\n * entries over the kit's. */\n readonly registry: SceneRegistry<TPose>;\n get(id: NodeId): Node<TData, TLayer, TPose> | undefined;\n /** A token for the node `id` names right now, for telling one node from a\n * later one that reuses its id. It holds for as long as the node stays in\n * the scene, whatever edits it takes, and is different every time the id\n * enters the scene — by `add`, by an undo or redo that brings it back, or\n * by `loadState`. `undefined` when `id` is not in the scene. Compare tokens\n * for equality only; their order means nothing. */\n incarnation(id: NodeId): number | undefined;\n childrenOf(id: NodeId): readonly NodeId[];\n ancestorsOf(id: NodeId): readonly NodeId[];\n renderOrder(): Iterable<NodeId>;\n /** The same layer-major sequence as {@link Scene.renderOrder}, as the nodes\n * themselves. Prefer this wherever the ids are only going to be resolved\n * back to nodes: the traversal already holds them, and re-looking each one\n * up was ~40% of the area hit-test's per-node cost. Cached until a\n * structural edit, so repeat calls hand back the same array — a snapshot,\n * not a live view, and not yours to mutate. */\n renderOrderNodes(): readonly Node<TData, TLayer, TPose>[];\n /** The nodes on one layer, in render order. Cached alongside\n * {@link Scene.renderOrderNodes} until a structural edit, so a caller that\n * only cares about one layer pays the tree walk once rather than once per\n * call. A snapshot, not a live view, and not yours to mutate. An unknown\n * layer id yields an empty array. */\n nodesOnLayer(layer: TLayer): readonly Node<TData, TLayer, TPose>[];\n\n // Mutations (all auto-undoable)\n add(spec: AddNodeSpec<TData, TLayer, TPose>): NodeId;\n /** Delete `id`, its **entire subtree**, and **everything that derives from**\n * any of those nodes — a node listing one of them in `dependsOn` goes too,\n * along with its own subtree, transitively. A dependent can live anywhere in\n * the tree, so this deletes nodes the caller never named and may unlink\n * several disjoint subtrees at once. Recorded as one undoable step; `undo()`\n * restores every one of them where it was, child order intact. */\n remove(id: NodeId): void;\n /** {@link remove} over several roots at once, as a **single** undoable step.\n * Ids resolve against the tree as it stands at the call, so an id that\n * another one would cascade away is absorbed rather than removed twice —\n * which is what makes it safe to pass a whole selection. Throws if any id is\n * not in the scene; an empty list does nothing and records no step. */\n removeMany(ids: readonly NodeId[]): void;\n /** Every node {@link removeMany} would take if given `ids`: each id, its\n * subtree, everything deriving from any of those, and those nodes' subtrees\n * in turn. The authoritative answer — the cascade relations live here, and\n * a caller reconstructing them from `dependsOn` and `children` drifts the\n * moment a third one is added. Ids not in the scene come back unchanged.\n *\n * A set, not a restore order: a dependent can be reached before the parent\n * it sits under, which is also in the closure. */\n removalClosure(ids: readonly NodeId[]): readonly NodeId[];\n update(id: NodeId, patch: { data: TData }): void;\n setPose(id: NodeId, pose: TPose): void;\n /** Retag `id` to `layer`. On a **container this cascades**: every descendant\n * is moved to the same layer, recorded as a **single** undo step.\n *\n * Invariants:\n * - **Layer floor** — a child may not render below its parent, so retagging\n * to a layer *below* the node's parent throws. Retagging to the parent's\n * layer or any higher one is allowed; a node with no parent is\n * unconstrained.\n * - **No-op elision** — setting the layer a node already has does nothing\n * and pushes **no** history entry. */\n setLayer(id: NodeId, layer: TLayer): void;\n /** Point `id` at a different set of dependencies — retargeting an edge's end\n * onto another node, or switching a container between an id list and\n * `'children'`. Recorded as one undoable step.\n *\n * Order is significant: a derivation reads its dependencies positionally,\n * so `[b, a]` is not `[a, b]`. Ids need not be in the scene — a declared\n * dependency that appears later invalidates the node when it does, the same\n * as one declared at `add`. Passing `undefined` drops the declaration, after\n * which nothing cascades the node away.\n *\n * **No-op elision** — declaring what the node already declares does nothing\n * and pushes no history entry. */\n setDependsOn(id: NodeId, dependsOn: readonly NodeId[] | 'children' | undefined): void;\n /** Give container `id` a different layout — a strategy, its key in\n * `SceneRegistry.layout`, or `null` for none — and re-arrange its children\n * under it, as one undoable step. Throws for a leaf, or a key the registry\n * does not hold. A registered layout is recorded by its key, so a\n * serialized history restores it; an unregistered one lives only as long\n * as the session.\n *\n * **No-op elision** — setting the layout a container already has does\n * nothing and pushes no history entry. */\n setLayout(id: NodeId, layout: LayoutStrategy<TPose> | string | null): void;\n /** Reparent `id` under `parent` (or to a root when `parent` is `null`) at\n * `index` within the new sibling list, appending when `index` is omitted.\n * Siblings are reindexed. Recorded as one undoable step.\n *\n * Rejected (throws) when:\n * - `parent` exists but is a **leaf**, not a container;\n * - the move would form a **cycle** — `parent` is `id` itself or one of\n * `id`'s own descendants;\n * - it would drop `id` **below its new parent's layer** (child may not\n * render below its parent).\n *\n * `move(id, null)` — detaching to a root — is always allowed regardless of\n * layer, since a root has no parent to render beneath. */\n move(id: NodeId, parent: NodeId | null, index?: number): void;\n /** Shift `id` to `index` within its **current** parent's child list. Unlike\n * {@link move}, the parent never changes — only sibling order. */\n reorder(id: NodeId, index: number): void;\n setLayerVisible(layer: TLayer, visible: boolean): void;\n /** Lock or unlock a layer. A locked layer still paints, but its nodes are\n * out of reach: picking and area selection pass over them, the selection\n * drops them, and every node mutation on them throws. Locking is never\n * blocked by the lock, and neither are the other layer operations. */\n setLayerLocked(layer: TLayer, locked: boolean): void;\n /** Set or clear (`undefined`) a layer's parallax — see\n * `LayerRecord.parallax`. Undoable; an animation tweening it writes inside\n * {@link Scene.untracked} so no frame becomes an undo step. */\n setLayerParallax(layer: TLayer, parallax: ParallaxOpts | undefined): void;\n /** Whether `id` sits on a locked layer or under a container that does.\n * A container's lock covers its whole subtree, whatever layers the\n * descendants are tagged to. An id not in the scene is not locked. */\n isLocked(id: NodeId): boolean;\n /** Run `fn` with the lock guard lifted, for a programmatic edit that has to\n * reach a locked node. Undo and redo never need it. */\n unlocked<T>(fn: () => T): T;\n addLayer(spec: AddLayerSpec<TLayer>): void;\n /** Drop a user layer and every node tagged to it, as one undoable step.\n * Removal cascades, so this also deletes nodes **on other layers** that\n * derive from a node on this one. */\n removeLayer(layer: TLayer): void;\n renameLayer(layer: TLayer, name: string): void;\n moveLayer(layer: TLayer, index: number): void;\n\n // Custom op seam\n registerOp<P>(kind: string, handler: RegisteredOp<P>): void;\n recordOp<P>(op: { kind: string; payload: P }): void;\n\n /** Install (or clear) the active-journal accessor after scene construction.\n * Useful when the journal source (typically a mode machine) is built\n * with `scene.history` as a dependency — a chicken-and-egg situation\n * where the accessor can't be passed in via `UseSceneOptions`.\n *\n * Pass `null` to detach. Overrides any `getActiveJournal` set in\n * `UseSceneOptions`. */\n setActiveJournalAccessor(\n fn: (() => import('@weasel-js/history').Journal | null) | null,\n ): void;\n\n /** Install what the scene does when nodes join a container, replacing any\n * handler installed before; `null` removes it. Returns a function that\n * removes this handler, and does nothing once another has replaced it.\n * See {@link SceneArrivalHandler}. */\n setArrivalHandler(handler: SceneArrivalHandler<TPose> | null): () => void;\n\n /** Apply a batch of ops with journal-aware routing.\n *\n * - **Without active journal** (or no `getActiveJournal` in options):\n * the ops themselves are recorded as one undo entry on the scene's own\n * history, rebound to `adapter` — undo replays each op's `invert()`\n * against that same adapter. Consecutive `applyBatch` entries can\n * coalesce via matching op `coalesceKey`s when the scene opts into\n * `coalesceWindowMs`.\n * - **With active journal**: routes ops to `journal.applyBatch(ops, label)`.\n * The scene's history recording is suppressed for the duration so the\n * journal's inner history — not the scene's undo stack — tracks the batch.\n * Mutations still happen on `adapter` / scene state.\n *\n * `adapter` must be the same adapter the ops expect (typically a\n * `SceneCanvasAdapter`). Pass `this` from `sceneToAdapter` or a compatible\n * adapter. */\n applyBatch(ops: import('core/ops/types').Op[], label: string, adapter: unknown): void;\n\n // Selection\n\n /** The transient set of active ids — \"operate on these N as a unit\".\n * Shared by every view over this scene unless a view supplies its own\n * (see `CanvasView.selection`). Not document content: it never appears\n * in `toJSON`. It does ride on history entries, so undo and redo put\n * back the selection an edit was made under; changing it is never an\n * undo step of its own. */\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n\n // Ephemeral presentation state\n\n /** Per-node pose / alpha overrides the render and hit-test paths read\n * through. Like {@link Scene.getSelection} this is not document content:\n * writes are never recorded, never serialized, and do not bump\n * {@link Scene.getVersion}. See {@link PoseOverrides}. */\n readonly overrides: PoseOverrides<TPose>;\n\n // History\n /** The scene's undo/redo engine, in the shape `@weasel-js/history` defines —\n * what the kit's `undo` / `redo` actions resolve their `history` dep to, and\n * what a mode machine opens journals against. Mutating members route through\n * the scene's own wrappers, so an undo driven through this bumps\n * {@link Scene.getVersion} and notifies subscribers exactly as\n * {@link Scene.undo} does; `getVersion` / `subscribe` on it report the\n * engine's history version, not the scene's. */\n readonly history: History;\n undo(): boolean;\n redo(): boolean;\n canUndo(): boolean;\n canRedo(): boolean;\n batch<T>(label: string, fn: () => T): T;\n /** The layout container `id` declares, or `null` for a leaf or a\n * container that declares none. */\n layoutOf(id: NodeId): LayoutStrategy<TPose> | null;\n /** Called with the poses each live edit's layout pass wrote, after the\n * edit lands — never for an undo or redo, which restore poses rather than\n * arrange them. What a reflow animation glides from. */\n onReflow(listener: (moves: readonly LayoutMove<TPose>[]) => void): () => void;\n /** Run `fn` with every mutation applied but none recorded — for writes\n * that are not edits, such as a simulation stepping poses each frame.\n * Undo and redo move between recorded states and never restore an\n * untracked write; the next recorded change starts from whatever the\n * untracked writes left, so undoing it lands there. A `batch` inside\n * records nothing; inside a `batch`, these writes stay out of its entry.\n * Notifies once, reverts `fn`'s writes if it throws, and throws on\n * `applyBatch` and `history.apply` / `applyOps`, which exist to record. */\n untracked<T>(fn: () => T): T;\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Oldest applied first, then redoable entries in\n * the order they'd be re-applied. Each entry id is stable. */\n historyEntries(): readonly { id: string; label: string }[];\n /** Index of the \"current state\". Equals the count of applied entries;\n * `0` means \"nothing applied\" (initial). */\n historyIndex(): number;\n /** Jump to the given history index by calling undo/redo repeatedly.\n * Clamps to [0, total]. Returns true if any movement occurred. */\n jumpToHistoryIndex(index: number): boolean;\n\n // History persistence\n /** Snapshot the undo/redo history in a JSON-serializable form (the\n * engine's `SerializedHistory`). Entries containing any nameless op are\n * dropped (hand-rolled anonymous ops passed to `applyBatch`); kit and\n * consumer-registered ops always carry names. Payload JSON-safety\n * (e.g. typed arrays inside poses) is the caller's concern. Do not call\n * mid-`batch` — the open batch's ops are not yet recorded. */\n serializeHistory(): SerializedHistory;\n /** Replace the undo/redo history from a `serializeHistory()` snapshot.\n * Call on a scene whose node/layer state already matches the snapshot's\n * head state (i.e. right after `loadState` from the paired scene\n * snapshot); node state is NOT mutated. Ops re-registered via\n * `registerOp` before this call round-trip; unknown kinds become no-op\n * placeholders; external ops rebuild via the global op-factory registry\n * and replay against the `setHistoryAdapter` accessor. Restored entries\n * never coalesce with new ones. Notifies once. Do not call mid-`batch`:\n * the stacks are replaced underneath the open batch, whose eventual\n * flush would graft onto (and evict against) the restored stacks. */\n restoreHistory(snapshot: SerializedHistory): void;\n /** Install (or clear with `null`) the accessor for the adapter that\n * RESTORED external ops (recorded via `applyBatch`, rebuilt from a\n * `restoreHistory` snapshot) apply against on undo/redo. Resolved lazily\n * at each apply, so wiring order relative to `restoreHistory` doesn't\n * matter. Live `applyBatch` entries are unaffected (they bind their\n * call-site adapter). If unset when a restored op applies, the op is a\n * debug-warned no-op. */\n setHistoryAdapter(fn: (() => unknown) | null): void;\n\n // Serialization\n /** Snapshot the current scene state to a JSON-serializable shape.\n * History (undo/redo stacks) is NOT captured. Function fields like\n * `ContainerNode.clipFromPose` are translated to string keys via the\n * scene's registry; throws if any function field has no matching key. */\n toJSON(): SerializedScene<TData, TLayer, TPose>;\n /** Replace this scene's entire node + layer state in place from a snapshot\n * produced by `toJSON()`. Unlike `sceneFromJSON`, the existing Scene\n * instance is preserved — holders such as `<SceneCanvas>` keep their\n * reference. History (undo/redo) is cleared, matching `sceneFromJSON`.\n * Bumps `getVersion()` and notifies subscribers exactly once.\n *\n * Throws on an unsupported version or unknown registry/layer ids; on a\n * malformed snapshot the scene is left empty or partially populated (callers should treat a\n * `loadState` throw as fatal and reload). Snapshots from `toJSON()` are\n * always well-formed. */\n loadState(json: SerializedScene<TData, TLayer, TPose>): void;\n\n // Subscription (used by useScene; also for non-React observers)\n subscribe(listener: () => void): () => void;\n /** Monotonically increasing version. Snapshot for `useSyncExternalStore`. */\n getVersion(): number;\n}\n"],"mappings":";AA8EA,IAAaA,KAAY,MAAsBC"}
1
+ {"version":3,"file":"types.js","names":["asNodeId","s"],"sources":["../../../src/core/scene/types.ts"],"sourcesContent":["import type { Path } from '@weasel-js/geom';\nimport type { History, SerializedHistory } from '@weasel-js/history';\nimport type { ParallaxOpts } from '../viewport/parallax';\nimport type { ContainerBounds, LayoutStrategy } from '../../layout/types';\nimport type { PoseComposition } from './composeFrame';\n\n/**\n * Axis-aligned rectangle pose with optional rotation. The canonical pose\n * shape used by `composeRectPose` and the `unionBounds` helper. Rotation is\n * in radians, pivoted on the unrotated AABB center; absent === 0. Kit-side\n * code that consumes rotation already reads `pose.rotation ?? 0`\n * (`wrapNodeOutput`, `rotate/handle.ts`, `pathInWorld.ts`), so\n * the slot exists on every default scene whether or not the consumer\n * populates it.\n */\nexport interface RectPose {\n x: number;\n y: number;\n width: number;\n height: number;\n /** Rotation in radians around the unrotated AABB center. Absent === 0. */\n rotation?: number;\n}\n\n/**\n * # SceneNode — the thing in the scene\n *\n * A `SceneNode` is the single canonical unit of a weasel scene. Everything\n * the user sees on the canvas — a shape, a group, an annotation, a tile —\n * is one of these. Containers and leaves are both nodes; the kit has no\n * other concept of \"scene element.\"\n *\n * ## Three orthogonal slots\n *\n * Every node carries three independent slots, plus its tree position:\n *\n * - **`data: TData`** — app-defined payload. The kit never inspects it.\n * Color, label, kind, glyph, sample-rate, whatever the app's domain\n * calls for. Mutated via `Scene.update(id, { data })`.\n *\n * - **`pose: TPose`** — local transform, relative to the node's direct\n * parent (or world, for root nodes). Default `RectPose` is\n * `{ x, y, width, height }`, but `TPose` is fully generic so apps can\n * use rotated rects, paths, ellipses, etc. The kit composes world\n * poses via `composeWorldPose` when rendering / hit-testing / snapping.\n *\n * - **`layer: TLayer`** — a string tag associating the node with a\n * visual `RenderLayer` at draw time. Separate from `LayerRecord` (the\n * per-layer visible/locked metadata held by the `Scene`).\n *\n * Tree position lives on the node itself: every node has a `parent` (or\n * `null` for roots), and `ContainerNode` adds an ordered `children: NodeId[]`.\n *\n * ## Identity is by `NodeId`, not by reference\n *\n * Nodes are addressed by `NodeId` everywhere outside the scene tree:\n * selection is `NodeId[]`, ops reference `NodeId`s, adapter methods accept\n * `string` ids and look up the node on demand. The `Node` object itself is\n * a snapshot of current state — don't hold references to it across scene\n * updates; look up by id when you need the latest.\n *\n * Picking helpers (`pickBest`, `pickEvery`) likewise return ids, not nodes —\n * they're hit-testing primitives that stay ignorant of node payload shape.\n *\n * ## Vocabulary\n *\n * The kit-internal name is `Node`; the public re-export is `SceneNode`\n * (avoids collision with DOM `Node` at call sites). Adapter methods speak\n * the same vocabulary: `getNode`, `getNodes`, `insertNode`, `removeNode`,\n * `cloneNode`, `addNode`. Older code, demos, and comments may still say\n * \"object\" or \"item\" — those are historical aliases for the same concept.\n */\n\n/** Opaque branded id. Treat as opaque outside the kit. */\nimport type { NodeId } from '@weasel-js/routing';\nexport type { NodeId };\n\n/** Brand a string as a NodeId. */\nexport const asNodeId = (s: string): NodeId => s as NodeId;\n\n/**\n * One dependency, as a derivation reads it: the node itself and the pose it is\n * painted at.\n *\n * The node comes along because a connector legitimately reads more than a box\n * — an edge that thickens with its endpoint's weight, or routes only to nodes\n * on a given layer, is answering off `data` and `layer`. The scene already\n * invalidates dependents on `kit:setData` and `kit:setLayer` for exactly that,\n * so handing over only the pose made the invalidation pay for a read nothing\n * could perform.\n */\nexport interface DerivedDep<TPose> {\n node: Node<unknown, string, TPose>;\n /** Its override when it has one, else its own derived pose, else the pose\n * the document stores — `effectivePose`, the same answer the renderer uses. */\n pose: TPose;\n /** The path it derives, or `null` when it derives none. Read it to place\n * something *along* a dependency rather than beside it — a label on a\n * routed edge, a tick on a curve.\n *\n * Resolved on first read and memoized on the dependency, so a route costs\n * the same whether one node reads it or five, and a dependency nobody asks\n * about costs nothing. */\n readonly path: Path | null;\n}\n\n/** Computes a node's path from its dependencies: the type of a node's\n * `derivePath` and of each entry in `SceneRegistry.derivePath`. */\nexport type DerivePathFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => Path | null;\n\n/** Computes a node's pose from its dependencies: the type of a node's\n * `derivePose` and of each entry in `SceneRegistry.derivePose`. */\nexport type DerivePoseFn<TPose> = (\n node: Node<unknown, string, TPose>,\n deps: readonly (DerivedDep<TPose> | undefined)[],\n) => TPose | null;\n\ninterface NodeBase<TData, TLayer extends string, TPose> {\n id: NodeId;\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent: NodeId | null;\n /** Nodes whose poses this node's geometry is computed from. Fixed at add\n * time. Absent or empty means the node's geometry is authored, which is the\n * normal case.\n *\n * `'children'` means \"my own children, in child order\" — a container that\n * hugs its contents, which a fixed id list cannot express because\n * reparenting would have to maintain it. The two forms differ in lifetime\n * as well as in membership: deleting a node deletes everything that names\n * it in `dependsOn`, but a container outlives the children it derives\n * from — an emptied group is still a group. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Whether the hit-test walk can return this node. Default `true`; `false`\n * makes it transparent to picking, so a click on it lands on whatever is\n * behind — normally its own container.\n *\n * For content a container owns rather than content the user selects on its\n * own: the label inside a box, a body's rows. Without it the innermost hit\n * wins, and dragging a labeled box moves the label out of the box. It does\n * not hide the node from anything else — it still paints, still clips, and\n * a consumer can still select it by id. */\n pickable?: boolean;\n /** Computes this node's path from its dependencies, in `dependsOn` order —\n * each one the node and the pose it is painted at.\n * A dependency that has been removed arrives as `undefined`.\n * Returning `null` means \"nothing to draw right now\". Re-evaluated when a\n * dependency's world pose changes, never authored. Absolute-pose `Scene`\n * makes that the dependency's own pose, and an ancestor's move reaches it as\n * a `setPose` of its own from the container cascade.\n * `node` is deliberately widened: naming `TData`/`TLayer` here puts them in\n * a contravariant position, making `Scene` invariant in both and breaking\n * assignment kit-wide. The cost is that a `derivePath` casts to read `node.data`. */\n derivePath?: DerivePathFn<TPose>;\n /** Computes this node's pose from its dependencies' poses, the same way\n * `derivePath` computes its path — same `dependsOn` list, same widened\n * `node`, same registry-keyed serialization.\n *\n * Where a derived path is resolved at paint time and reaches only the\n * painter, a derived pose is what the node *is* at: it feeds bounds,\n * hit-testing, selection chrome, snapping and layout, and every reader\n * gets it through `effectivePose`. A pose override still wins over it —\n * that is what lets a drag preview a node the document says is elsewhere.\n *\n * Returning `null` means \"I have nothing to derive from right now\", and\n * the node falls back to its authored `pose`. `setPose` on a derived node\n * still writes that authored pose; it is simply not what anything reads. */\n derivePose?: DerivePoseFn<TPose>;\n}\n\n/** A node with no children — a shape, a label, an image. */\nexport interface LeafNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'leaf';\n}\n\n/** A node with an ordered list of children. This is the real group: what\n * Cmd+G creates, what SVG `<g>` round-trips to. A container has its own pose,\n * which its children's poses are relative to, and may optionally clip them. */\nexport interface ContainerNode<TData, TLayer extends string, TPose = RectPose>\n extends NodeBase<TData, TLayer, TPose> {\n kind: 'container';\n children: NodeId[];\n /** Optional clip-path source. Re-evaluated each render. Returning `null`\n * means \"no clip for this container right now\"; an empty / zero-area path\n * means \"clip everything out\" (children render nowhere). When set, the\n * renderer rasterizes the returned path into the stencil buffer and\n * paints descendants only where it covers. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** How this container arranges its children. Whenever the container's\n * child set or order changes, or its bounds change size, the scene hands\n * the change to the strategy — `depart` for children that left it,\n * `arrive` for children that joined it, `childPoses` otherwise — and records the poses it writes in the same\n * undo entry as the change. A drag reads it too: it is the layout `move`\n * reflows and drops against. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A pose a container's layout wrote — reported by {@link Scene.onReflow} —\n * in the node's stored frame. */\nexport interface LayoutMove<TPose> {\n id: NodeId;\n from: TPose;\n to: TPose;\n}\n\n/** How a scene reads a laid-out container's bounds and folds poses to the\n * world frame a {@link LayoutStrategy} works in. */\nexport interface LayoutFrame<TPose> {\n /** The container's bounds, from its world pose. Default: the pose's own\n * `x`/`y`/`width`/`height`; a pose without them is not laid out. */\n bounds?(pose: TPose): ContainerBounds | null;\n /** `pose` resized from bounds `from` to `to`, for a layout that grows its\n * container. Default: `to`'s fields written over the pose. */\n remap?(pose: TPose, from: ContainerBounds, to: ContainerBounds): TPose;\n /** Omit for the absolute-pose model. A scene whose canvas composes poses\n * (`<SceneCanvas poseComposition>`) passes the same strategy here. */\n composition?: PoseComposition<TPose>;\n}\n\n/** A node in the scene tree: either a leaf or a container. Re-exported\n * publicly as `SceneNode`, to avoid colliding with the DOM's `Node`. */\nexport type Node<TData, TLayer extends string, TPose = RectPose> =\n | LeafNode<TData, TLayer, TPose>\n | ContainerNode<TData, TLayer, TPose>;\n\ninterface LayerRecordBase<TLayer extends string> {\n id: TLayer;\n visible: boolean;\n locked: boolean;\n /** Draw this layer as a parallax plane: through a view derived from the\n * camera's (see `deriveParallaxView`), and picked through the same one.\n * Absent means the layer moves with the camera. */\n parallax?: ParallaxOpts;\n}\n\n/** A layer declared when the scene was created. Fixed set, no display name —\n * these are the kit's own render bands, not something a user manages. */\nexport interface SystemLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'system';\n}\n\n/** A layer the user created and can rename, reorder or delete. */\nexport interface UserLayerRecord<TLayer extends string>\n extends LayerRecordBase<TLayer> {\n kind: 'user';\n name: string;\n}\n\n/** Per-layer metadata held by the scene: whether it is visible and locked,\n * and where it sits in the render stack. Distinct from a node's `layer` tag,\n * which merely names one of these. */\nexport type LayerRecord<TLayer extends string> =\n | SystemLayerRecord<TLayer>\n | UserLayerRecord<TLayer>;\n\n/** What `Scene.add` needs to mint a node. Everything except the id is\n * required; the id is generated unless one is supplied. */\nexport interface AddNodeSpec<TData, TLayer extends string, TPose = RectPose> {\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n parent?: NodeId | null;\n index?: number;\n /** Explicit id wins over the Scene's `generateId` and the kit default. */\n id?: NodeId;\n /** Mirrors `SceneNode.pickable`. Omit for the default, which is pickable. */\n pickable?: boolean;\n /** Only meaningful when `kind === 'container'`. Attach a clip-path function\n * to the node; ignored for leaves. Mirrors `ContainerNode.clipFromPose`. */\n clipFromPose?: (pose: TPose) => Path | null;\n /** Mirrors `SceneNode.dependsOn`. */\n dependsOn?: readonly NodeId[] | 'children';\n /** Mirrors `SceneNode.derivePath`. Taken as a live function; its registry key is\n * looked up from it, never passed in. */\n derivePath?: DerivePathFn<TPose>;\n /** Mirrors `SceneNode.derivePose`, on the same terms as `derivePath`. */\n derivePose?: DerivePoseFn<TPose>;\n /** Mirrors `ContainerNode.layout`; ignored for leaves. */\n layout?: LayoutStrategy<TPose>;\n}\n\n/** A custom scene mutation registered with `Scene.registerOp`: how to apply\n * it and how to undo it. The pair is what makes it participate in history. */\nexport interface RegisteredOp<P> {\n apply: (payload: P) => void;\n revert: (payload: P) => void;\n}\n\n/** One of the layers a scene is created with. */\nexport interface SystemLayerSpec<TLayer extends string> {\n id: TLayer;\n visible?: boolean;\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n}\n\n/** Argument to `Scene.addLayer`. Always produces a `UserLayerRecord`\n * (`kind: 'user'`). */\nexport interface AddLayerSpec<TLayer extends string> {\n id: TLayer;\n name: string;\n /** Default `true`. */\n visible?: boolean;\n /** Default `false`. */\n locked?: boolean;\n /** See `LayerRecord.parallax`. */\n parallax?: ParallaxOpts;\n /** Render-stack position. Default: top of stack (highest render index). */\n index?: number;\n}\n\n/** One layer as it appears in a snapshot. A snapshot written before layer\n * kind was serialized carries neither field, and loads as a system layer —\n * which is what every layer in such a snapshot was. */\nexport interface SerializedLayer<TLayer extends string>\n extends SystemLayerSpec<TLayer> {\n kind?: 'system' | 'user';\n /** Present on a user layer, absent on a system one. */\n name?: string;\n}\n\n/** JSON-serializable shape of a Scene's current state. Produced by\n * `scene.toJSON()`; consumed by `sceneFromJSON()`. Function fields\n * (e.g., `clipFromPose`) appear as string keys (`clipFromPoseKey`) and\n * are resolved through `SceneRegistry` at load time. */\nexport interface SerializedScene<TData, TLayer extends string, TPose> {\n version: 1;\n /** The whole layer stack, system and user alike — the name predates user\n * layers and is kept so existing snapshots still parse. */\n systemLayers: readonly SerializedLayer<TLayer>[];\n nodes: readonly SerializedNode<TData, TLayer, TPose>[];\n}\n\n/** JSON-serializable shape of a single node. Mirrors `AddNodeSpec` but\n * with function fields replaced by registry keys. */\nexport interface SerializedNode<TData, TLayer extends string, TPose> {\n id: string;\n kind: 'leaf' | 'container';\n layer: TLayer;\n pose: TPose;\n data: TData;\n /** Parent id; omitted for roots. */\n parent?: string;\n /** Registry key for the container's clip-path factory.\n * Containers only; omitted when the container has no clip. */\n clipFromPoseKey?: string;\n /** Ids this node's geometry derives from, or `'children'`. Omitted when it\n * derives from nothing. */\n dependsOn?: readonly string[] | 'children';\n /** Mirrors `SceneNode.pickable`. Omitted when the node is pickable. */\n pickable?: boolean;\n /** Registry key for the node's `derivePath` function. Omitted when it has none. */\n derivePathKey?: string;\n /** Registry key for the node's `derivePose` function. Omitted when it has none. */\n derivePoseKey?: string;\n /** Registry key for the container's layout strategy. Omitted when it has none. */\n layoutKey?: string;\n}\n\n/** Per-scene registry mapping string keys to live function references.\n * Passed to `createScene({ ..., registry })` and `sceneFromJSON(json, { registry })`.\n * Each function-field type has its own keyed map. */\nexport interface SceneRegistry<TPose> {\n /** Maps registry keys to `clipFromPose` factory functions for container nodes. */\n clipFromPose?: Readonly<Record<string, (pose: TPose) => Path | null>>;\n /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */\n derivePath?: Readonly<Record<string, DerivePathFn<TPose>>>;\n /** Maps registry keys to `derivePose` functions for nodes with `dependsOn`. */\n derivePose?: Readonly<Record<string, DerivePoseFn<TPose>>>;\n /** Maps registry keys to container layout strategies. */\n layout?: Readonly<Record<string, LayoutStrategy<TPose>>>;\n // A new function field is a row in `NODE_FN_FIELDS` (core/scene/nodeFnFields.ts)\n // plus its entry here; the field name is the registry key by construction.\n}\n\n/**\n * Decides what one edit's changes to containers do to their children.\n * `arrivals` maps each container to the ids that joined it — by an `add`\n * under it or a `move` into it, whatever op or call made them — in the order\n * they arrived. `changed` names every container whose child set or order\n * changed, or whose pose changed size, arrivals included. Both are read once\n * the edit's other mutations have landed.\n *\n * Return the poses to write, in each node's stored frame; they become part of\n * the same edit, and so of the same undo step. An empty map writes nothing.\n * Return `null` to refuse: the whole edit is reverted (see\n * `SceneArrivalRefused`).\n *\n * Runs only for live edits. Undo, redo and a restored history replay the\n * arrangement that was decided the first time. With none installed, a scene\n * holding declared layouts (`ContainerNode.layout`) runs its own.\n */\nexport type SceneArrivalHandler<TPose> = (\n arrivals: ReadonlyMap<NodeId, readonly NodeId[]>,\n changed: ReadonlySet<NodeId>,\n /** The nodes that left each container in the edit, by the container they\n * left — removed, or moved out. */\n departures: ReadonlyMap<NodeId, readonly NodeId[]>,\n) => ReadonlyMap<NodeId, TPose> | null;\n\n/** Options for `useScene` — the layers the scene has, what it starts out\n * holding, and how its history behaves. */\nexport interface UseSceneOptions<TData, TLayer extends string, TPose = RectPose> {\n systemLayers: readonly SystemLayerSpec<TLayer>[];\n initial?: readonly AddNodeSpec<TData, TLayer, TPose>[];\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n historyLimit?: number;\n /** Window (ms) within which consecutive same-shaped mutations merge into\n * the previous undo entry (matching per-op coalesce keys — e.g. repeated\n * `setPose` on the same node, or repeated `applyBatch` calls whose ops\n * carry matching `coalesceKey` multisets). `0` (default) disables\n * coalescing: every mutation is a discrete undo entry. Undo of a\n * coalesced entry returns to the state before the first merged mutation;\n * redo restores the latest. `scene.batch` entries never coalesce. */\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n /** Per-scene registry for non-serializable function fields (clipFromPose, etc.).\n * Required only when serializing/deserializing scenes that use function fields. */\n registry?: SceneRegistry<TPose>;\n /** How laid-out containers are measured. See {@link LayoutFrame}. */\n layoutFrame?: LayoutFrame<TPose>;\n /** When supplied, `scene.applyOps(ops, label)` consults this on every call.\n * If it returns a non-null `Journal`, ops are routed to the journal's\n * `applyBatch` instead of recording a new parent-history entry. The journal\n * drives adapter mutation internally (via `op.apply(adapter)`), so the\n * scene state changes as normal; only the history tracking differs.\n *\n * The accessor is called on every `applyOps` invocation so the caller can\n * swap the active journal in and out by updating the closure's reference\n * (e.g., an app's mode machine holds `let activeJournal: Journal | null`\n * and the accessor reads that variable).\n *\n * When the accessor isn't known at scene-construction time (typical for\n * mode machines that depend on `scene.history`), pass nothing here and\n * wire it after construction via `scene.setActiveJournalAccessor(fn)`. */\n getActiveJournal?: () => import('@weasel-js/history').Journal | null;\n /** Re-render the host on every scene mutation. Default `true`. Set `false`\n * when the scene is read by a frame loop rather than by a render — a game\n * loop, a simulation — and nothing in the host's DOM derives from it.\n * Read by `useScene`; `createScene` ignores it. */\n subscribe?: boolean;\n}\n\n/**\n * One node's ephemeral presentation override — what a frame loop wants to say\n * about a node without saying it about the document.\n *\n * Not document content: never recorded in history, never in `toJSON`, and\n * writing one does not bump `Scene.getVersion()`. Hoist one entry per node and\n * mutate it in place on a frame loop; `PoseOverrides.commit()` is what makes a\n * mutation visible.\n */\nexport interface PoseOverride<TPose> {\n /** Replaces the node's document pose everywhere the render and hit-test\n * paths read one, including the clip a container derives from its pose, and\n * winning over a `derivePose`. Resolved by `effectivePose` — reading\n * `node.pose` directly is how those paths came to disagree about where a\n * node is. */\n pose?: TPose;\n /** Multiplied into the node's painted alpha, on top of any `alphaFor`. */\n alpha?: number;\n}\n\n/**\n * The scene's ephemeral per-node overrides — see {@link PoseOverride}.\n *\n * The intended shape of a frame is: `set` each node once, mutate the entries\n * in place per frame, `commit()` once. `commit` is not optional bookkeeping —\n * the painter memo keys on pose *reference*, so a mutation without a commit\n * paints the previous frame with no error.\n *\n * To promote a frame to document state (dropping a drag, baking an animation),\n * write it once through `Scene.setPose` and `clear` the override.\n */\nexport interface PoseOverrides<TPose> {\n /** Store `entry` for `id` **by reference**; the caller keeps mutating it. */\n set(id: NodeId, entry: PoseOverride<TPose>): void;\n /** The entry `set` stored, by reference — what a writer checks to know\n * whether its own entry is still installed. Painting reads `read`. */\n get(id: NodeId): PoseOverride<TPose> | undefined;\n /** What the node is drawn and picked with: every source of overrides for\n * it folded into one, as of the last write or `commit()`. `undefined` for\n * a node nothing overrides. The object is reused per node. */\n read(id: NodeId): PoseOverride<TPose> | undefined;\n has(id: NodeId): boolean;\n /** The overridden ids, as a snapshot array. */\n ids(): readonly NodeId[];\n clear(id: NodeId): void;\n clearAll(): void;\n /** Publish this frame's in-place mutations: invalidate the painter memo for\n * every overridden node, then notify subscribers. */\n commit(): void;\n /** Notified after every write. The canvas uses this to repaint without a\n * scene version bump. */\n subscribe(fn: () => void): () => void;\n /** Monotonic write counter. A snapshot for observers that poll. */\n getGeneration(): number;\n}\n\n/**\n * The kit-owned scene tree: nodes, layers, and the undo history over both.\n *\n * A scene is logical, not visual — it says what exists and where, and nothing\n * about how it is painted. Every mutating method is undoable, and reads are\n * snapshots rather than live views. Nodes are addressed by `NodeId`; hold ids\n * across mutations, not node objects.\n *\n * Three type parameters keep it domain-agnostic: `TData` is the app's payload,\n * which the kit never inspects; `TPose` is the transform shape, `RectPose` by\n * default; `TLayer` is the union of layer names.\n */\nexport interface Scene<TData, TLayer extends string, TPose = RectPose> {\n // Reads\n readonly nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;\n readonly roots: readonly NodeId[];\n readonly layers: readonly LayerRecord<TLayer>[];\n /** The registry this scene resolves node functions against — the consumer's\n * entries over the kit's. */\n readonly registry: SceneRegistry<TPose>;\n get(id: NodeId): Node<TData, TLayer, TPose> | undefined;\n /** A token for the node `id` names right now, for telling one node from a\n * later one that reuses its id. It holds for as long as the node stays in\n * the scene, whatever edits it takes, and is different every time the id\n * enters the scene — by `add`, by an undo or redo that brings it back, or\n * by `loadState`. `undefined` when `id` is not in the scene. Compare tokens\n * for equality only; their order means nothing. */\n incarnation(id: NodeId): number | undefined;\n childrenOf(id: NodeId): readonly NodeId[];\n ancestorsOf(id: NodeId): readonly NodeId[];\n renderOrder(): Iterable<NodeId>;\n /** The same layer-major sequence as {@link Scene.renderOrder}, as the nodes\n * themselves. Prefer this wherever the ids are only going to be resolved\n * back to nodes: the traversal already holds them, and re-looking each one\n * up was ~40% of the area hit-test's per-node cost. Cached until a\n * structural edit, so repeat calls hand back the same array — a snapshot,\n * not a live view, and not yours to mutate. */\n renderOrderNodes(): readonly Node<TData, TLayer, TPose>[];\n /** The nodes on one layer, in render order. Cached alongside\n * {@link Scene.renderOrderNodes} until a structural edit, so a caller that\n * only cares about one layer pays the tree walk once rather than once per\n * call. A snapshot, not a live view, and not yours to mutate. An unknown\n * layer id yields an empty array. */\n nodesOnLayer(layer: TLayer): readonly Node<TData, TLayer, TPose>[];\n\n // Mutations (all auto-undoable)\n add(spec: AddNodeSpec<TData, TLayer, TPose>): NodeId;\n /** Delete `id`, its **entire subtree**, and **everything that derives from**\n * any of those nodes — a node listing one of them in `dependsOn` goes too,\n * along with its own subtree, transitively. A dependent can live anywhere in\n * the tree, so this deletes nodes the caller never named and may unlink\n * several disjoint subtrees at once. Recorded as one undoable step; `undo()`\n * restores every one of them where it was, child order intact. */\n remove(id: NodeId): void;\n /** {@link remove} over several roots at once, as a **single** undoable step.\n * Ids resolve against the tree as it stands at the call, so an id that\n * another one would cascade away is absorbed rather than removed twice —\n * which is what makes it safe to pass a whole selection. Throws if any id is\n * not in the scene; an empty list does nothing and records no step. */\n removeMany(ids: readonly NodeId[]): void;\n /** Every node {@link removeMany} would take if given `ids`: each id, its\n * subtree, everything deriving from any of those, and those nodes' subtrees\n * in turn. The authoritative answer — the cascade relations live here, and\n * a caller reconstructing them from `dependsOn` and `children` drifts the\n * moment a third one is added. Ids not in the scene come back unchanged.\n *\n * A set, not a restore order: a dependent can be reached before the parent\n * it sits under, which is also in the closure. */\n removalClosure(ids: readonly NodeId[]): readonly NodeId[];\n update(id: NodeId, patch: { data: TData }): void;\n setPose(id: NodeId, pose: TPose): void;\n /** Retag `id` to `layer`. On a **container this cascades**: every descendant\n * is moved to the same layer, recorded as a **single** undo step.\n *\n * Invariants:\n * - **Layer floor** — a child may not render below its parent, so retagging\n * to a layer *below* the node's parent throws. Retagging to the parent's\n * layer or any higher one is allowed; a node with no parent is\n * unconstrained.\n * - **No-op elision** — setting the layer a node already has does nothing\n * and pushes **no** history entry. */\n setLayer(id: NodeId, layer: TLayer): void;\n /** Point `id` at a different set of dependencies — retargeting an edge's end\n * onto another node, or switching a container between an id list and\n * `'children'`. Recorded as one undoable step.\n *\n * Order is significant: a derivation reads its dependencies positionally,\n * so `[b, a]` is not `[a, b]`. Ids need not be in the scene — a declared\n * dependency that appears later invalidates the node when it does, the same\n * as one declared at `add`. Passing `undefined` drops the declaration, after\n * which nothing cascades the node away.\n *\n * **No-op elision** — declaring what the node already declares does nothing\n * and pushes no history entry. */\n setDependsOn(id: NodeId, dependsOn: readonly NodeId[] | 'children' | undefined): void;\n /** Give container `id` a different layout — a strategy, its key in\n * `SceneRegistry.layout`, or `null` for none — and re-arrange its children\n * under it, as one undoable step. Throws for a leaf, or a key the registry\n * does not hold. A registered layout is recorded by its key, so a\n * serialized history restores it; an unregistered one lives only as long\n * as the session.\n *\n * **No-op elision** — setting the layout a container already has does\n * nothing and pushes no history entry. */\n setLayout(id: NodeId, layout: LayoutStrategy<TPose> | string | null): void;\n /** Reparent `id` under `parent` (or to a root when `parent` is `null`) at\n * `index` within the new sibling list, appending when `index` is omitted.\n * Siblings are reindexed. Recorded as one undoable step.\n *\n * Rejected (throws) when:\n * - `parent` exists but is a **leaf**, not a container;\n * - the move would form a **cycle** — `parent` is `id` itself or one of\n * `id`'s own descendants;\n * - it would drop `id` **below its new parent's layer** (child may not\n * render below its parent).\n *\n * `move(id, null)` — detaching to a root — is always allowed regardless of\n * layer, since a root has no parent to render beneath. */\n move(id: NodeId, parent: NodeId | null, index?: number): void;\n /** Shift `id` to `index` within its **current** parent's child list. Unlike\n * {@link move}, the parent never changes — only sibling order. */\n reorder(id: NodeId, index: number): void;\n setLayerVisible(layer: TLayer, visible: boolean): void;\n /** Lock or unlock a layer. A locked layer still paints, but its nodes are\n * out of reach: picking and area selection pass over them, the selection\n * drops them, and every node mutation on them throws. Locking is never\n * blocked by the lock, and neither are the other layer operations. */\n setLayerLocked(layer: TLayer, locked: boolean): void;\n /** Set or clear (`undefined`) a layer's parallax — see\n * `LayerRecord.parallax`. Undoable; an animation tweening it writes inside\n * {@link Scene.untracked} so no frame becomes an undo step. */\n setLayerParallax(layer: TLayer, parallax: ParallaxOpts | undefined): void;\n /** Whether `id` sits on a locked layer or under a container that does.\n * A container's lock covers its whole subtree, whatever layers the\n * descendants are tagged to. An id not in the scene is not locked. */\n isLocked(id: NodeId): boolean;\n /** Run `fn` with the lock guard lifted, for a programmatic edit that has to\n * reach a locked node. Undo and redo never need it. */\n unlocked<T>(fn: () => T): T;\n addLayer(spec: AddLayerSpec<TLayer>): void;\n /** Drop a user layer and every node tagged to it, as one undoable step.\n * Removal cascades, so this also deletes nodes **on other layers** that\n * derive from a node on this one. */\n removeLayer(layer: TLayer): void;\n renameLayer(layer: TLayer, name: string): void;\n moveLayer(layer: TLayer, index: number): void;\n\n // Custom op seam\n registerOp<P>(kind: string, handler: RegisteredOp<P>): void;\n recordOp<P>(op: { kind: string; payload: P }): void;\n\n /** Install (or clear) the active-journal accessor after scene construction.\n * Useful when the journal source (typically a mode machine) is built\n * with `scene.history` as a dependency — a chicken-and-egg situation\n * where the accessor can't be passed in via `UseSceneOptions`.\n *\n * Pass `null` to detach. Overrides any `getActiveJournal` set in\n * `UseSceneOptions`. */\n setActiveJournalAccessor(\n fn: (() => import('@weasel-js/history').Journal | null) | null,\n ): void;\n\n /** Install what the scene does when nodes join a container, replacing any\n * handler installed before; `null` removes it. Returns a function that\n * removes this handler, and does nothing once another has replaced it.\n * See {@link SceneArrivalHandler}. */\n setArrivalHandler(handler: SceneArrivalHandler<TPose> | null): () => void;\n\n /** Apply a batch of ops with journal-aware routing.\n *\n * - **Without active journal** (or no `getActiveJournal` in options):\n * the ops themselves are recorded as one undo entry on the scene's own\n * history, rebound to `adapter` — undo replays each op's `invert()`\n * against that same adapter. Consecutive `applyBatch` entries can\n * coalesce via matching op `coalesceKey`s when the scene opts into\n * `coalesceWindowMs`.\n * - **With active journal**: routes ops to `journal.applyBatch(ops, label)`.\n * The scene's history recording is suppressed for the duration so the\n * journal's inner history — not the scene's undo stack — tracks the batch.\n * Mutations still happen on `adapter` / scene state.\n *\n * `adapter` must be the same adapter the ops expect (typically a\n * `SceneCanvasAdapter`). Pass `this` from `sceneToAdapter` or a compatible\n * adapter. */\n applyBatch(ops: import('core/ops/types').Op[], label: string, adapter: unknown): void;\n\n // Selection\n\n /** The transient set of active ids — \"operate on these N as a unit\".\n * Shared by every view over this scene unless a view supplies its own\n * (see `CanvasView.selection`). Not document content: it never appears\n * in `toJSON`. It does ride on history entries, so undo and redo put\n * back the selection an edit was made under; changing it is never an\n * undo step of its own. */\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n\n // Ephemeral presentation state\n\n /** Per-node pose / alpha overrides the render and hit-test paths read\n * through. Like {@link Scene.getSelection} this is not document content:\n * writes are never recorded, never serialized, and do not bump\n * {@link Scene.getVersion}. See {@link PoseOverrides}. */\n readonly overrides: PoseOverrides<TPose>;\n\n // History\n /** The scene's undo/redo engine, in the shape `@weasel-js/history` defines —\n * what the kit's `undo` / `redo` actions resolve their `history` dep to, and\n * what a mode machine opens journals against. Mutating members route through\n * the scene's own wrappers, so an undo driven through this bumps\n * {@link Scene.getVersion} and notifies subscribers exactly as\n * {@link Scene.undo} does; `getVersion` / `subscribe` on it report the\n * engine's history version, not the scene's. */\n readonly history: History;\n undo(): boolean;\n redo(): boolean;\n canUndo(): boolean;\n canRedo(): boolean;\n batch<T>(label: string, fn: () => T): T;\n /** The layout container `id` declares, or `null` for a leaf or a\n * container that declares none. */\n layoutOf(id: NodeId): LayoutStrategy<TPose> | null;\n /** Called with the poses each live edit's layout pass wrote, after the\n * edit lands — never for an undo or redo, which restore poses rather than\n * arrange them. What a reflow animation glides from. */\n onReflow(listener: (moves: readonly LayoutMove<TPose>[]) => void): () => void;\n /** Run `fn` with every mutation applied but none recorded — for writes\n * that are not edits, such as a simulation stepping poses each frame.\n * Undo and redo move between recorded states and never restore an\n * untracked write; the next recorded change starts from whatever the\n * untracked writes left, so undoing it lands there. A `batch` inside\n * records nothing; inside a `batch`, these writes stay out of its entry.\n * Notifies once, reverts `fn`'s writes if it throws, and throws on\n * `applyBatch` and `history.apply` / `applyOps`, which exist to record. */\n untracked<T>(fn: () => T): T;\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Oldest applied first, then redoable entries in\n * the order they'd be re-applied. Each entry id is stable. */\n historyEntries(): readonly { id: string; label: string }[];\n /** Index of the \"current state\". Equals the count of applied entries;\n * `0` means \"nothing applied\" (initial). */\n historyIndex(): number;\n /** Jump to the given history index by calling undo/redo repeatedly.\n * Clamps to [0, total]. Returns true if any movement occurred. */\n jumpToHistoryIndex(index: number): boolean;\n\n // History persistence\n /** Snapshot the undo/redo history in a JSON-serializable form (the\n * engine's `SerializedHistory`). Entries containing any nameless op are\n * dropped (hand-rolled anonymous ops passed to `applyBatch`); kit and\n * consumer-registered ops always carry names. Payload JSON-safety\n * (e.g. typed arrays inside poses) is the caller's concern. Do not call\n * mid-`batch` — the open batch's ops are not yet recorded. */\n serializeHistory(): SerializedHistory;\n /** Replace the undo/redo history from a `serializeHistory()` snapshot.\n * Call on a scene whose node/layer state already matches the snapshot's\n * head state (i.e. right after `loadState` from the paired scene\n * snapshot); node state is NOT mutated. Ops re-registered via\n * `registerOp` before this call round-trip; unknown kinds become no-op\n * placeholders; external ops rebuild via the global op-factory registry\n * and replay against the `setHistoryAdapter` accessor. Restored entries\n * never coalesce with new ones. Notifies once. Do not call mid-`batch`:\n * the stacks are replaced underneath the open batch, whose eventual\n * flush would graft onto (and evict against) the restored stacks. */\n restoreHistory(snapshot: SerializedHistory): void;\n /** Install (or clear with `null`) the accessor for the adapter that\n * RESTORED external ops (recorded via `applyBatch`, rebuilt from a\n * `restoreHistory` snapshot) apply against on undo/redo. Resolved lazily\n * at each apply, so wiring order relative to `restoreHistory` doesn't\n * matter. Live `applyBatch` entries are unaffected (they bind their\n * call-site adapter). If unset when a restored op applies, the op is a\n * debug-warned no-op. */\n setHistoryAdapter(fn: (() => unknown) | null): void;\n\n // Serialization\n /** Snapshot the current scene state to a JSON-serializable shape.\n * History (undo/redo stacks) is NOT captured. Function fields like\n * `ContainerNode.clipFromPose` are translated to string keys via the\n * scene's registry; throws if any function field has no matching key. */\n toJSON(): SerializedScene<TData, TLayer, TPose>;\n /** Replace this scene's entire node + layer state in place from a snapshot\n * produced by `toJSON()`. Unlike `sceneFromJSON`, the existing Scene\n * instance is preserved — holders such as `<SceneCanvas>` keep their\n * reference. History (undo/redo) is cleared, matching `sceneFromJSON`.\n * Bumps `getVersion()` and notifies subscribers exactly once.\n *\n * Throws on an unsupported version or unknown registry/layer ids; on a\n * malformed snapshot the scene is left empty or partially populated (callers should treat a\n * `loadState` throw as fatal and reload). Snapshots from `toJSON()` are\n * always well-formed. */\n loadState(json: SerializedScene<TData, TLayer, TPose>): void;\n\n // Subscription (used by useScene; also for non-React observers)\n subscribe(listener: () => void): () => void;\n /** Monotonically increasing version. Snapshot for `useSyncExternalStore`. */\n getVersion(): number;\n}\n"],"mappings":";AA8EA,IAAaA,KAAY,MAAsBC"}
@@ -1,39 +1,27 @@
1
1
  import { dlog as e } from "../../debug/flag.js";
2
2
  import { useLayoutEffect as t, useMemo as n, useRef as r, useState as i, useSyncExternalStore as a } from "react";
3
3
  import { useLatest as o } from "@weasel-js/react";
4
+ import { createSelectionStore as s, intentOf as c, select as l } from "@weasel-js/select";
4
5
  //#region src/core/selection/useSelection.ts
5
- function s(e) {
6
- let t = e, n = /* @__PURE__ */ new Set();
7
- return {
8
- getSelection: () => t,
9
- setSelection: (e) => {
10
- t = e;
11
- for (let e of n) e();
12
- },
13
- subscribe: (e) => (n.add(e), () => {
14
- n.delete(e);
15
- })
16
- };
17
- }
18
- function c(c = {}) {
19
- let { mode: l = "single", extend: u = "shift", initial: d = [], lock: f = !1, scene: p } = c, [m] = i(() => s([...d])), h = p ?? m, g = r(d);
20
- a(h.subscribe, () => h.getSelection());
21
- let _ = r(!1);
6
+ function u(u = {}) {
7
+ let { mode: d = "single", extend: f = "shift", initial: p = [], lock: m = !1, scene: h } = u, [g] = i(() => s([...p])), _ = h ?? g, v = r(p);
8
+ a(_.subscribe, () => _.getSelection());
9
+ let y = r(!1);
22
10
  t(() => {
23
- p && !_.current && (_.current = !0, g.current.length > 0 && p.getSelection().length === 0 && p.setSelection([...g.current]));
24
- }, [p]);
25
- let v = o({
26
- mode: l,
27
- extend: u,
28
- lock: f
11
+ h && !y.current && (y.current = !0, v.current.length > 0 && h.getSelection().length === 0 && h.setSelection([...v.current]));
12
+ }, [h]);
13
+ let b = o({
14
+ mode: d,
15
+ extend: f,
16
+ lock: m
29
17
  });
30
18
  return n(() => {
31
- let t = () => h.getSelection(), n = (n) => {
32
- v.current.lock || (e("selection", "set", {
19
+ let t = () => _.getSelection(), n = (n) => {
20
+ b.current.lock || (e("selection", "set", {
33
21
  from: t().length,
34
22
  to: n.length,
35
23
  ids: n
36
- }), h.setSelection(n));
24
+ }), _.setSelection(n));
37
25
  }, r = (e) => t().filter((t) => t !== e);
38
26
  return {
39
27
  get current() {
@@ -42,30 +30,36 @@ function c(c = {}) {
42
30
  get: t,
43
31
  set: n,
44
32
  add(e) {
45
- v.current.mode === "single" ? n([e]) : t().includes(e) || n([...t(), e]);
33
+ b.current.mode === "single" ? n([e]) : t().includes(e) || n([...t(), e]);
46
34
  },
47
35
  remove(e) {
48
36
  t().includes(e) && n(r(e));
49
37
  },
50
38
  toggle(e) {
51
- t().includes(e) ? n(r(e)) : n(v.current.mode === "single" ? [e] : [...t(), e]);
39
+ t().includes(e) ? n(r(e)) : n(b.current.mode === "single" ? [e] : [...t(), e]);
52
40
  },
53
41
  clear() {
54
42
  n([]);
55
43
  },
56
44
  contains: (e) => t().includes(e),
57
- applyClick(e, i) {
58
- let { mode: a, extend: o } = v.current;
59
- a === "multi" && i[o] ? n(t().includes(e) ? r(e) : [...t(), e]) : n([e]);
45
+ applyClick(e, r) {
46
+ let { mode: i, extend: a } = b.current;
47
+ n([...l({
48
+ ids: t(),
49
+ anchor: null
50
+ }, e, c(r, {
51
+ mode: i,
52
+ toggle: a
53
+ })).ids]);
60
54
  },
61
55
  adapterMethods: {
62
56
  getSelection: () => t(),
63
57
  setSelection: (e) => n(e)
64
58
  }
65
59
  };
66
- }, [h, v]);
60
+ }, [_, b]);
67
61
  }
68
62
  //#endregion
69
- export { c as useSelection };
63
+ export { u as useSelection };
70
64
 
71
65
  //# sourceMappingURL=useSelection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSelection.js","names":["createLocalStore","ids","initial","listeners","next","l","useSelection","opts","local","useState","store","scene","initialRef","useRef","seeded","optsRef","useLatest","useMemo","get","set","dlog","without","x","id","m","key","modifiers"],"sources":["../../../src/core/selection/useSelection.ts"],"sourcesContent":["import { useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport type { NodeId } from 'core/scene/types';\nimport { dlog } from 'debug/flag';\n\n/**\n * `SelectionApi`, `SelectionMode` and `SelectionExtendKey` are declared in\n * `@weasel-js/routing` — the `selection` dep and half the kit's actions are\n * typed in them. Re-exported here, beside the hook that returns one.\n */\nimport type { SelectionApi, SelectionMode, SelectionExtendKey } from '@weasel-js/routing';\nexport type { SelectionApi, SelectionMode, SelectionExtendKey };\n\n/** Somewhere selection can live outside this hook. `Scene` satisfies it;\n * so does any store with the same three methods. */\nexport interface SelectionStore {\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n subscribe(listener: () => void): () => void;\n}\n\n/** Options for {@link useSelection}. */\nexport interface UseSelectionOptions {\n /** Default `'single'`. */\n mode?: SelectionMode;\n /** Default `'shift'`. Ignored in single-mode. */\n extend?: SelectionExtendKey;\n /** Default `[]`. */\n initial?: readonly NodeId[];\n /** Keep the selection on this store rather than in the hook, so every\n * consumer of the same scene shares one selection and undo / redo can\n * restore it. `initial` then only seeds a store that has none yet.\n * Omit it and the hook owns a selection nobody else sees. */\n scene?: SelectionStore;\n /** When `true`, every mutator (`set`/`add`/`remove`/`toggle`/`clear`/\n * `applyClick`) is a no-op — selection stays at whatever `initial`\n * pinned it to. Useful for demos that exist to showcase a single\n * pre-selected node and don't want a\n * stray click to deselect. */\n lock?: boolean;\n}\n\n/** Where a hook with no `scene` keeps its selection, so `get()` reads one\n * store either way and a write is visible before the re-render it causes. */\nfunction createLocalStore(initial: readonly NodeId[]): SelectionStore {\n let ids: readonly NodeId[] = initial;\n const listeners = new Set<() => void>();\n return {\n getSelection: () => ids,\n setSelection: (next) => {\n ids = next;\n for (const l of listeners) l();\n },\n subscribe: (l) => {\n listeners.add(l);\n return () => { listeners.delete(l); };\n },\n };\n}\n\n/**\n * Default implementation of the `getSelection` / `setSelection` adapter\n * contract every action hook (delete, duplicate, nudge, group, ...) requires.\n *\n * Owns selection state, exposes a click-policy helper (single vs multi with\n * an extend key), and pre-builds the two adapter methods consumers otherwise\n * hand-roll in every demo:\n *\n * ```tsx\n * const selection = useSelection({ mode: 'multi' });\n * const adapter = { ...arrayAdapter({...}), ...selection.adapterMethods };\n * ```\n *\n * Returns the same object for as long as `scene` is the same store, so it is\n * safe as a memo or effect dependency. The calling component re-renders when\n * the selection changes; key anything derived from the ids on\n * `selection.current`.\n */\nexport function useSelection(opts: UseSelectionOptions = {}): SelectionApi {\n const { mode = 'single', extend = 'shift', initial = [], lock = false, scene } = opts;\n const [local] = useState(() => createLocalStore([...initial]));\n const store = scene ?? local;\n const initialRef = useRef(initial);\n\n useSyncExternalStore(store.subscribe, () => store.getSelection());\n\n // A store that already holds a selection wins: the hook is joining it, not\n // resetting it. In an effect, not during render — the store has other\n // subscribers.\n const seeded = useRef(false);\n useLayoutEffect(() => {\n if (!scene || seeded.current) return;\n seeded.current = true;\n if (initialRef.current.length > 0 && scene.getSelection().length === 0) {\n scene.setSelection([...initialRef.current]);\n }\n }, [scene]);\n\n const optsRef = useLatest({ mode, extend, lock });\n\n return useMemo<SelectionApi>(() => {\n const get = (): NodeId[] => store.getSelection() as NodeId[];\n const set = (ids: NodeId[]): void => {\n if (optsRef.current.lock) return;\n dlog('selection', 'set', { from: get().length, to: ids.length, ids });\n store.setSelection(ids);\n };\n const without = (id: NodeId) => get().filter((x) => x !== id);\n return {\n get current() { return get(); },\n get,\n set,\n add(id) {\n if (optsRef.current.mode === 'single') set([id]);\n else if (!get().includes(id)) set([...get(), id]);\n },\n remove(id) {\n if (get().includes(id)) set(without(id));\n },\n toggle(id) {\n if (get().includes(id)) set(without(id));\n else set(optsRef.current.mode === 'single' ? [id] : [...get(), id]);\n },\n clear() { set([]); },\n contains: (id) => get().includes(id),\n applyClick(id, modifiers) {\n const { mode: m, extend: key } = optsRef.current;\n if (m === 'multi' && modifiers[key]) set(get().includes(id) ? without(id) : [...get(), id]);\n else set([id]);\n },\n adapterMethods: {\n getSelection: () => get(),\n setSelection: (ids: NodeId[]) => set(ids),\n },\n };\n }, [store, optsRef]);\n}\n"],"mappings":";;;;AA4CA,SAASA,EAAiB,GAA4C;CACpE,IAAIC,IAAyBC,GACvBC,oBAAY,IAAI,IAAgB;CACtC,OAAO;EACL,oBAAoBF;EACpB,eAAe,MAAS;GACtB,IAAMG;GACN,KAAK,IAAMC,KAAKF,GAAW,EAAE;EAC/B;EACA,YAAY,OACVA,EAAU,IAAIE,CAAC,SACF;GAAE,EAAU,OAAOA,CAAC;EAAG;CAExC;AACF;AAoBA,SAAgBC,EAAa,IAA4B,CAAC,GAAiB;CACzE,IAAM,EAAE,UAAO,UAAU,YAAS,SAAS,aAAU,CAAC,GAAG,UAAO,IAAO,aAAUC,GAC3E,CAACC,KAASC,QAAeT,EAAiB,CAAC,GAAGE,CAAO,CAAC,CAAC,GACvDQ,IAAQC,KAASH,GACjBI,IAAaC,EAAOX,CAAO;CAEjC,EAAqBQ,EAAM,iBAAiBA,EAAM,aAAa,CAAC;CAKhE,IAAMI,IAASD,EAAO,EAAK;CAC3B,QAAsB;EACpB,AAAKF,KAAS,GAAO,YACrB,EAAO,UAAU,IACbC,EAAW,QAAQ,SAAS,KAAKD,EAAM,aAAa,CAAC,CAAC,WAAW,KACnEA,EAAM,aAAa,CAAC,GAAGC,EAAW,OAAO,CAAC;CAE9C,GAAG,CAACD,CAAK,CAAC;CAEV,IAAMI,IAAUC,EAAU;EAAE;EAAM;EAAQ;CAAK,CAAC;CAEhD,OAAOC,QAA4B;EACjC,IAAMC,UAAsBR,EAAM,aAAa,GACzCS,KAAO,MAAwB;GACnC,AAAIJ,EAAQ,QAAQ,SACpBK,EAAK,aAAa,OAAO;IAAE,MAAMF,EAAI,CAAC,CAAC;IAAQ,IAAIjB,EAAI;IAAQ;GAAI,CAAC,GACpES,EAAM,aAAaT,CAAG;EACxB,GACMoB,KAAW,MAAeH,EAAI,CAAC,CAAC,QAAQ,MAAMI,MAAMC,CAAE;EAC5D,OAAO;GACL,IAAI,UAAU;IAAE,OAAOL,EAAI;GAAG;GAC9B;GACA;GACA,IAAI,GAAI;IACN,AAAIH,EAAQ,QAAQ,SAAS,WAAUI,EAAI,CAACI,CAAE,CAAC,IACrCL,EAAI,CAAC,CAAC,SAASK,CAAE,KAAGJ,EAAI,CAAC,GAAGD,EAAI,GAAGK,CAAE,CAAC;GAClD;GACA,OAAO,GAAI;IACT,AAAIL,EAAI,CAAC,CAAC,SAASK,CAAE,KAAGJ,EAAIE,EAAQE,CAAE,CAAC;GACzC;GACA,OAAO,GAAI;IACT,AAAIL,EAAI,CAAC,CAAC,SAASK,CAAE,IAAGJ,EAAIE,EAAQE,CAAE,CAAC,IAClCJ,EAAIJ,EAAQ,QAAQ,SAAS,WAAW,CAACQ,CAAE,IAAI,CAAC,GAAGL,EAAI,GAAGK,CAAE,CAAC;GACpE;GACA,QAAQ;IAAE,EAAI,CAAC,CAAC;GAAG;GACnB,WAAW,MAAOL,EAAI,CAAC,CAAC,SAASK,CAAE;GACnC,WAAW,GAAI,GAAW;IACxB,IAAM,EAAE,MAAMC,GAAG,QAAQC,MAAQV,EAAQ;IACzC,AAAIS,MAAM,WAAWE,EAAUD,KAAMN,EAAID,EAAI,CAAC,CAAC,SAASK,CAAE,IAAIF,EAAQE,CAAE,IAAI,CAAC,GAAGL,EAAI,GAAGK,CAAE,CAAC,IACrFJ,EAAI,CAACI,CAAE,CAAC;GACf;GACA,gBAAgB;IACd,oBAAoBL,EAAI;IACxB,eAAe,MAAkBC,EAAIlB,CAAG;GAC1C;EACF;CACF,GAAG,CAACS,GAAOK,CAAO,CAAC;AACrB"}
1
+ {"version":3,"file":"useSelection.js","names":["useSelection","opts","local","useState","createSelectionStore","initial","store","scene","initialRef","useRef","seeded","optsRef","useLatest","useMemo","get","set","dlog","ids","without","x","id","m","key","select","intentOf","modifiers"],"sources":["../../../src/core/selection/useSelection.ts"],"sourcesContent":["import { useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { useLatest } from '@weasel-js/react';\nimport { createSelectionStore, intentOf, select, type SelectionStore as Store } from '@weasel-js/select';\nimport type { NodeId } from 'core/scene/types';\nimport { dlog } from 'debug/flag';\n\n/**\n * `SelectionApi`, `SelectionMode` and `SelectionExtendKey` are declared in\n * `@weasel-js/routing` — the `selection` dep and half the kit's actions are\n * typed in them. Re-exported here, beside the hook that returns one.\n */\nimport type { SelectionApi, SelectionMode, SelectionExtendKey } from '@weasel-js/routing';\nexport type { SelectionApi, SelectionMode, SelectionExtendKey };\n\n/** Somewhere selection can live outside this hook. `Scene` satisfies it;\n * so does any store with the same three methods. */\nexport type SelectionStore = Store<NodeId>;\n\n/** Options for {@link useSelection}. */\nexport interface UseSelectionOptions {\n /** Default `'single'`. */\n mode?: SelectionMode;\n /** Default `'shift'`. Ignored in single-mode. */\n extend?: SelectionExtendKey;\n /** Default `[]`. */\n initial?: readonly NodeId[];\n /** Keep the selection on this store rather than in the hook, so every\n * consumer of the same scene shares one selection and undo / redo can\n * restore it. `initial` then only seeds a store that has none yet.\n * Omit it and the hook owns a selection nobody else sees. */\n scene?: SelectionStore;\n /** When `true`, every mutator (`set`/`add`/`remove`/`toggle`/`clear`/\n * `applyClick`) is a no-op — selection stays at whatever `initial`\n * pinned it to. Useful for demos that exist to showcase a single\n * pre-selected node and don't want a\n * stray click to deselect. */\n lock?: boolean;\n}\n\n/**\n * Default implementation of the `getSelection` / `setSelection` adapter\n * contract every action hook (delete, duplicate, nudge, group, ...) requires.\n *\n * Owns selection state, exposes a click-policy helper (single vs multi with\n * an extend key), and pre-builds the two adapter methods consumers otherwise\n * hand-roll in every demo:\n *\n * ```tsx\n * const selection = useSelection({ mode: 'multi' });\n * const adapter = { ...arrayAdapter({...}), ...selection.adapterMethods };\n * ```\n *\n * Returns the same object for as long as `scene` is the same store, so it is\n * safe as a memo or effect dependency. The calling component re-renders when\n * the selection changes; key anything derived from the ids on\n * `selection.current`.\n */\nexport function useSelection(opts: UseSelectionOptions = {}): SelectionApi {\n const { mode = 'single', extend = 'shift', initial = [], lock = false, scene } = opts;\n // Without a `scene` the hook still keeps its ids in a store, so `get()` reads one store either\n // way and a write is visible before the re-render it causes.\n const [local] = useState(() => createSelectionStore<NodeId>([...initial]));\n const store = scene ?? local;\n const initialRef = useRef(initial);\n\n useSyncExternalStore(store.subscribe, () => store.getSelection());\n\n // A store that already holds a selection wins: the hook is joining it, not\n // resetting it. In an effect, not during render — the store has other\n // subscribers.\n const seeded = useRef(false);\n useLayoutEffect(() => {\n if (!scene || seeded.current) return;\n seeded.current = true;\n if (initialRef.current.length > 0 && scene.getSelection().length === 0) {\n scene.setSelection([...initialRef.current]);\n }\n }, [scene]);\n\n const optsRef = useLatest({ mode, extend, lock });\n\n return useMemo<SelectionApi>(() => {\n const get = (): NodeId[] => store.getSelection() as NodeId[];\n const set = (ids: NodeId[]): void => {\n if (optsRef.current.lock) return;\n dlog('selection', 'set', { from: get().length, to: ids.length, ids });\n store.setSelection(ids);\n };\n const without = (id: NodeId) => get().filter((x) => x !== id);\n return {\n get current() { return get(); },\n get,\n set,\n add(id) {\n if (optsRef.current.mode === 'single') set([id]);\n else if (!get().includes(id)) set([...get(), id]);\n },\n remove(id) {\n if (get().includes(id)) set(without(id));\n },\n toggle(id) {\n if (get().includes(id)) set(without(id));\n else set(optsRef.current.mode === 'single' ? [id] : [...get(), id]);\n },\n clear() { set([]); },\n contains: (id) => get().includes(id),\n applyClick(id, modifiers) {\n const { mode: m, extend: key } = optsRef.current;\n set([...select({ ids: get(), anchor: null }, id, intentOf(modifiers, { mode: m, toggle: key })).ids]);\n },\n adapterMethods: {\n getSelection: () => get(),\n setSelection: (ids: NodeId[]) => set(ids),\n },\n };\n }, [store, optsRef]);\n}\n"],"mappings":";;;;;AAyDA,SAAgBA,EAAa,IAA4B,CAAC,GAAiB;CACzE,IAAM,EAAE,UAAO,UAAU,YAAS,SAAS,aAAU,CAAC,GAAG,UAAO,IAAO,aAAUC,GAG3E,CAACC,KAASC,QAAeC,EAA6B,CAAC,GAAGC,CAAO,CAAC,CAAC,GACnEC,IAAQC,KAASL,GACjBM,IAAaC,EAAOJ,CAAO;CAEjC,EAAqBC,EAAM,iBAAiBA,EAAM,aAAa,CAAC;CAKhE,IAAMI,IAASD,EAAO,EAAK;CAC3B,QAAsB;EACpB,AAAKF,KAAS,GAAO,YACrB,EAAO,UAAU,IACbC,EAAW,QAAQ,SAAS,KAAKD,EAAM,aAAa,CAAC,CAAC,WAAW,KACnEA,EAAM,aAAa,CAAC,GAAGC,EAAW,OAAO,CAAC;CAE9C,GAAG,CAACD,CAAK,CAAC;CAEV,IAAMI,IAAUC,EAAU;EAAE;EAAM;EAAQ;CAAK,CAAC;CAEhD,OAAOC,QAA4B;EACjC,IAAMC,UAAsBR,EAAM,aAAa,GACzCS,KAAO,MAAwB;GACnC,AAAIJ,EAAQ,QAAQ,SACpBK,EAAK,aAAa,OAAO;IAAE,MAAMF,EAAI,CAAC,CAAC;IAAQ,IAAIG,EAAI;IAAQ;GAAI,CAAC,GACpEX,EAAM,aAAaW,CAAG;EACxB,GACMC,KAAW,MAAeJ,EAAI,CAAC,CAAC,QAAQ,MAAMK,MAAMC,CAAE;EAC5D,OAAO;GACL,IAAI,UAAU;IAAE,OAAON,EAAI;GAAG;GAC9B;GACA;GACA,IAAI,GAAI;IACN,AAAIH,EAAQ,QAAQ,SAAS,WAAUI,EAAI,CAACK,CAAE,CAAC,IACrCN,EAAI,CAAC,CAAC,SAASM,CAAE,KAAGL,EAAI,CAAC,GAAGD,EAAI,GAAGM,CAAE,CAAC;GAClD;GACA,OAAO,GAAI;IACT,AAAIN,EAAI,CAAC,CAAC,SAASM,CAAE,KAAGL,EAAIG,EAAQE,CAAE,CAAC;GACzC;GACA,OAAO,GAAI;IACT,AAAIN,EAAI,CAAC,CAAC,SAASM,CAAE,IAAGL,EAAIG,EAAQE,CAAE,CAAC,IAClCL,EAAIJ,EAAQ,QAAQ,SAAS,WAAW,CAACS,CAAE,IAAI,CAAC,GAAGN,EAAI,GAAGM,CAAE,CAAC;GACpE;GACA,QAAQ;IAAE,EAAI,CAAC,CAAC;GAAG;GACnB,WAAW,MAAON,EAAI,CAAC,CAAC,SAASM,CAAE;GACnC,WAAW,GAAI,GAAW;IACxB,IAAM,EAAE,MAAMC,GAAG,QAAQC,MAAQX,EAAQ;IACzC,EAAI,CAAC,GAAGY,EAAO;KAAE,KAAKT,EAAI;KAAG,QAAQ;IAAK,GAAGM,GAAII,EAASC,GAAW;KAAE,MAAMJ;KAAG,QAAQC;IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;GACtG;GACA,gBAAgB;IACd,oBAAoBR,EAAI;IACxB,eAAe,MAAkBC,EAAIE,CAAG;GAC1C;EACF;CACF,GAAG,CAACX,GAAOK,CAAO,CAAC;AACrB"}
@@ -0,0 +1,8 @@
1
+ //#region src/core/stableStringify.ts
2
+ function e(e) {
3
+ return JSON.stringify(e, (e, t) => t && typeof t == "object" && !Array.isArray(t) ? Object.fromEntries(Object.entries(t).sort(([e], [t]) => e < t ? -1 : 1)) : t);
4
+ }
5
+ //#endregion
6
+ export { e as stableStringify };
7
+
8
+ //# sourceMappingURL=stableStringify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stableStringify.js","names":["stableStringify","value","v","a","b"],"sources":["../../src/core/stableStringify.ts"],"sourcesContent":["/** JSON with object keys sorted, so two equal values produce one string. */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, (_key, v) =>\n v && typeof v === 'object' && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))\n : v,\n );\n}\n"],"mappings":";AACA,SAAgBA,EAAgB,GAAwB;CACtD,OAAO,KAAK,UAAUC,IAAQ,GAAM,MAClCC,KAAK,OAAOA,KAAM,YAAY,CAAC,MAAM,QAAQA,CAAC,IAC1C,OAAO,YAAY,OAAO,QAAQA,CAAC,CAAC,CAAC,MAAM,CAACC,IAAI,CAACC,OAAQD,IAAIC,IAAI,KAAK,CAAE,CAAC,IACzEF,CACN;AACF"}