@weasel-js/core 1.8.0 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"scene.js","names":["rebuildGlobalOp","defaultIdCounter","defaultGenerateId","asNodeId","setParallax","to","record","layerFromSerialized","base","spec","createScene","options","state","registry","withKitRegistry","fnFields","createNodeFnFields","fnField","f","name","layoutFrame","resolveLayoutFrame","hasLayouts","field","write","node","fn","layoutOfInternal","id","dependents","createDependentsIndex","childDerived","invalidateDependents","invalidateChildDerivedFrom","subtree","src","dep","dropPoseKeyedMemoSlots","cursor","start","d","trackChildDerived","dependsOn","retarget","requireNode","i","generateId","listeners","registered","historyAdapterAccessor","bindOpToHistoryAdapter","op","get","dwarn","err","selection","overrides","createPoseOverrides","history","createHistory","reachable","ids","notify","pruneCacheForDroppedOps","entry","makeOp","args","createArrangeOp","writePose","rebuilt","rebuildOp","version","incarnations","nextIncarnation","batchDepth","currentBatch","suppressRecording","untrackedDepth","lockBypass","appliedLog","batchDirty","activeJournalAccessor","arrivalHandler","arrivals","departures","changed","reflowDue","reflowListeners","declaredLayouts","runLayoutPass","scene","arrived","touched","departed","activeHandler","noteArrival","parent","from","list","noteDeparture","noteChange","bareLayoutEdit","openArrivals","always","emitReflow","moves","listener","settleArrivals","pending","handler","landed","still","left","gone","poses","SceneArrivalRefused","out","pose","givesLayout","withArrivalOps","ops","runArrivalEdit","all","run","owned","isLockedInternal","l","cur","refuseUntracked","verb","refuseLocked","refuseLockedLayer","layer","withLocksLifted","atomically","outer","log","selectionBefore","result","ownsEntry","kind","payload","n","requireLayerIndex","rebuildLayerIndex","invalidateOrder","assertSubtreeLayer","nodeLayer","parentLayer","action","nodeId","parentId","siblingsOf","p","detach","sibs","idx","attach","index","descendants","c","removalClosure","removing","take","sub","s","root","rootIds","patchNodeFunctions","cacheForRedo","restoreNodeFunctions","keys","target","key","restoreFn","registerKitOp","cached","k","clone","layoutRefs","placeLayout","live","side","layout","rec","runOp","coalesceKeyFor","dir","bindOpToAdapter","adapter","token","withRecordingSuppressed","prevSuppress","prevDirty","executeAndLog","label","h","renderOrderInternal","renderOrderFlat","renderOrderBucketed","renderOrderNodesInternal","renderOrderNodesFlat","renderOrderNodesBucketed","structureGeneration","orderCache","EMPTY_NODES","currentOrderCache","only","stack","buckets","bucket","rawJournals","wrapJournal","wrapped","raw","sceneHistory","opts","snapshot","journal","applyBatchNow","byLayer","fnKeysOf","nid","detached","r","fnKeys","patch","resized","parentNode","curId","sid","fromKey","toKey","desc","fromSibs","fromIndex","toSibs","toIndex","visible","locked","parallax","clamped","tagged","finalIndex","proposed","tempIndex","e","undo","redo","total","targetIndex","outermost","ownsArrivals","finished","versionBefore","nodes","specs","specsFromSerialized","json","applyConstructionSpecs","serialized","NODE_FN_FIELDS","sceneSelectionStore","sceneFromJSON"],"sources":["../../../src/core/scene/scene.ts"],"sourcesContent":["import { createHistory, type History, type HistorySelection, type Journal, type SerializedHistory } from '@weasel-js/history';\nimport type { Op } from 'core/ops/types';\nimport type { ParallaxOpts } from 'core/viewport/parallax';\nimport { rebuildOp as rebuildGlobalOp } from 'core/ops/registry';\nimport { createArrangeOp, type ArrangeArgs, type ArrangedPose } from 'core/ops/arrange';\nimport { SceneArrivalRefused } from './arrivals';\nimport { dwarn } from 'debug/flag';\nimport { createDependentsIndex, sameDependsOn } from './dependents';\nimport { withKitRegistry } from './kitRegistry';\nimport { dropPoseKeyedMemoSlots } from './nodeMemo';\nimport {\n createNodeFnFields,\n fnKeysOf,\n restoreFn,\n NODE_FN_FIELDS,\n type FnBearingNode,\n type NodeFn,\n type NodeFnField,\n} from './nodeFnFields';\nimport { createPoseOverrides } from './poseOverrides';\nimport { resized, resolveLayoutFrame, runLayoutPass } from './layoutPass';\nimport type { LayoutStrategy } from '../../layout/types';\nimport {\n asNodeId,\n type LayoutMove,\n type AddNodeSpec,\n type ContainerNode,\n type LayerRecord,\n type LeafNode,\n type Node,\n type NodeId,\n type RegisteredOp,\n type Scene,\n type SceneArrivalHandler,\n type SceneRegistry,\n type SerializedNode,\n type SerializedScene,\n type SerializedLayer,\n type UseSceneOptions,\n type UserLayerRecord,\n} from './types';\n\ninterface SceneState<TData, TLayer extends string, TPose> {\n nodes: Map<NodeId, Node<TData, TLayer, TPose>>;\n roots: NodeId[];\n layers: LayerRecord<TLayer>[];\n layerIndex: Map<TLayer, number>;\n}\n\nlet defaultIdCounter = 0;\nconst defaultGenerateId = (): NodeId =>\n asNodeId(`n${(defaultIdCounter++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`);\n\n/** One layer record from its snapshot form. A snapshot with no `kind` predates\n * user layers, so everything in it was a system layer. */\nfunction setParallax(record: { parallax?: ParallaxOpts }, to: ParallaxOpts | undefined): void {\n if (to === undefined) delete record.parallax;\n else record.parallax = to;\n}\n\nfunction layerFromSerialized<TLayer extends string>(\n spec: SerializedLayer<TLayer>,\n): LayerRecord<TLayer> {\n const base = {\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n return spec.kind === 'user'\n ? { ...base, kind: 'user', name: spec.name ?? spec.id }\n : { ...base, kind: 'system' };\n}\n\n/** Build a scene outside React. `useScene` is the usual entry point; reach for\n * this in tests, in headless rendering, or wherever a scene must outlive a\n * component. Throws if no system layers are declared. */\nexport function createScene<TData, TLayer extends string, TPose = import('../../features/groups/composePose').RectPose>(\n options: UseSceneOptions<TData, TLayer, TPose>,\n): Scene<TData, TLayer, TPose> {\n if (!options.systemLayers || options.systemLayers.length === 0) {\n throw new Error('useScene: systemLayers must declare at least one layer');\n }\n\n // ── State ──────────────────────────────────────────────────────────────\n const state: SceneState<TData, TLayer, TPose> = {\n nodes: new Map(),\n roots: [],\n layers: [],\n layerIndex: new Map(),\n };\n\n // The kit's own registry entries sit under the consumer's, so a snapshot\n // carrying a kit-attached function (a grouped container's derived pose)\n // reloads in any scene, not only one whose consumer registered the key.\n const registry = withKitRegistry(options.registry ?? {});\n\n /**\n * The registry-keyed function fields — `clipFromPose`, `derivePath`,\n * `derivePose` — each with its key maps and the side-channel cache the\n * `kit:add` redo path re-attaches from. A function cannot travel through a\n * serializable op payload, so `scene.add` and the `initial` loader stash it\n * here and the replayed op reads it back.\n *\n * Those caches are pruned at two hook points, both delivered via the history\n * engine's `onEvict`, to prevent unbounded growth:\n * 1. When the redo stack is cleared by a new op (branch-on-edit): any\n * kit:add in the discarded entries that references a node absent from\n * `state.nodes` is permanently unreachable — its cache entry is dropped.\n * 2. When the undo stack overflows `historyLimit` and evicts the oldest\n * entry: same reasoning applies to the evicted entries.\n * Invariant: after pruning, no entry remains for a node that is both absent\n * from `state.nodes` AND unreachable via any remaining undo/redo log entry.\n */\n const fnFields = createNodeFnFields<TPose>(registry);\n const fnField = (name: 'clipFromPose' | 'derivePath' | 'derivePose' | 'layout'): NodeFnField =>\n fnFields.find((f) => f.spec.field === name)!;\n\n /** How declared layouts are measured; see `LayoutFrame`. */\n const layoutFrame = resolveLayoutFrame(options.layoutFrame);\n /** Latched on the first layout a container is given, so a scene that never\n * declares one records exactly the entries it did before layouts existed. */\n let hasLayouts = false;\n {\n const field = fnField('layout');\n const write = field.write;\n (field as { write: NodeFnField['write'] }).write = (node, fn) => {\n if (node.kind === 'container') hasLayouts = true;\n write(node, fn);\n };\n }\n\n function layoutOfInternal(id: NodeId) {\n const node = state.nodes.get(id);\n return node?.kind === 'container' ? (node.layout ?? null) : null;\n }\n\n /** Maintained from `kit:add` / `kit:remove` — the only two places a node is\n * created or destroyed, and unlike `add`/`remove` they replay on undo/redo.\n * Only explicit `dependsOn` id lists are registered here; `'children'` is\n * the ancestor walk in `invalidateDependents` instead. */\n const dependents = createDependentsIndex();\n\n /** Nodes carrying `dependsOn: 'children'`. Empty in every scene that has no\n * container hugging its contents, which is what keeps the ancestor walk off\n * the hot path. */\n const childDerived = new Set<NodeId>();\n\n /** Walks `id`'s whole subtree. Not required while `Scene` stores absolute\n * poses and the render walks compose nothing; it is here so `derivePath`'s\n * world-pose contract still holds if they ever do. */\n function invalidateDependents(id: NodeId): void {\n invalidateChildDerivedFrom(state.nodes.get(id)?.parent ?? null);\n if (dependents.isEmpty()) return;\n const subtree: NodeId[] = [id];\n descendants(id, subtree);\n for (const src of subtree) {\n for (const dep of dependents.transitiveDependentsOf(src)) {\n const node = state.nodes.get(dep);\n if (node !== undefined) dropPoseKeyedMemoSlots(node);\n }\n }\n }\n\n /** A `dependsOn: 'children'` container derives from nodes the reverse index\n * never sees, so its invalidation runs the other way: up the parent chain\n * from `start` inclusive, and on to each such ancestor's own dependents.\n *\n * Callers that removed or reparented a node pass the parent explicitly —\n * a gone node cannot say who its parent was. */\n function invalidateChildDerivedFrom(start: NodeId | null): void {\n if (childDerived.size === 0) return;\n let cursor = start;\n while (cursor !== null) {\n const node = state.nodes.get(cursor);\n if (node === undefined) return;\n if (childDerived.has(cursor)) {\n dropPoseKeyedMemoSlots(node);\n for (const dep of dependents.transitiveDependentsOf(cursor)) {\n const d = state.nodes.get(dep);\n if (d !== undefined) dropPoseKeyedMemoSlots(d);\n }\n }\n cursor = node.parent;\n }\n }\n\n /** Track (or forget) a node whose `dependsOn` is `'children'`. Paired with\n * `dependents.add` / `.remove` at every site a node is created or destroyed. */\n function trackChildDerived(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n if (dependsOn === 'children') childDerived.add(id);\n else childDerived.delete(id);\n }\n\n /** Point `id` at a different set of dependencies, keeping both indices and\n * every memo that reads them in step. Shared by `kit:setDependsOn`'s two\n * directions, which differ only in which value they install.\n *\n * `id`'s own memo is dropped as well as its dependents': its derivation now\n * reads different sources, and nothing else would clear it. */\n function retarget(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n const node = requireNode(id) as { dependsOn?: readonly NodeId[] | 'children' };\n if (dependsOn === undefined) delete node.dependsOn;\n else node.dependsOn = dependsOn;\n dependents.add(id, dependsOn === undefined || dependsOn === 'children' ? [] : dependsOn);\n trackChildDerived(id, dependsOn);\n dropPoseKeyedMemoSlots(requireNode(id));\n invalidateDependents(id);\n }\n\n for (let i = 0; i < options.systemLayers.length; i++) {\n const spec = options.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`useScene: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push({\n kind: 'system',\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n });\n state.layerIndex.set(spec.id, i);\n }\n\n const generateId = options.generateId ?? defaultGenerateId;\n\n const listeners = new Set<() => void>();\n const registered = new Map<string, RegisteredOp<unknown>>();\n\n // Accessor for the adapter restored external ops apply against.\n let historyAdapterAccessor: (() => unknown) | null = null;\n\n /** Wrap a globally-rebuilt external op so apply resolves the history\n * adapter lazily — wiring order vs restoreHistory doesn't matter. An\n * unset accessor makes the op a debug-warned no-op, and an apply that\n * throws (e.g. the wired adapter lacks a method the op calls) degrades\n * the same way — never throws mid-undo, matching the placeholder\n * degradation policy. (The engine pops entries before applying, so an\n * uncaught throw would corrupt the stacks.) See `bindOpToAdapter` for\n * the live `applyBatch` path (fixed call-site adapter). */\n function bindOpToHistoryAdapter(op: Op): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => {\n const get = historyAdapterAccessor;\n if (!get) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" has no history adapter — skipping (setHistoryAdapter was not wired)`);\n return 'noop';\n }\n try {\n return op.apply(get());\n } catch (err) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" failed against the history adapter — skipping: ${String(err)}`);\n return 'noop';\n }\n },\n invert: () => bindOpToHistoryAdapter(op.invert()),\n };\n }\n\n // The scene's undo/redo engine. Recorded ops are `makeOp` wrappers over\n // `registered` handlers, so the engine's adapter argument is unused (the\n /** The transient set of active ids. Deliberately not part of `state`:\n * selection is not document content and never reaches `toJSON`. It is\n * handed to the history engine so entries can restore it. */\n let selection: readonly NodeId[] = [];\n\n /** Ephemeral per-node overrides. Deliberately not part of `state`, for the\n * same reason `selection` isn't: not document content, never reaches\n * `toJSON`, and never touches history. */\n const overrides = createPoseOverrides<TPose>(\n (id) => state.nodes.get(id),\n invalidateDependents,\n );\n\n // wrappers close over their payloads). Eviction (branch-edit redo-clears\n // + historyLimit overflow) drives function-field cache pruning via onEvict.\n const history = createHistory(undefined, {\n selection: {\n get: () => selection,\n set: (ids) => { selection = reachable(ids as readonly NodeId[]); notify(); },\n },\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n onEvict: (entry) => {\n // forwardOps and baseOps are the same array until a coalesce splits\n // them, so the double scan is cheap today and correct later.\n pruneCacheForDroppedOps(entry.forwardOps);\n pruneCacheForDroppedOps(entry.baseOps);\n },\n // Restore-time rebuild: scene-registered kinds (kit:* + consumer\n // registerOp) rebuild via makeOp; external ops rebuild via the global\n // op-factory registry, wrapped in the lazy history-adapter binding.\n // Return null only when the global registry also misses — the engine\n // then places its no-op placeholder. (The engine's own global-registry\n // fallback never fires for scene histories: this hook already\n // consulted it.)\n rebuildOp: (name, args) => {\n if (registered.has(name)) return makeOp(name, args);\n // Its writes are the scene's own, so it replays without an adapter.\n if (name === 'arrange') return createArrangeOp(args as ArrangeArgs, undefined, writePose);\n const rebuilt = rebuildGlobalOp(name, args);\n return rebuilt === null ? null : bindOpToHistoryAdapter(rebuilt);\n },\n });\n\n let version = 0;\n // Keyed by node object: every entry into `state.nodes` is a fresh object and\n // every edit mutates it in place, which is exactly an incarnation's lifetime.\n const incarnations = new WeakMap<object, number>();\n let nextIncarnation = 1;\n let batchDepth = 0;\n let currentBatch: { label: string; ops: Op[]; selectionBefore: readonly NodeId[] } | null = null;\n /** True while the history engine drives mutations (undo/redo/goto, journal\n * routing) — suppresses scene-side history recording so engine-applied\n * ops that re-enter scene mutation methods don't record twice. */\n let suppressRecording = false;\n /** Above zero inside `scene.untracked`, where the APIs that exist to\n * record refuse rather than record. */\n let untrackedDepth = 0;\n /** Above zero while the lock guard is lifted: `unlocked()`, `removeLayer`,\n * and every replay — undo, redo, a journal stepping, a rollback — which\n * restores a state that was legal when it was recorded. */\n let lockBypass = 0;\n /** Every kit op applied since the innermost `atomically` opened, so a\n * refused batch can revert what it already did. Null outside one. */\n let appliedLog: { kind: string; payload: unknown }[] | null = null;\n\n // ── Helpers ────────────────────────────────────────────────────────────\n // When `batchDepth > 0` the per-op `notify()` is coalesced: we still bump\n // the version so getVersion() reflects in-progress mutations, but we defer\n // listener dispatch until the outermost batch closes. This avoids one\n // React re-render per op during high-frequency gestures (e.g. snap moves\n // that emit ~10 transform ops per pointer-move).\n let batchDirty = false;\n // Mutable accessor for the active journal — seeded from options and\n // swappable via `scene.setActiveJournalAccessor(fn)` so mode machines that\n // depend on `scene.history` can wire it after construction.\n let activeJournalAccessor: (() => Journal | null) | null =\n options.getActiveJournal ?? null;\n\n // Container layout. `arrivals` is open (non-null) while a live edit is\n // collecting the nodes that joined a container, and `changed` every\n // container whose children or size it changed; whoever opened the window\n // settles it before the edit closes. Undo, redo and journal replays never\n // open it: they restore an arrangement that was already decided.\n let arrivalHandler: SceneArrivalHandler<TPose> | null = null;\n let arrivals: Map<NodeId, NodeId[]> | null = null;\n let departures = new Map<NodeId, NodeId[]>();\n let changed = new Set<NodeId>();\n /** What the last settle wrote, reported to `onReflow` once its edit lands. */\n let reflowDue: LayoutMove<TPose>[] | null = null;\n const reflowListeners = new Set<(moves: readonly LayoutMove<TPose>[]) => void>();\n\n /** The pass a scene runs over its declared layouts when nothing else is\n * installed. */\n const declaredLayouts: SceneArrivalHandler<TPose> = (arrived, touched, departed) =>\n runLayoutPass(scene, layoutOfInternal, arrived, touched, layoutFrame, departed);\n\n function activeHandler(): SceneArrivalHandler<TPose> | null {\n return arrivalHandler ?? (hasLayouts ? declaredLayouts : null);\n }\n\n function noteArrival(id: NodeId, parent: NodeId | null, from: NodeId | null): void {\n if (arrivals === null || parent === null || parent === from) return;\n changed.add(parent);\n const list = arrivals.get(parent);\n if (list === undefined) arrivals.set(parent, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n function noteDeparture(id: NodeId, from: NodeId | null, to: NodeId | null): void {\n if (arrivals === null || from === null || from === to) return;\n changed.add(from);\n // One that joined earlier in this edit was never there to leave.\n if (arrivals.get(from)?.includes(id)) return;\n const list = departures.get(from);\n if (list === undefined) departures.set(from, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n /** A container's child set or order changed, or it changed size. */\n function noteChange(id: NodeId | null): void {\n if (arrivals !== null && id !== null) changed.add(id);\n }\n\n /** Whether a bare scene call has to run as a batch of its own, so the\n * layout pass it triggers lands in its undo step. */\n function bareLayoutEdit(): boolean {\n return activeHandler() !== null && arrivals === null && batchDepth === 0 && !suppressRecording;\n }\n\n /** Open the arrival window when a handler wants one — or `always`, for an\n * edit that may give the scene its first layout partway through — and no\n * enclosing edit holds it already; true when this caller now owns it. */\n function openArrivals(always = false): boolean {\n if (arrivals !== null || (!always && activeHandler() === null)) return false;\n arrivals = new Map();\n departures = new Map();\n changed = new Set();\n reflowDue = null;\n return true;\n }\n\n /** Report what the settled edit wrote, now that it has landed. */\n function emitReflow(): void {\n const moves = reflowDue;\n reflowDue = null;\n if (moves === null || moves.length === 0) return;\n for (const listener of [...reflowListeners]) listener(moves);\n }\n\n /** Close the window and ask the handler what the arrivals get. Throws\n * `SceneArrivalRefused` when it refuses, which reverts the edit. */\n function settleArrivals(): ArrangedPose[] {\n const pending = arrivals;\n arrivals = null;\n const handler = activeHandler();\n if (pending === null || handler === null) return [];\n // Only what is still there once the edit's other mutations have landed.\n const landed = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of pending) {\n const still = ids.filter((id) => state.nodes.get(id)?.parent === parent);\n if (still.length > 0 && state.nodes.has(parent)) landed.set(parent, still);\n }\n // Only what is gone from the container once the edit has landed: a child\n // that left and came back did not depart.\n const left = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of departures) {\n const gone = ids.filter((id) => state.nodes.get(id)?.parent !== parent);\n if (gone.length > 0 && state.nodes.has(parent)) left.set(parent, gone);\n }\n departures = new Map();\n const touched = new Set([...changed].filter((id) => state.nodes.get(id)?.kind === 'container'));\n if (landed.size === 0 && touched.size === 0) return [];\n const poses = handler(landed, touched, left);\n if (poses === null) throw new SceneArrivalRefused(landed);\n const out: ArrangedPose[] = [];\n for (const [id, to] of poses) {\n const node = state.nodes.get(id);\n if (node) out.push({ id, from: node.pose, to });\n }\n reflowDue = out as LayoutMove<TPose>[];\n return out;\n }\n\n function writePose(id: string, pose: unknown): void {\n scene.setPose(asNodeId(id), pose as TPose);\n }\n\n /** Whether `op` is a `createSetLayoutOp` giving a container a layout. An\n * edit's op list is fixed before it runs, so a layout-less scene has to see\n * this coming to append the arrange op its first layout needs. */\n function givesLayout(op: Op): boolean {\n return op.name === 'setLayout' && (op.args as { to?: unknown } | undefined)?.to != null;\n }\n\n /** `ops` plus the op that settles their arrivals, when this call owns the\n * window; `ops` unchanged otherwise. */\n function withArrivalOps(ops: Op[]): { ops: Op[]; owned: boolean } {\n if (!openArrivals(ops.some(givesLayout))) return { ops, owned: false };\n return { ops: [...ops, createArrangeOp({}, settleArrivals, writePose)], owned: true };\n }\n\n /** Run an op-driven edit that may carry arrivals: a refusal reverts it and\n * is swallowed, the way a drop onto a full container is — nothing lands. */\n function runArrivalEdit(ops: Op[], run: (ops: Op[]) => void): void {\n const { ops: all, owned } = withArrivalOps(ops);\n try {\n run(all);\n if (owned) emitReflow();\n } catch (err) {\n if (!(err instanceof SceneArrivalRefused)) throw err;\n } finally {\n if (owned) {\n arrivals = null;\n reflowDue = null;\n }\n }\n }\n\n function isLockedInternal(id: NodeId): boolean {\n if (!state.layers.some((l) => l.locked)) return false;\n let cur = state.nodes.get(id);\n while (cur !== undefined) {\n if (state.layers[state.layerIndex.get(cur.layer) ?? -1]?.locked) return true;\n cur = cur.parent === null ? undefined : state.nodes.get(cur.parent);\n }\n return false;\n }\n\n function refuseUntracked(verb: string): void {\n if (untrackedDepth > 0) throw new Error(`Scene: cannot ${verb} inside untracked() — it records`);\n }\n\n function refuseLocked(id: NodeId, verb: string): void {\n if (lockBypass > 0 || !isLockedInternal(id)) return;\n throw new Error(`Scene: cannot ${verb} \"${id}\" — it is on a locked layer`);\n }\n\n function refuseLockedLayer(layer: TLayer, verb: string): void {\n if (lockBypass > 0 || !state.layers[state.layerIndex.get(layer) ?? -1]?.locked) return;\n throw new Error(`Scene: cannot ${verb} layer \"${layer}\" — it is locked`);\n }\n\n /** The scene's selection never holds a locked node, whoever writes it. */\n function reachable(ids: readonly NodeId[]): readonly NodeId[] {\n if (!state.layers.some((l) => l.locked)) return ids;\n return ids.filter((id) => !isLockedInternal(id));\n }\n\n function withLocksLifted<T>(fn: () => T): T {\n lockBypass++;\n try {\n return fn();\n } finally {\n lockBypass--;\n }\n }\n\n /**\n * Run `fn` as all-or-nothing: if it throws, every kit op it applied is\n * reverted, newest first, and the selection goes back to where it was.\n * The log is at kit-op grain rather than per external op, because one\n * external op can issue several scene mutations (a container move cascading\n * to its children) and fail halfway through its own.\n *\n * On success the ops join an enclosing log only when `ownsEntry` says no\n * history entry holds them: reverting ops an entry still claims would leave\n * undo replaying a change that is no longer there.\n */\n function atomically<T>(fn: () => T, ownsEntry: () => boolean): T {\n const outer = appliedLog;\n const log: { kind: string; payload: unknown }[] = [];\n const selectionBefore = selection;\n appliedLog = log;\n try {\n const result = fn();\n if (outer && !ownsEntry()) outer.push(...log);\n return result;\n } catch (err) {\n appliedLog = null;\n withLocksLifted(() => {\n for (let i = log.length - 1; i >= 0; i--) {\n const { kind, payload } = log[i];\n registered.get(kind)!.revert(payload);\n }\n });\n selection = selectionBefore;\n if (log.length > 0) notify();\n throw err;\n } finally {\n appliedLog = outer;\n }\n }\n\n function notify(): void {\n version++;\n if (batchDepth > 0) {\n batchDirty = true;\n return;\n }\n for (const listener of listeners) listener();\n }\n\n /**\n * Prune the function-field caches of nodes referenced only by ops in entries\n * that just became permanently unreachable (redo entries dropped by a branch\n * edit, or undo entries evicted by `historyLimit`) — wired to the engine's\n * `onEvict`. An entry is safe to drop when the node is absent from\n * `state.nodes`: its only path back into the scene was through these\n * now-unreachable ops.\n */\n function pruneCacheForDroppedOps(ops: readonly Op[]): void {\n if (fnFields.every((f) => f.pending.size === 0)) return;\n for (const op of ops) {\n if (op.name !== 'kit:add') continue;\n const id = (op.args as { id?: NodeId } | null)?.id;\n if (id && !state.nodes.has(id)) {\n for (const field of fnFields) field.pending.delete(id);\n }\n }\n }\n\n function requireNode(id: NodeId): Node<TData, TLayer, TPose> {\n const n = state.nodes.get(id);\n if (!n) throw new Error(`Scene: unknown node id \"${id}\"`);\n return n;\n }\n\n function requireLayerIndex(layer: TLayer): number {\n const i = state.layerIndex.get(layer);\n if (i === undefined) throw new Error(`Scene: unknown layer \"${layer}\"`);\n return i;\n }\n\n /** Repopulate `state.layerIndex` from the current `state.layers` order.\n * Call after any op that inserts, removes, or reorders a layer record. */\n function rebuildLayerIndex(): void {\n invalidateOrder();\n state.layerIndex.clear();\n for (let i = 0; i < state.layers.length; i++) {\n state.layerIndex.set(state.layers[i].id, i);\n }\n }\n\n /**\n * A child may sit on its parent's layer **or any layer above it** (higher\n * render index) — never below. `renderOrder()` / `toJSON()` are layer-major\n * (each node yielded in its OWN layer's pass) and `buildSceneTree` buckets by\n * each node's own layer, so a child on a higher layer than its parent renders\n * correctly on top while staying a tree child for hit-testing / move /\n * reparent (e.g. plantings tagged into a top `plantings` layer while remaining\n * children of their container). Rejecting only the *below* case keeps the\n * sensible invariant that a child never paints under its own parent.\n */\n function assertSubtreeLayer(\n nodeId: string | undefined,\n nodeLayer: TLayer,\n parentId: NodeId,\n parentLayer: TLayer,\n verb: 'place' | 'relayer' = 'place',\n ): void {\n if (requireLayerIndex(nodeLayer) < requireLayerIndex(parentLayer)) {\n const action = verb === 'place'\n ? `cannot place node '${nodeId ?? '<new>'}' on layer '${nodeLayer}' under parent '${parentId}' on layer '${parentLayer}'`\n : `cannot setLayer('${nodeId ?? '<new>'}', '${nodeLayer}') — node has parent '${parentId}' on layer '${parentLayer}'`;\n throw new Error(`Scene: ${action} — a child may not render below its parent's layer`);\n }\n }\n\n function siblingsOf(parent: NodeId | null): NodeId[] {\n if (parent === null) return state.roots;\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n return p.children;\n }\n\n function detach(id: NodeId): { parent: NodeId | null; index: number } {\n const node = requireNode(id);\n const sibs = siblingsOf(node.parent);\n const idx = sibs.indexOf(id);\n if (idx < 0) throw new Error(`Scene: node \"${id}\" not found in its parent's children`);\n sibs.splice(idx, 1);\n invalidateOrder();\n return { parent: node.parent, index: idx };\n }\n\n function attach(id: NodeId, parent: NodeId | null, index: number): void {\n const sibs = siblingsOf(parent);\n const i = Math.max(0, Math.min(index, sibs.length));\n sibs.splice(i, 0, id);\n const node = requireNode(id);\n (node as { parent: NodeId | null }).parent = parent;\n invalidateOrder();\n }\n\n function descendants(id: NodeId, out: NodeId[]): void {\n const n = state.nodes.get(id);\n if (!n || n.kind !== 'container') return;\n for (const c of n.children) {\n out.push(c);\n descendants(c, out);\n }\n }\n\n /** Everything removing `rootIds` takes with it: each root's subtree, then\n * every node deriving from any of those, then those nodes' subtrees in turn.\n * A dependent is not a descendant, so the second pass is a separate\n * reachability walk; `ids` grows as it runs, which is what carries the\n * cascade transitively and upward through a dependent's own ancestors.\n *\n * Published as {@link Scene.removalClosure}, which is what the delete op and\n * `buildDeleteOps` ask instead of rebuilding the walk from `dependsOn` and\n * `children` — a third cascade relation is then added here alone. */\n function removalClosure(rootIds: readonly NodeId[]): {\n ids: NodeId[];\n removing: Set<NodeId>;\n } {\n const ids: NodeId[] = [];\n const removing = new Set<NodeId>();\n function take(id: NodeId): void {\n if (removing.has(id)) return;\n removing.add(id);\n ids.push(id);\n const sub: NodeId[] = [];\n descendants(id, sub);\n for (const s of sub) {\n if (removing.has(s)) continue;\n removing.add(s);\n ids.push(s);\n }\n }\n for (const root of rootIds) take(root);\n for (let i = 0; i < ids.length; i++) {\n for (const dep of dependents.transitiveDependentsOf(ids[i])) take(dep);\n }\n return { ids, removing };\n }\n\n /** Post-patch the registry-keyed function fields onto a node after its\n * `kit:add` op runs. A function cannot travel through the serializable op\n * payload, so it is attached to the live node here. `cacheForRedo` also\n * keeps the reference in the field's pending map, which is where the\n * `kit:add` redo path reads it from — redo replays the op without a spec.\n * `dependsOn` is plain data and rides the payload instead. */\n function patchNodeFunctions(\n spec: AddNodeSpec<TData, TLayer, TPose>,\n id: NodeId,\n { cacheForRedo }: { cacheForRedo: boolean },\n ): void {\n const node = state.nodes.get(id) as FnBearingNode | undefined;\n if (node === undefined) return;\n for (const field of fnFields) {\n const fn = (spec as unknown as Record<string, unknown>)[field.spec.field] as NodeFn | undefined;\n if (fn === undefined) continue;\n if (field.spec.containersOnly && spec.kind !== 'container') continue;\n field.write(node, fn);\n if (cacheForRedo) field.pending.set(id, fn);\n }\n }\n\n /** Re-attach those fields to a node restored from a `kit:remove` snapshot.\n * In-session the clone already carries them; a persisted history does not,\n * so the registry keys are what is left. */\n function restoreNodeFunctions(\n node: Node<TData, TLayer, TPose>,\n keys: Record<string, string | undefined> | undefined,\n ): void {\n if (!keys) return;\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n if (field.read(target) !== undefined) continue;\n const key = keys[field.spec.opKey];\n if (key === undefined) continue;\n restoreFn(field, target, key, 'kit:remove', dwarn);\n }\n }\n\n // ── Internal kit op kinds ──────────────────────────────────────────────\n // These are registered like any other op; the kit's mutation methods build\n // serializable payloads and route through the same log/replay machinery.\n function registerKitOp<P>(kind: string, handler: RegisteredOp<P>): void {\n registered.set(kind, handler as RegisteredOp<unknown>);\n }\n\n registerKitOp<{\n id: NodeId; kind: 'leaf' | 'container'; layer: TLayer; pose: TPose; data: TData;\n parent: NodeId | null; index: number;\n dependsOn?: readonly NodeId[] | 'children';\n pickable?: boolean;\n } & Record<string, unknown>>('kit:add', {\n apply: (p) => {\n if (state.nodes.has(p.id)) {\n throw new Error(`Scene: id collision on \"${p.id}\"`);\n }\n const node: Node<TData, TLayer, TPose> = p.kind === 'container'\n ? ({ kind: 'container', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent, children: [] } as ContainerNode<TData, TLayer, TPose>)\n : ({ kind: 'leaf', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent } as LeafNode<TData, TLayer, TPose>);\n state.nodes.set(p.id, node);\n attach(p.id, p.parent, p.index);\n if (p.dependsOn !== undefined) node.dependsOn = p.dependsOn;\n if (p.pickable !== undefined) node.pickable = p.pickable;\n dependents.add(p.id, p.dependsOn === 'children' ? [] : p.dependsOn ?? []);\n trackChildDerived(p.id, p.dependsOn);\n // Two ways a function field comes back. The redo path reads the\n // side-channel cache the original `scene.add` filled, because redo\n // replays the op without a spec. The restore path — a fresh session,\n // empty cache — resolves the registry key the payload carries, and\n // seeds the cache so later undo/redo cycles behave like the live one.\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n const cached = field.pending.get(p.id);\n if (cached !== undefined) {\n field.write(target, cached);\n continue;\n }\n const key = p[field.spec.opKey] as string | undefined;\n if (key !== undefined) restoreFn(field, target, key, 'kit:add', dwarn);\n }\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n state.nodes.delete(p.id);\n dependents.remove(p.id);\n childDerived.delete(p.id);\n invalidateChildDerivedFrom(p.parent);\n invalidateDependents(p.id);\n // Note: we intentionally do NOT delete the pending function-field\n // entries — redo re-applies the node and re-attaches from them.\n },\n });\n\n /**\n * Snapshot of every node a removal deletes, so revert restores it exactly.\n *\n * A cascade unlinks several disjoint subtrees, not one, so `detached` names\n * each node the tree has to re-link; everything else in `nodes` has a parent\n * that is also going and rides back in that parent's cloned `children`.\n * Entries are sorted by ascending sibling index — globally rather than\n * per-parent, because only same-parent order constrains re-insertion and\n * entries under different parents never interact.\n */\n interface RemoveSnapshot {\n nodes: Node<TData, TLayer, TPose>[];\n detached: { id: NodeId; parent: NodeId | null; index: number }[];\n /** Registry keys for the function-valued fields on `nodes`. The functions\n * themselves do not survive a persisted history, so revert re-resolves\n * them the way `kit:add` does. */\n fnKeys?: ({ id: NodeId } & Record<string, string | undefined>)[];\n }\n // Neither half invalidates dependents: removal's closure takes every live one.\n registerKitOp<RemoveSnapshot>('kit:remove', {\n apply: (p) => {\n for (const d of p.detached) detach(d.id);\n for (const n of p.nodes) {\n state.nodes.delete(n.id);\n dependents.remove(n.id);\n childDerived.delete(n.id);\n }\n // A `dependsOn: 'children'` container the removal did not take is now\n // hugging a smaller set.\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n revert: (p) => {\n const keys = new Map((p.fnKeys ?? []).map((k) => [k.id, k]));\n // Order-independent: every clone carries its own parent and children.\n for (const n of p.nodes) {\n const clone: Node<TData, TLayer, TPose> = n.kind === 'container'\n ? { ...n, children: [...n.children] }\n : { ...n };\n restoreNodeFunctions(clone, keys.get(n.id));\n state.nodes.set(n.id, clone);\n dependents.add(n.id, clone.dependsOn === 'children' ? [] : clone.dependsOn ?? []);\n trackChildDerived(n.id, clone.dependsOn);\n }\n for (const d of p.detached) attach(d.id, d.parent, d.index);\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TPose; to: TPose }>('kit:setPose', {\n apply: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.from;\n invalidateDependents(p.id);\n },\n });\n\n // A derivation is handed its dependencies' nodes, not only their poses, so a\n // connector reading `data` or `layer` goes stale on these two exactly as it\n // does on a move.\n registerKitOp<{ id: NodeId; from: TData; to: TData }>('kit:setData', {\n apply: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.from;\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TLayer; to: TLayer }>('kit:setLayer', {\n apply: (p) => {\n requireLayerIndex(p.to);\n (requireNode(p.id) as { layer: TLayer }).layer = p.to;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { layer: TLayer }).layer = p.from;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{\n id: NodeId;\n from: Node<TData, TLayer, TPose>['dependsOn'];\n to: Node<TData, TLayer, TPose>['dependsOn'];\n }>('kit:setDependsOn', {\n apply: (p) => { retarget(p.id, p.to); },\n revert: (p) => { retarget(p.id, p.from); },\n });\n\n /** The strategies each live `kit:setLayout` payload swaps between. A payload\n * replayed from a persisted history has none, and resolves its keys. */\n const layoutRefs = new WeakMap<object, { from: LayoutStrategy<TPose> | null; to: LayoutStrategy<TPose> | null }>();\n interface SetLayoutPayload { id: NodeId; fromKey?: string; toKey?: string }\n function placeLayout(p: SetLayoutPayload, side: 'from' | 'to'): void {\n const node = requireNode(p.id) as unknown as FnBearingNode;\n const field = fnField('layout');\n const live = layoutRefs.get(p);\n const key = side === 'from' ? p.fromKey : p.toKey;\n if (live === undefined && key !== undefined) {\n delete node.layout;\n restoreFn(field, node, key, 'kit:setLayout', dwarn);\n return;\n }\n const layout = live?.[side] ?? null;\n if (layout === null) delete node.layout;\n else field.write(node, layout);\n }\n registerKitOp<SetLayoutPayload>('kit:setLayout', {\n apply: (p) => { placeLayout(p, 'to'); },\n revert: (p) => { placeLayout(p, 'from'); },\n });\n\n registerKitOp<{\n id: NodeId; fromParent: NodeId | null; fromIndex: number;\n toParent: NodeId | null; toIndex: number;\n }>('kit:move', {\n apply: (p) => {\n detach(p.id);\n attach(p.id, p.toParent, p.toIndex);\n // Both ends: the container it left no longer hugs it, and the one it\n // joined now does.\n invalidateChildDerivedFrom(p.fromParent);\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n attach(p.id, p.fromParent, p.fromIndex);\n invalidateChildDerivedFrom(p.toParent);\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerVisible', {\n apply: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.to; },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerLocked', {\n apply: (p) => {\n state.layers[requireLayerIndex(p.layer)].locked = p.to;\n if (p.to) selection = reachable(selection);\n },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].locked = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from?: ParallaxOpts; to?: ParallaxOpts }>('kit:setLayerParallax', {\n apply: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.to); },\n revert: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.from); },\n });\n\n registerKitOp<{ record: UserLayerRecord<TLayer>; index: number }>('kit:addLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 0, { ...p.record });\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ record: LayerRecord<TLayer>; index: number }>('kit:removeLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 0, { ...p.record } as LayerRecord<TLayer>);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ layer: TLayer; from: string; to: string }>('kit:renameLayer', {\n apply: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.to;\n },\n revert: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.from;\n },\n });\n\n registerKitOp<{ layer: TLayer; from: number; to: number }>('kit:moveLayer', {\n apply: (p) => {\n const [rec] = state.layers.splice(p.from, 1);\n state.layers.splice(p.to, 0, rec);\n rebuildLayerIndex();\n },\n revert: (p) => {\n const [rec] = state.layers.splice(p.to, 1);\n state.layers.splice(p.from, 0, rec);\n rebuildLayerIndex();\n },\n });\n\n // ── Op execution (used by both kit mutations and consumer recordOp) ────\n function runOp(kind: string, payload: unknown): void {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n handler.apply(payload);\n }\n\n /** Bridge a registered scene op into an engine `Op`: a direction-flipping\n * wrapper over the `RegisteredOp`'s `apply`/`revert` pair. `invert()`\n * flips the direction with the same payload, so undo replays `revert`\n * and redo replays `apply` — no per-op inverse code. `name`/`args` carry\n * the (kind, payload) pair for eviction pruning (and, later,\n * serialization). Handler lookup happens at apply time so re-registered\n * kinds take effect on replay, but existence is checked eagerly to fail\n * fast at the call site. */\n function makeOp(kind: string, payload: unknown, dir: 'fwd' | 'rev' = 'fwd'): Op {\n if (!registered.has(kind)) {\n throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n }\n return {\n name: kind,\n args: payload,\n coalesceKey: coalesceKeyFor(kind, payload),\n apply: () => {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n (dir === 'fwd' ? handler.apply : handler.revert)(payload);\n },\n invert: () => makeOp(kind, payload, dir === 'fwd' ? 'rev' : 'fwd'),\n };\n }\n\n /** Rebind an external op to the adapter supplied at the `applyBatch` call\n * site — the scene's engine was constructed without an adapter, so ops\n * it stores and later replays must close over the right one. Forwards\n * the apply return value (no-op detection) and preserves\n * `coalesceKey`/`name`/`args`/`label` for coalescing and eviction. See\n * `bindOpToHistoryAdapter` for RESTORED entries (lazy accessor). */\n function bindOpToAdapter(op: Op, adapter: unknown): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => op.apply(adapter),\n invert: () => bindOpToAdapter(op.invert(), adapter),\n };\n }\n\n /** Best-effort coalesce-grouping token: node ops carry `payload.id`,\n * layer ops `payload.layer`. Payloads with neither get no key and never\n * coalesce (the engine treats a missing key on either side as\n * \"new entry\"). Keys only take effect when the scene opts in via\n * `UseSceneOptions.coalesceWindowMs` (default `0`, which disables\n * coalescing entirely). */\n function coalesceKeyFor(kind: string, payload: unknown): string | undefined {\n if (payload === null || typeof payload !== 'object') return undefined;\n const p = payload as { id?: unknown; layer?: unknown };\n const token =\n typeof p.id === 'string' ? p.id\n : typeof p.layer === 'string' ? p.layer\n : undefined;\n return token === undefined ? undefined : `${kind}:${token}`;\n }\n\n /** Run `fn` with scene-side recording suppressed and per-op notifies\n * batched. Used whenever the engine drives mutations (undo/redo/goto):\n * engine-applied ops may re-enter scene mutation methods, which must\n * apply but not record. The caller fires exactly one `notify()` after. */\n function withRecordingSuppressed<T>(fn: () => T): T {\n const prevSuppress = suppressRecording;\n suppressRecording = true;\n batchDepth++;\n const prevDirty = batchDirty;\n try {\n return fn();\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n batchDirty = prevDirty;\n }\n }\n\n function executeAndLog(kind: string, payload: unknown, label: string): void {\n if (suppressRecording) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n notify();\n return;\n }\n if (currentBatch) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n currentBatch.ops.push(makeOp(kind, payload));\n notify();\n return;\n }\n // The engine applies the op itself (inside applyOps) — no separate\n // runOp call, or the mutation would run twice.\n history.applyOps([makeOp(kind, payload)], label);\n notify();\n }\n\n // ── Public Scene object ────────────────────────────────────────────────\n\n // Register consumer-supplied ops up front.\n if (options.ops) {\n for (const [k, h] of Object.entries(options.ops)) {\n registered.set(k, h);\n }\n }\n\n /**\n * Layer-major DFS-preorder ids, and the same sequence as nodes. Four walks\n * for two sequences, which wants explaining, because collapsing them is the\n * obvious cleanup and each collapse was measured to cost something:\n *\n * - ids vs nodes: projecting one from the other is a whole extra pass, worth\n * 20% of `renderOrder()` on a multi-layer scene.\n * - flat vs bucketed: a single layer needs no buckets and can compare the\n * layer id instead of indexing it, which is 1.4x. Behind a branch in one\n * function it also slows the bucketed path by 20% — the two shapes share\n * one optimized body, and whichever ran first wins it.\n *\n * All four emit the same order and `renderOrder.test.ts` holds them to it.\n */\n function renderOrderInternal(): NodeId[] {\n return state.layers.length === 1 ? renderOrderFlat() : renderOrderBucketed();\n }\n\n function renderOrderNodesInternal(): Node<TData, TLayer, TPose>[] {\n return state.layers.length === 1 ? renderOrderNodesFlat() : renderOrderNodesBucketed();\n }\n\n /**\n * Render order survives everything except a structural edit, so both walks\n * are cached against a counter the structural writers bump: `attach` and\n * `detach` (add / remove / reparent / reorder), `kit:setLayer` (which bucket\n * a node lands in), `rebuildLayerIndex` (the layer list itself), and\n * `loadState`. Pose and data edits leave order alone and must NOT invalidate\n * — they fire per frame during a drag, which is exactly when the cache pays.\n *\n * A missed bump is a silent wrong answer: nodes painted in the wrong z-order,\n * or unpickable. `renderOrder.test.ts` walks each structural op and asserts\n * the order moved.\n */\n let structureGeneration = 0;\n let orderCache: {\n gen: number;\n ids?: NodeId[];\n nodes?: Node<TData, TLayer, TPose>[];\n byLayer?: Map<TLayer, Node<TData, TLayer, TPose>[]>;\n } = { gen: 0 };\n\n function invalidateOrder(): void {\n structureGeneration++;\n }\n\n const EMPTY_NODES: readonly Node<TData, TLayer, TPose>[] = [];\n\n function currentOrderCache(): typeof orderCache {\n if (orderCache.gen !== structureGeneration) {\n orderCache = { gen: structureGeneration };\n }\n return orderCache;\n }\n\n function renderOrderFlat(): NodeId[] {\n const only = state.layers[0].id;\n const out: NodeId[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n function renderOrderNodesFlat(): Node<TData, TLayer, TPose>[] {\n const only = state.layers[0].id;\n const out: Node<TData, TLayer, TPose>[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n /** One DFS of the tree, bucketed by layer: appending in preorder keeps each\n * bucket in preorder, so concatenating them is the layer-major sequence. */\n function renderOrderBucketed(): NodeId[] {\n const buckets: NodeId[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: NodeId[] = [];\n for (const bucket of buckets) {\n for (const id of bucket) out.push(id);\n }\n return out;\n }\n\n function renderOrderNodesBucketed(): Node<TData, TLayer, TPose>[] {\n const buckets: Node<TData, TLayer, TPose>[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: Node<TData, TLayer, TPose>[] = [];\n for (const bucket of buckets) {\n for (const node of bucket) out.push(node);\n }\n return out;\n }\n\n // ── scene.history ──────────────────────────────────────────────────────\n // The `History` the kit's `undo`/`redo` actions resolve their `history` dep\n // to, and the handle a mode machine opens journals against. Handing out\n // `history` (the engine) directly would let an action-driven undo replay ops\n // with scene-side recording still armed and without bumping the version, so\n // every member that mutates routes through the scene's own wrapper\n // (`withRecordingSuppressed` + one `notify()`); reads forward to the engine.\n\n /** Wrapped journal → the engine's own, for `resumeJournal`: the engine keys\n * resumability off journal identity, which a wrapper would not match. */\n const rawJournals = new WeakMap<Journal, Journal>();\n\n /** Same treatment as the façade: a journal drives adapter mutation itself,\n * so its applies/undos re-enter scene mutation methods. */\n function wrapJournal(raw: Journal): Journal {\n const wrapped: Journal = {\n targetId: raw.targetId,\n forkedAtEntryId: raw.forkedAtEntryId,\n applyBatch(ops, label) {\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => raw.applyBatch(all, label)), () => true);\n notify();\n });\n },\n undo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.undo()));\n notify();\n },\n redo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.redo()));\n notify();\n },\n canUndo: () => raw.canUndo(),\n canRedo: () => raw.canRedo(),\n entries: () => raw.entries(),\n seal: () => raw.seal(),\n getVersion: () => raw.getVersion(),\n subscribe: (listener) => raw.subscribe(listener),\n commit(label) {\n // Flushes the session's net ops to the parent stack — no apply, but\n // the parent's undo depth changes and listeners read that.\n raw.commit(label);\n notify();\n },\n cancel() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.cancel()));\n notify();\n },\n suspend: () => raw.suspend(),\n isActive: () => raw.isActive(),\n };\n rawJournals.set(wrapped, raw);\n return wrapped;\n }\n\n const sceneHistory: History = {\n // Mutating: applied ops re-enter the scene's own mutation methods.\n apply(op, label) {\n refuseUntracked('history.apply');\n runArrivalEdit([op], (all) => {\n const run = () => (all.length === 1\n ? history.apply(op, label)\n : history.applyOps(all, label ?? op.label ?? ''));\n atomically(() => withRecordingSuppressed(run), () => true);\n notify();\n });\n },\n applyOps(ops, label) {\n refuseUntracked('history.applyOps');\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => history.applyOps(all, label)), () => true);\n notify();\n });\n },\n undo: () => { scene.undo(); },\n redo: () => { scene.redo(); },\n goto: (n) => { scene.jumpToHistoryIndex(n); },\n // Stack-only: nothing applies, but what `canUndo()` answers changes.\n clear() {\n history.clear();\n notify();\n },\n recordEntry(ops, label, opts) {\n history.recordEntry(ops, label, opts);\n notify();\n },\n restore: (snapshot) => { scene.restoreHistory(snapshot); },\n // Reads forward to the engine, `version` included: it counts history\n // operations, where the scene's counts every mutation.\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n undoDepth: () => history.undoDepth(),\n redoDepth: () => history.redoDepth(),\n entries: () => history.entries(),\n getVersion: () => history.getVersion(),\n subscribe: (listener) => history.subscribe(listener),\n serialize: () => history.serialize(),\n allForwardOps: () => history.allForwardOps(),\n seal: () => history.seal(),\n currentEntryId: () => history.currentEntryId(),\n beginJournal: (opts) => wrapJournal(history.beginJournal(opts)),\n resumeJournal: (journal) => history.resumeJournal(rawJournals.get(journal) ?? journal),\n };\n\n function applyBatchNow(ops: Op[], label: string, adapter: unknown): void {\n const journal: Journal | null = (activeJournalAccessor ?? (() => null))();\n // Either route drives mutations from a history engine (the journal's\n // inner history, or the scene's own), so scene-side recording is\n // suppressed for the duration: op applies that re-enter scene\n // mutation methods via the adapter must mutate without re-recording.\n // batchDepth coalesces the per-op notify() calls (same as\n // scene.batch); exactly one listener dispatch fires at the end —\n // mirroring the single-notification semantics callers expect.\n const prevSuppress = suppressRecording;\n const prevDirty = batchDirty;\n suppressRecording = true;\n batchDepth++;\n batchDirty = false;\n try {\n atomically(() => {\n if (journal) {\n journal.applyBatch(ops, label);\n } else {\n // Native path: record the external ops themselves as one engine\n // entry — coalescible across applyBatch calls via their own\n // coalesceKeys — rebound to this call's adapter.\n history.applyOps(ops.map((op) => bindOpToAdapter(op, adapter)), label);\n }\n }, () => true);\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n // Re-merge any outer batch's pending dirt so a nested call can't\n // swallow it; at true top level prevDirty is always false.\n batchDirty = batchDirty || prevDirty;\n // Flush inside finally so a throwing op can't strand subscribers\n // after earlier ops in the batch already mutated state (mirrors\n // scene.batch). Depth-guarded: a nested context defers to the\n // outermost flush.\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n\n const scene: Scene<TData, TLayer, TPose> = {\n get nodes() { return state.nodes; },\n get roots() { return state.roots; },\n get layers() { return state.layers; },\n registry,\n\n get(id) { return state.nodes.get(id); },\n incarnation(id) {\n const node = state.nodes.get(id);\n if (!node) return undefined;\n let token = incarnations.get(node);\n if (token === undefined) {\n token = nextIncarnation++;\n incarnations.set(node, token);\n }\n return token;\n },\n\n childrenOf(id) {\n const n = state.nodes.get(id);\n return n && n.kind === 'container' ? n.children : [];\n },\n\n ancestorsOf(id) {\n const out: NodeId[] = [];\n let cur = state.nodes.get(id)?.parent ?? null;\n while (cur !== null) {\n out.push(cur);\n cur = state.nodes.get(cur)?.parent ?? null;\n }\n return out;\n },\n\n renderOrder() {\n const c = currentOrderCache();\n return (c.ids ??= renderOrderInternal());\n },\n\n renderOrderNodes() {\n const c = currentOrderCache();\n return (c.nodes ??= renderOrderNodesInternal());\n },\n\n nodesOnLayer(layer) {\n const c = currentOrderCache();\n let byLayer = c.byLayer;\n if (!byLayer) {\n byLayer = new Map();\n for (const node of (c.nodes ??= renderOrderNodesInternal())) {\n let bucket = byLayer.get(node.layer);\n if (!bucket) byLayer.set(node.layer, (bucket = []));\n bucket.push(node);\n }\n c.byLayer = byLayer;\n }\n return byLayer.get(layer) ?? EMPTY_NODES;\n },\n\n add(spec) {\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n refuseLockedLayer(spec.layer, 'add to');\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n refuseLocked(parent, 'add under');\n }\n if (parent !== null && bareLayoutEdit()) {\n // A bare add under a container is an edit of its own, so it settles\n // its arrival like one — as a batch, which is what makes the\n // arrangement part of the same undo step.\n return scene.batch(`add ${spec.kind}`, () => scene.add(spec));\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n noteArrival(id, parent, null);\n executeAndLog('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n ...fnKeysOf(fnFields, { ...spec, id, kind: spec.kind } as unknown as FnBearingNode, 'opKey'),\n }, `add ${spec.kind}`);\n // A function cannot travel through the serializable op payload. Patch it\n // directly onto the live node after the op applies.\n patchNodeFunctions(spec, id, { cacheForRedo: true });\n return id;\n },\n\n remove(id) {\n scene.removeMany([id]);\n },\n\n removalClosure(rootIds) {\n return removalClosure(rootIds).ids;\n },\n\n removeMany(rootIds) {\n if (rootIds.length === 0) return;\n // Every id resolves against the pre-removal tree, so an id another one\n // cascades away is absorbed rather than being a second, failing removal.\n const { ids, removing } = removalClosure(rootIds);\n for (const nid of ids) refuseLocked(nid, 'remove');\n // requireNode is what rejects an id that is not in the scene, and it runs\n // before anything mutates.\n const snapshot: Node<TData, TLayer, TPose>[] = ids.map((nid) => {\n const n = requireNode(nid);\n return n.kind === 'container' ? { ...n, children: [...n.children] } : { ...n };\n });\n // The rest is reachable through a snapshotted parent's cloned `children`.\n const detached = snapshot\n .filter((n) => n.parent === null || !removing.has(n.parent))\n .map((n) => ({ id: n.id, parent: n.parent, index: siblingsOf(n.parent).indexOf(n.id) }))\n .sort((l, r) => l.index - r.index);\n // Ephemeral, and ids are reusable: an override left behind would\n // reattach itself to whatever is added under this id next.\n for (const nid of ids) overrides.clear(nid);\n const fnKeys = snapshot.flatMap((n) => {\n const keys = fnKeysOf(fnFields, n as unknown as FnBearingNode, 'opKey');\n return Object.keys(keys).length === 0 ? [] : [{ id: n.id, ...keys }];\n });\n const payload: RemoveSnapshot = {\n nodes: snapshot, detached,\n ...(fnKeys.length > 0 ? { fnKeys } : {}),\n };\n if (detached.some((d) => d.parent !== null) && bareLayoutEdit()) {\n scene.batch('remove', () => scene.removeMany(rootIds));\n return;\n }\n for (const d of detached) noteDeparture(d.id, d.parent, null);\n executeAndLog('kit:remove', payload, 'remove');\n },\n\n update(id, patch) {\n const node = requireNode(id);\n refuseLocked(id, 'update');\n executeAndLog('kit:setData', { id, from: node.data, to: patch.data }, 'update');\n },\n\n setPose(id, pose) {\n const node = requireNode(id);\n refuseLocked(id, 'set the pose of');\n if (node.kind === 'container' && resized(layoutFrame, id, node.pose, pose)) {\n if (bareLayoutEdit()) {\n scene.batch('setPose', () => scene.setPose(id, pose));\n return;\n }\n noteChange(id);\n }\n executeAndLog('kit:setPose', { id, from: node.pose, to: pose }, 'setPose');\n },\n\n setLayer(id, layer) {\n requireLayerIndex(layer);\n const node = requireNode(id);\n refuseLocked(id, 'relayer');\n if (node.layer !== layer) refuseLockedLayer(layer, 'move nodes onto');\n if (node.parent !== null) {\n const parentNode = requireNode(node.parent);\n assertSubtreeLayer(id, layer, node.parent, parentNode.layer, 'relayer');\n }\n if (node.layer === layer) return;\n // DFS preorder: collect id + all descendants.\n const subtree: NodeId[] = [];\n const stack: NodeId[] = [id];\n while (stack.length > 0) {\n const curId = stack.pop()!;\n const cur = state.nodes.get(curId);\n if (!cur) continue;\n subtree.push(curId);\n refuseLocked(curId, 'relayer');\n if (cur.kind === 'container') {\n for (let i = cur.children.length - 1; i >= 0; i--) {\n stack.push(cur.children[i]);\n }\n }\n }\n if (subtree.length === 1) {\n // Fast path: single node, no batch needed.\n executeAndLog('kit:setLayer', { id, from: node.layer, to: layer }, 'setLayer');\n } else {\n scene.batch('setLayer', () => {\n for (const sid of subtree) {\n const cur = requireNode(sid);\n if (cur.layer === layer) continue;\n executeAndLog('kit:setLayer', { id: sid, from: cur.layer, to: layer }, 'setLayer');\n }\n });\n }\n },\n\n setDependsOn(id, dependsOn) {\n const node = requireNode(id);\n refuseLocked(id, 'retarget');\n if (sameDependsOn(node.dependsOn, dependsOn)) return;\n executeAndLog(\n 'kit:setDependsOn',\n { id, from: node.dependsOn, to: dependsOn },\n 'setDependsOn',\n );\n },\n\n setLayout(id, layout) {\n const node = requireNode(id);\n if (node.kind !== 'container') throw new Error(`Scene: \"${id}\" is not a container`);\n refuseLocked(id, 'set the layout of');\n const field = fnField('layout');\n let to: LayoutStrategy<TPose> | null;\n if (typeof layout === 'string') {\n to = (field.fnOf(layout) as LayoutStrategy<TPose> | undefined) ?? null;\n if (to === null) throw new Error(`Scene: no layout \"${layout}\" in this scene's registry`);\n } else {\n to = layout;\n }\n const from = node.layout ?? null;\n if (from === to) return;\n if (to !== null) hasLayouts = true;\n if (bareLayoutEdit()) {\n scene.batch('setLayout', () => scene.setLayout(id, to));\n return;\n }\n noteChange(id);\n const fromKey = from === null ? undefined : field.keyOf(from);\n const toKey = to === null ? undefined : field.keyOf(to);\n const payload: SetLayoutPayload = {\n id,\n ...(fromKey !== undefined ? { fromKey } : {}),\n ...(toKey !== undefined ? { toKey } : {}),\n };\n layoutRefs.set(payload, { from, to });\n executeAndLog('kit:setLayout', payload, 'setLayout');\n },\n\n move(id, parent, index) {\n const node = requireNode(id);\n refuseLocked(id, 'move');\n if (parent !== null) {\n refuseLocked(parent, 'move nodes into');\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(id, node.layer, parent, p.layer);\n // Cycle check: parent must not be id or a descendant of id.\n if (parent === id) throw new Error('Scene: cannot parent a node to itself');\n const desc: NodeId[] = [];\n descendants(id, desc);\n if (desc.includes(parent)) {\n throw new Error('Scene: cannot parent a node to its own descendant');\n }\n }\n if ((parent !== null || node.parent !== null) && bareLayoutEdit()) {\n scene.batch('move', () => scene.move(id, parent, index));\n return;\n }\n const fromSibs = siblingsOf(node.parent);\n const fromIndex = fromSibs.indexOf(id);\n const toSibs = parent === node.parent ? fromSibs : siblingsOf(parent);\n const toIndex = index ?? toSibs.length;\n noteArrival(id, parent, node.parent);\n noteDeparture(id, node.parent, parent);\n noteChange(node.parent);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: parent, toIndex,\n }, 'move');\n },\n\n reorder(id, index) {\n const node = requireNode(id);\n refuseLocked(id, 'reorder');\n if (node.parent !== null && bareLayoutEdit()) {\n scene.batch('reorder', () => scene.reorder(id, index));\n return;\n }\n noteChange(node.parent);\n const sibs = siblingsOf(node.parent);\n const fromIndex = sibs.indexOf(id);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: node.parent, toIndex: index,\n }, 'reorder');\n },\n\n setLayerVisible(layer, visible) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerVisible', { layer, from: state.layers[i].visible, to: visible }, 'setLayerVisible');\n },\n\n setLayerLocked(layer, locked) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerLocked', { layer, from: state.layers[i].locked, to: locked }, 'setLayerLocked');\n },\n\n setLayerParallax(layer, parallax) {\n const i = requireLayerIndex(layer);\n executeAndLog(\n 'kit:setLayerParallax',\n { layer, from: state.layers[i].parallax, to: parallax },\n 'setLayerParallax',\n );\n },\n\n isLocked: (id) => isLockedInternal(id),\n\n unlocked: (fn) => withLocksLifted(fn),\n\n addLayer(spec) {\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene: duplicate layer id \"${spec.id}\"`);\n }\n const index = spec.index ?? state.layers.length;\n const clamped = Math.max(0, Math.min(index, state.layers.length));\n const record: UserLayerRecord<TLayer> = {\n kind: 'user',\n id: spec.id,\n name: spec.name,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n executeAndLog('kit:addLayer', { record, index: clamped }, 'addLayer');\n },\n\n removeLayer(layer) {\n const index = requireLayerIndex(layer);\n const rec = state.layers[index];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot remove system layer \"${layer}\"`);\n }\n // A layer operation, like the lock toggle: taking a locked layer away\n // takes its nodes with it.\n withLocksLifted(() => scene.batch('removeLayer', () => {\n const tagged: NodeId[] = [];\n for (const [id, node] of state.nodes) {\n if (node.layer === layer) tagged.push(id);\n }\n scene.removeMany(tagged);\n const finalIndex = requireLayerIndex(layer);\n executeAndLog('kit:removeLayer', { record: rec, index: finalIndex }, 'removeLayer');\n }));\n },\n\n renameLayer(layer, name) {\n const rec = state.layers[requireLayerIndex(layer)];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot rename system layer \"${layer}\"`);\n }\n executeAndLog('kit:renameLayer', { layer, from: rec.name, to: name }, 'renameLayer');\n },\n\n moveLayer(layer, index) {\n const from = requireLayerIndex(layer);\n const to = Math.max(0, Math.min(index, state.layers.length - 1));\n if (from === to) return;\n // Build the proposed order and a temp index map, then verify the\n // child-below-parent invariant holds for every node before mutating.\n const proposed = [...state.layers];\n const [rec] = proposed.splice(from, 1);\n proposed.splice(to, 0, rec);\n const tempIndex = new Map<TLayer, number>();\n for (let i = 0; i < proposed.length; i++) tempIndex.set(proposed[i].id, i);\n for (const node of state.nodes.values()) {\n if (node.parent === null) continue;\n const parent = state.nodes.get(node.parent);\n if (!parent) continue;\n if (tempIndex.get(node.layer)! < tempIndex.get(parent.layer)!) {\n throw new Error(\n `Scene: moveLayer(\"${layer}\", ${index}) — a child may not render below its parent's layer`,\n );\n }\n }\n executeAndLog('kit:moveLayer', { layer, from, to }, 'moveLayer');\n },\n\n registerOp(kind, handler) {\n if (kind.startsWith('kit:')) {\n throw new Error(`Scene: op kind \"${kind}\" is reserved (kit:* prefix)`);\n }\n registered.set(kind, handler as RegisteredOp<unknown>);\n },\n\n recordOp(op) {\n executeAndLog(op.kind, op.payload, op.kind);\n },\n\n setActiveJournalAccessor(fn) {\n activeJournalAccessor = fn;\n },\n\n applyBatch(ops, label, adapter) {\n refuseUntracked('applyBatch');\n runArrivalEdit(ops, (all) => applyBatchNow(all, label, adapter));\n },\n\n setArrivalHandler(handler) {\n arrivalHandler = handler;\n return () => {\n if (arrivalHandler === handler) arrivalHandler = null;\n };\n },\n\n layoutOf(id) {\n return layoutOfInternal(id);\n },\n\n onReflow(listener) {\n reflowListeners.add(listener);\n return () => { reflowListeners.delete(listener); };\n },\n\n overrides,\n\n getSelection: () => selection,\n\n setSelection(ids) {\n selection = reachable([...ids]);\n notify();\n },\n\n history: sceneHistory,\n\n undo() {\n if (!history.canUndo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.undo()));\n notify();\n return true;\n },\n\n redo() {\n if (!history.canRedo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.redo()));\n notify();\n return true;\n },\n\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Order: oldest applied first, then redoable\n * entries in the order they'd be re-applied (top of redo stack last).\n * Each entry's `id` is stable for the entry's lifetime. */\n historyEntries() {\n const { undo, redo } = history.entries();\n const out: { id: string; label: string }[] = [];\n for (const e of undo) out.push({ id: String(e.id), label: e.label });\n // entries().redo is already chronological: the next redo comes first.\n for (const e of redo) out.push({ id: String(e.id), label: e.label });\n return out;\n },\n\n /** Index of the \"current state\". `0` = nothing applied (initial);\n * equals the number of applied (undoable) entries —\n * `historyEntries().length` when fully redone. */\n historyIndex: () => history.undoDepth(),\n\n /** Walk to a target history index by calling undo/redo repeatedly.\n * Caps at the valid range; returns true if the index changed. */\n jumpToHistoryIndex(targetIndex: number) {\n const total = history.undoDepth() + history.redoDepth();\n const target = Math.max(0, Math.min(total, targetIndex));\n if (target === history.undoDepth()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.goto(target)));\n notify();\n return true;\n },\n\n serializeHistory: () => history.serialize(),\n\n restoreHistory(snapshot: SerializedHistory) {\n // restore() only rebuilds the stacks — no op applies, no node-state\n // mutation. The caller guarantees state already matches the head.\n history.restore(snapshot);\n notify();\n },\n\n setHistoryAdapter(fn) {\n historyAdapterAccessor = fn;\n },\n\n batch(label, fn) {\n // Captured at open, not at recordEntry: by the time the batch closes\n // the selection has already moved to wherever the batch put it.\n const outermost = batchDepth === 0;\n if (outermost) currentBatch = { label, ops: [], selectionBefore: selection };\n const ownsArrivals = outermost && openArrivals(true);\n batchDepth++;\n try {\n if (!outermost) return fn();\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => (currentBatch?.ops.length ?? 0) > 0);\n if (ownsArrivals) emitReflow();\n return result;\n } catch (err) {\n // Reverted already; the half-built entry must not reach history.\n currentBatch = null;\n throw err;\n }\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n if (batchDepth === 0) {\n if (currentBatch) {\n const finished = currentBatch;\n currentBatch = null;\n // Ops were applied live as they were issued (state stays\n // readable mid-batch); recordEntry pushes without re-applying.\n if (finished.ops.length > 0) {\n history.recordEntry(finished.ops, finished.label, { selectionBefore: finished.selectionBefore });\n }\n }\n // Fire one coalesced notify if any op inside the batch dirtied\n // state. Nested batches contribute to the same flush — only the\n // outermost emits.\n if (batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n },\n\n untracked(fn) {\n const prevSuppress = suppressRecording;\n const versionBefore = version;\n suppressRecording = true;\n untrackedDepth++;\n const ownsArrivals = openArrivals(true);\n batchDepth++;\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => false);\n if (ownsArrivals) emitReflow();\n return result;\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n untrackedDepth--;\n suppressRecording = prevSuppress;\n if (version !== versionBefore) history.seal();\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n },\n\n toJSON(): SerializedScene<TData, TLayer, TPose> {\n const nodes: SerializedNode<TData, TLayer, TPose>[] = [];\n for (const n of renderOrderNodesInternal()) {\n const id = n.id;\n const out: SerializedNode<TData, TLayer, TPose> = {\n id,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent != null) out.parent = n.parent;\n if (n.dependsOn === 'children') out.dependsOn = 'children';\n else if (n.dependsOn && n.dependsOn.length > 0) out.dependsOn = n.dependsOn;\n if (n.pickable === false) out.pickable = false;\n Object.assign(\n out,\n fnKeysOf(fnFields, n as unknown as FnBearingNode, 'jsonKey', (field) => {\n throw new Error(\n `Scene.toJSON: node '${id}' has ${field.spec.field} but no matching registry key. ` +\n `The function must be registered via createScene's registry option to round-trip.`\n );\n }),\n );\n nodes.push(out);\n }\n const systemLayers = state.layers.map((l) => {\n const layer: SerializedLayer<TLayer> = { id: l.id };\n if (l.visible === false) layer.visible = false;\n if (l.locked === true) layer.locked = true;\n if (l.parallax) layer.parallax = l.parallax;\n if (l.kind === 'user') {\n layer.kind = 'user';\n layer.name = l.name;\n }\n return layer;\n });\n return { version: 1, systemLayers, nodes };\n },\n\n loadState(json) {\n // Validate + map up front (throws before we touch live state on a bad\n // version or unknown registry key).\n const specs = specsFromSerialized(json, registry);\n // Reset node + layer state.\n dependents.clear();\n state.nodes.clear();\n state.roots.length = 0;\n state.layers.length = 0;\n state.layerIndex.clear();\n invalidateOrder();\n for (let i = 0; i < json.systemLayers.length; i++) {\n const spec = json.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene.loadState: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push(layerFromSerialized(spec));\n state.layerIndex.set(spec.id, i);\n }\n // Clear history + the transient batch and function-field caches.\n history.clear();\n for (const field of fnFields) field.pending.clear();\n currentBatch = null;\n batchDepth = 0;\n batchDirty = false;\n // Rebuild nodes (bypass the log, exactly like construction).\n applyConstructionSpecs(specs);\n notify();\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n getVersion: () => version,\n };\n\n /** Insert nodes without writing to the undo log — used by construction\n * (`options.initial`) and by `loadState`. Specs must list parents before\n * children (the order `toJSON()` emits). Throws on id collision, unknown\n * layer, non-container parent, or cross-layer subtree. */\n function applyConstructionSpecs(specs: readonly AddNodeSpec<TData, TLayer, TPose>[]): void {\n for (const spec of specs) {\n // Bypass the log: we want construction to start with empty history.\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n runOp('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n });\n // No `kit:add` reaches history here, so nothing ever replays these and\n // `pruneCacheForDroppedOps` — which only scans `kit:add` — could never\n // drop the entries. A restore after `remove` comes from `kit:remove`'s\n // revert, which clones the whole node and carries every field along.\n patchNodeFunctions(spec, id, { cacheForRedo: false });\n }\n }\n\n // Apply initial nodes (not undoable — they're part of the construction).\n if (options.initial) {\n applyConstructionSpecs(options.initial);\n notify();\n }\n\n // ── Internal / test-only access ───────────────────────────────────────\n // Attach private state accessors directly on the returned object, hidden\n // behind `as unknown` because Scene<> is the public interface.\n // __clipCacheSize / __derivePathCacheSize: used only by test files to assert\n // prune behaviour.\n (scene as unknown as { __clipCacheSize: () => number }).__clipCacheSize =\n () => fnField('clipFromPose').pending.size;\n (scene as unknown as { __derivePathCacheSize: () => number }).__derivePathCacheSize =\n () => fnField('derivePath').pending.size;\n (scene as unknown as { __derivePoseCacheSize: () => number }).__derivePoseCacheSize =\n () => fnField('derivePose').pending.size;\n\n return scene;\n}\n\n/** Map a `SerializedScene` to construction specs. Shared by `sceneFromJSON`\n * (new instance) and `Scene.loadState` (in-place). Validates version and\n * resolves every `NODE_FN_FIELDS` key → function via the registry;\n * throws on an unsupported version or an unknown registry key. */\nfunction specsFromSerialized<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n registry: SceneRegistry<TPose>,\n): AddNodeSpec<TData, TLayer, TPose>[] {\n if (json.version !== 1) {\n throw new Error(`Scene: unsupported version ${json.version}; only v1 supported`);\n }\n return json.nodes.map((n) => {\n const spec: AddNodeSpec<TData, TLayer, TPose> = {\n id: n.id as NodeId,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent !== undefined) spec.parent = n.parent as NodeId;\n if (n.pickable !== undefined) spec.pickable = n.pickable;\n if (n.dependsOn !== undefined) {\n spec.dependsOn = n.dependsOn === 'children'\n ? 'children'\n : (n.dependsOn as readonly NodeId[]);\n }\n const serialized = n as unknown as Record<string, string | undefined>;\n for (const field of NODE_FN_FIELDS) {\n const key = serialized[field.jsonKey];\n if (key === undefined) continue;\n const fn = (registry[field.field] as Record<string, unknown> | undefined)?.[key];\n if (!fn) {\n throw new Error(\n `Scene: unknown ${field.field} key '${key}'. ` +\n `Register a function with this key in the registry option.`,\n );\n }\n (spec as unknown as Record<string, unknown>)[field.field] = fn;\n }\n return spec;\n });\n}\n\n/** The scene's selection in the shape `createHistory` wants, for a consumer\n * building a second History over the same scene (a modality machine, a\n * journal owner) that should restore selection the way the scene's own\n * history does. */\nexport function sceneSelectionStore(scene: {\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n}): HistorySelection {\n return {\n get: () => scene.getSelection(),\n set: (ids) => scene.setSelection(ids as readonly NodeId[]),\n };\n}\n\n/** Reconstruct a Scene from a JSON snapshot produced by `scene.toJSON()`.\n * Function fields (e.g., `clipFromPose`) are resolved by string key via the\n * registry passed in `options`. Throws on unknown version, unknown registry\n * keys, or invalid scene shape (cross-layer subtrees, unknown layer ids).\n * Loaded scenes start with empty history — undo/redo is NOT serialized. */\nexport function sceneFromJSON<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n options: {\n registry?: SceneRegistry<TPose>;\n historyLimit?: number;\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n layoutFrame?: UseSceneOptions<TData, TLayer, TPose>['layoutFrame'];\n } = {},\n): Scene<TData, TLayer, TPose> {\n const registry = options.registry ?? {};\n // Built empty and then loaded, so the snapshot's layer stack is rebuilt by\n // the one reader that knows how — `createScene` mints system layers only.\n const scene = createScene<TData, TLayer, TPose>({\n systemLayers: json.systemLayers.map((l) => ({ id: l.id })),\n registry,\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.generateId !== undefined ? { generateId: options.generateId } : {}),\n ...(options.ops !== undefined ? { ops: options.ops } : {}),\n ...(options.layoutFrame !== undefined ? { layoutFrame: options.layoutFrame } : {}),\n });\n scene.loadState(json);\n return scene;\n}\n"],"mappings":";;;;;;;;;;;;;AAiDA,IAAIC,IAAmB,GACjBC,WACJC,EAAS,KAAK,IAAA,CAAoB,SAAS,EAAE,EAAE,GAAG,KAAK,OAAO,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,GAAG;AAI5F,SAASC,GAAY,GAAqC,GAAoC;CAC5F,AAAIC,MAAO,KAAA,IAAW,OAAOC,EAAO,WAC/B,EAAO,WAAWD;AACzB;AAEA,SAASE,GACP,GACqB;CACrB,IAAMC,IAAO;EACX,IAAIC,EAAK;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Ae,KAAA,IAAiD,CAAC,IAAtC,EAAE,YAAYA,EAAQ,WAAW;EACxE,GAAIA,EAAQ,QAAQ,KAAA,IAAmC,CAAC,IAAxB,EAAE,KAAKA,EAAQ,IAAI;EACnD,GAAIA,EAAQ,gBAAgB,KAAA,IAAmD,CAAC,IAAxC,EAAE,aAAaA,EAAQ,YAAY;CAC7E,CAAC;CAED,OADA+E,EAAM,UAAUwK,CAAI,GACbxK;AACT"}
1
+ {"version":3,"file":"scene.js","names":["rebuildGlobalOp","defaultIdCounter","defaultGenerateId","asNodeId","setParallax","to","record","layerFromSerialized","base","spec","createScene","options","state","registry","withKitRegistry","fnFields","createNodeFnFields","fnField","f","name","layoutFrame","resolveLayoutFrame","hasLayouts","field","write","node","fn","layoutOfInternal","id","dependents","createDependentsIndex","childDerived","invalidateDependents","invalidateChildDerivedFrom","subtree","src","dep","dropPoseKeyedMemoSlots","cursor","start","d","trackChildDerived","dependsOn","retarget","requireNode","i","generateId","listeners","registered","historyAdapterAccessor","bindOpToHistoryAdapter","op","get","dwarn","err","selection","overrides","createPoseOverrides","history","createHistory","reachable","ids","notify","pruneCacheForDroppedOps","entry","makeOp","args","createArrangeOp","writePose","rebuilt","rebuildOp","version","incarnations","nextIncarnation","batchDepth","currentBatch","suppressRecording","untrackedDepth","lockBypass","appliedLog","batchDirty","activeJournalAccessor","arrivalHandler","arrivals","departures","changed","reflowDue","reflowListeners","declaredLayouts","runLayoutPass","scene","arrived","touched","departed","activeHandler","noteArrival","parent","from","list","noteDeparture","noteChange","bareLayoutEdit","openArrivals","always","emitReflow","moves","listener","settleArrivals","pending","handler","landed","still","left","gone","poses","SceneArrivalRefused","out","pose","givesLayout","withArrivalOps","ops","runArrivalEdit","all","run","owned","isLockedInternal","l","cur","refuseUntracked","verb","refuseLocked","refuseLockedLayer","layer","withLocksLifted","atomically","outer","log","selectionBefore","result","ownsEntry","kind","payload","n","requireLayerIndex","rebuildLayerIndex","invalidateOrder","assertSubtreeLayer","nodeLayer","parentLayer","action","nodeId","parentId","siblingsOf","p","detach","sibs","idx","attach","index","descendants","c","removalClosure","removing","take","sub","s","root","rootIds","patchNodeFunctions","cacheForRedo","restoreNodeFunctions","keys","target","key","restoreFn","registerKitOp","cached","k","clone","layoutRefs","placeLayout","live","side","layout","rec","runOp","coalesceKeyFor","dir","bindOpToAdapter","adapter","token","withRecordingSuppressed","prevSuppress","prevDirty","executeAndLog","label","h","renderOrderInternal","renderOrderFlat","renderOrderBucketed","renderOrderNodesInternal","renderOrderNodesFlat","renderOrderNodesBucketed","structureGeneration","orderCache","EMPTY_NODES","currentOrderCache","only","stack","buckets","bucket","rawJournals","wrapJournal","wrapped","raw","sceneHistory","opts","t","snapshot","journal","applyBatchNow","byLayer","fnKeysOf","nid","detached","r","fnKeys","patch","resized","parentNode","curId","sid","fromKey","toKey","desc","fromSibs","fromIndex","toSibs","toIndex","visible","locked","parallax","clamped","tagged","finalIndex","proposed","tempIndex","e","undo","redo","total","targetIndex","outermost","ownsArrivals","finished","versionBefore","nodes","specs","specsFromSerialized","json","applyConstructionSpecs","serialized","NODE_FN_FIELDS","sceneSelectionStore","sceneFromJSON"],"sources":["../../../src/core/scene/scene.ts"],"sourcesContent":["import { createHistory, type History, type HistorySelection, type Journal, type SerializedHistory } from '@weasel-js/history';\nimport type { Op } from 'core/ops/types';\nimport type { ParallaxOpts } from 'core/viewport/parallax';\nimport { rebuildOp as rebuildGlobalOp } from 'core/ops/registry';\nimport { createArrangeOp, type ArrangeArgs, type ArrangedPose } from 'core/ops/arrange';\nimport { SceneArrivalRefused } from './arrivals';\nimport { dwarn } from 'debug/flag';\nimport { createDependentsIndex, sameDependsOn } from './dependents';\nimport { withKitRegistry } from './kitRegistry';\nimport { dropPoseKeyedMemoSlots } from './nodeMemo';\nimport {\n createNodeFnFields,\n fnKeysOf,\n restoreFn,\n NODE_FN_FIELDS,\n type FnBearingNode,\n type NodeFn,\n type NodeFnField,\n} from './nodeFnFields';\nimport { createPoseOverrides } from './poseOverrides';\nimport { resized, resolveLayoutFrame, runLayoutPass } from './layoutPass';\nimport type { LayoutStrategy } from '../../layout/types';\nimport {\n asNodeId,\n type LayoutMove,\n type AddNodeSpec,\n type ContainerNode,\n type LayerRecord,\n type LeafNode,\n type Node,\n type NodeId,\n type RegisteredOp,\n type Scene,\n type SceneArrivalHandler,\n type SceneRegistry,\n type SerializedNode,\n type SerializedScene,\n type SerializedLayer,\n type UseSceneOptions,\n type UserLayerRecord,\n} from './types';\n\ninterface SceneState<TData, TLayer extends string, TPose> {\n nodes: Map<NodeId, Node<TData, TLayer, TPose>>;\n roots: NodeId[];\n layers: LayerRecord<TLayer>[];\n layerIndex: Map<TLayer, number>;\n}\n\nlet defaultIdCounter = 0;\nconst defaultGenerateId = (): NodeId =>\n asNodeId(`n${(defaultIdCounter++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`);\n\n/** One layer record from its snapshot form. A snapshot with no `kind` predates\n * user layers, so everything in it was a system layer. */\nfunction setParallax(record: { parallax?: ParallaxOpts }, to: ParallaxOpts | undefined): void {\n if (to === undefined) delete record.parallax;\n else record.parallax = to;\n}\n\nfunction layerFromSerialized<TLayer extends string>(\n spec: SerializedLayer<TLayer>,\n): LayerRecord<TLayer> {\n const base = {\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n return spec.kind === 'user'\n ? { ...base, kind: 'user', name: spec.name ?? spec.id }\n : { ...base, kind: 'system' };\n}\n\n/** Build a scene outside React. `useScene` is the usual entry point; reach for\n * this in tests, in headless rendering, or wherever a scene must outlive a\n * component. Throws if no system layers are declared. */\nexport function createScene<TData, TLayer extends string, TPose = import('../../features/groups/composePose').RectPose>(\n options: UseSceneOptions<TData, TLayer, TPose>,\n): Scene<TData, TLayer, TPose> {\n if (!options.systemLayers || options.systemLayers.length === 0) {\n throw new Error('useScene: systemLayers must declare at least one layer');\n }\n\n // ── State ──────────────────────────────────────────────────────────────\n const state: SceneState<TData, TLayer, TPose> = {\n nodes: new Map(),\n roots: [],\n layers: [],\n layerIndex: new Map(),\n };\n\n // The kit's own registry entries sit under the consumer's, so a snapshot\n // carrying a kit-attached function (a grouped container's derived pose)\n // reloads in any scene, not only one whose consumer registered the key.\n const registry = withKitRegistry(options.registry ?? {});\n\n /**\n * The registry-keyed function fields — `clipFromPose`, `derivePath`,\n * `derivePose` — each with its key maps and the side-channel cache the\n * `kit:add` redo path re-attaches from. A function cannot travel through a\n * serializable op payload, so `scene.add` and the `initial` loader stash it\n * here and the replayed op reads it back.\n *\n * Those caches are pruned at two hook points, both delivered via the history\n * engine's `onEvict`, to prevent unbounded growth:\n * 1. When the redo stack is cleared by a new op (branch-on-edit): any\n * kit:add in the discarded entries that references a node absent from\n * `state.nodes` is permanently unreachable — its cache entry is dropped.\n * 2. When the undo stack overflows `historyLimit` and evicts the oldest\n * entry: same reasoning applies to the evicted entries.\n * Invariant: after pruning, no entry remains for a node that is both absent\n * from `state.nodes` AND unreachable via any remaining undo/redo log entry.\n */\n const fnFields = createNodeFnFields<TPose>(registry);\n const fnField = (name: 'clipFromPose' | 'derivePath' | 'derivePose' | 'layout'): NodeFnField =>\n fnFields.find((f) => f.spec.field === name)!;\n\n /** How declared layouts are measured; see `LayoutFrame`. */\n const layoutFrame = resolveLayoutFrame(options.layoutFrame);\n /** Latched on the first layout a container is given, so a scene that never\n * declares one records exactly the entries it did before layouts existed. */\n let hasLayouts = false;\n {\n const field = fnField('layout');\n const write = field.write;\n (field as { write: NodeFnField['write'] }).write = (node, fn) => {\n if (node.kind === 'container') hasLayouts = true;\n write(node, fn);\n };\n }\n\n function layoutOfInternal(id: NodeId) {\n const node = state.nodes.get(id);\n return node?.kind === 'container' ? (node.layout ?? null) : null;\n }\n\n /** Maintained from `kit:add` / `kit:remove` — the only two places a node is\n * created or destroyed, and unlike `add`/`remove` they replay on undo/redo.\n * Only explicit `dependsOn` id lists are registered here; `'children'` is\n * the ancestor walk in `invalidateDependents` instead. */\n const dependents = createDependentsIndex();\n\n /** Nodes carrying `dependsOn: 'children'`. Empty in every scene that has no\n * container hugging its contents, which is what keeps the ancestor walk off\n * the hot path. */\n const childDerived = new Set<NodeId>();\n\n /** Walks `id`'s whole subtree. Not required while `Scene` stores absolute\n * poses and the render walks compose nothing; it is here so `derivePath`'s\n * world-pose contract still holds if they ever do. */\n function invalidateDependents(id: NodeId): void {\n invalidateChildDerivedFrom(state.nodes.get(id)?.parent ?? null);\n if (dependents.isEmpty()) return;\n const subtree: NodeId[] = [id];\n descendants(id, subtree);\n for (const src of subtree) {\n for (const dep of dependents.transitiveDependentsOf(src)) {\n const node = state.nodes.get(dep);\n if (node !== undefined) dropPoseKeyedMemoSlots(node);\n }\n }\n }\n\n /** A `dependsOn: 'children'` container derives from nodes the reverse index\n * never sees, so its invalidation runs the other way: up the parent chain\n * from `start` inclusive, and on to each such ancestor's own dependents.\n *\n * Callers that removed or reparented a node pass the parent explicitly —\n * a gone node cannot say who its parent was. */\n function invalidateChildDerivedFrom(start: NodeId | null): void {\n if (childDerived.size === 0) return;\n let cursor = start;\n while (cursor !== null) {\n const node = state.nodes.get(cursor);\n if (node === undefined) return;\n if (childDerived.has(cursor)) {\n dropPoseKeyedMemoSlots(node);\n for (const dep of dependents.transitiveDependentsOf(cursor)) {\n const d = state.nodes.get(dep);\n if (d !== undefined) dropPoseKeyedMemoSlots(d);\n }\n }\n cursor = node.parent;\n }\n }\n\n /** Track (or forget) a node whose `dependsOn` is `'children'`. Paired with\n * `dependents.add` / `.remove` at every site a node is created or destroyed. */\n function trackChildDerived(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n if (dependsOn === 'children') childDerived.add(id);\n else childDerived.delete(id);\n }\n\n /** Point `id` at a different set of dependencies, keeping both indices and\n * every memo that reads them in step. Shared by `kit:setDependsOn`'s two\n * directions, which differ only in which value they install.\n *\n * `id`'s own memo is dropped as well as its dependents': its derivation now\n * reads different sources, and nothing else would clear it. */\n function retarget(id: NodeId, dependsOn: Node<TData, TLayer, TPose>['dependsOn']): void {\n const node = requireNode(id) as { dependsOn?: readonly NodeId[] | 'children' };\n if (dependsOn === undefined) delete node.dependsOn;\n else node.dependsOn = dependsOn;\n dependents.add(id, dependsOn === undefined || dependsOn === 'children' ? [] : dependsOn);\n trackChildDerived(id, dependsOn);\n dropPoseKeyedMemoSlots(requireNode(id));\n invalidateDependents(id);\n }\n\n for (let i = 0; i < options.systemLayers.length; i++) {\n const spec = options.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`useScene: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push({\n kind: 'system',\n id: spec.id,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n });\n state.layerIndex.set(spec.id, i);\n }\n\n const generateId = options.generateId ?? defaultGenerateId;\n\n const listeners = new Set<() => void>();\n const registered = new Map<string, RegisteredOp<unknown>>();\n\n // Accessor for the adapter restored external ops apply against.\n let historyAdapterAccessor: (() => unknown) | null = null;\n\n /** Wrap a globally-rebuilt external op so apply resolves the history\n * adapter lazily — wiring order vs restoreHistory doesn't matter. An\n * unset accessor makes the op a debug-warned no-op, and an apply that\n * throws (e.g. the wired adapter lacks a method the op calls) degrades\n * the same way — never throws mid-undo, matching the placeholder\n * degradation policy. (The engine pops entries before applying, so an\n * uncaught throw would corrupt the stacks.) See `bindOpToAdapter` for\n * the live `applyBatch` path (fixed call-site adapter). */\n function bindOpToHistoryAdapter(op: Op): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => {\n const get = historyAdapterAccessor;\n if (!get) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" has no history adapter — skipping (setHistoryAdapter was not wired)`);\n return 'noop';\n }\n try {\n return op.apply(get());\n } catch (err) {\n dwarn('scene', `restored op \"${op.name ?? '?'}\" failed against the history adapter — skipping: ${String(err)}`);\n return 'noop';\n }\n },\n invert: () => bindOpToHistoryAdapter(op.invert()),\n };\n }\n\n // The scene's undo/redo engine. Recorded ops are `makeOp` wrappers over\n // `registered` handlers, so the engine's adapter argument is unused (the\n /** The transient set of active ids. Deliberately not part of `state`:\n * selection is not document content and never reaches `toJSON`. It is\n * handed to the history engine so entries can restore it. */\n let selection: readonly NodeId[] = [];\n\n /** Ephemeral per-node overrides. Deliberately not part of `state`, for the\n * same reason `selection` isn't: not document content, never reaches\n * `toJSON`, and never touches history. */\n const overrides = createPoseOverrides<TPose>(\n (id) => state.nodes.get(id),\n invalidateDependents,\n );\n\n // wrappers close over their payloads). Eviction (branch-edit redo-clears\n // + historyLimit overflow) drives function-field cache pruning via onEvict.\n const history = createHistory(undefined, {\n selection: {\n get: () => selection,\n set: (ids) => { selection = reachable(ids as readonly NodeId[]); notify(); },\n },\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n onEvict: (entry) => {\n // forwardOps and baseOps are the same array until a coalesce splits\n // them, so the double scan is cheap today and correct later.\n pruneCacheForDroppedOps(entry.forwardOps);\n pruneCacheForDroppedOps(entry.baseOps);\n },\n // Restore-time rebuild: scene-registered kinds (kit:* + consumer\n // registerOp) rebuild via makeOp; external ops rebuild via the global\n // op-factory registry, wrapped in the lazy history-adapter binding.\n // Return null only when the global registry also misses — the engine\n // then places its no-op placeholder. (The engine's own global-registry\n // fallback never fires for scene histories: this hook already\n // consulted it.)\n rebuildOp: (name, args) => {\n if (registered.has(name)) return makeOp(name, args);\n // Its writes are the scene's own, so it replays without an adapter.\n if (name === 'arrange') return createArrangeOp(args as ArrangeArgs, undefined, writePose);\n const rebuilt = rebuildGlobalOp(name, args);\n return rebuilt === null ? null : bindOpToHistoryAdapter(rebuilt);\n },\n });\n\n let version = 0;\n // Keyed by node object: every entry into `state.nodes` is a fresh object and\n // every edit mutates it in place, which is exactly an incarnation's lifetime.\n const incarnations = new WeakMap<object, number>();\n let nextIncarnation = 1;\n let batchDepth = 0;\n let currentBatch: { label: string; ops: Op[]; selectionBefore: readonly NodeId[] } | null = null;\n /** True while the history engine drives mutations (undo/redo/goto, journal\n * routing) — suppresses scene-side history recording so engine-applied\n * ops that re-enter scene mutation methods don't record twice. */\n let suppressRecording = false;\n /** Above zero inside `scene.untracked`, where the APIs that exist to\n * record refuse rather than record. */\n let untrackedDepth = 0;\n /** Above zero while the lock guard is lifted: `unlocked()`, `removeLayer`,\n * and every replay — undo, redo, a journal stepping, a rollback — which\n * restores a state that was legal when it was recorded. */\n let lockBypass = 0;\n /** Every kit op applied since the innermost `atomically` opened, so a\n * refused batch can revert what it already did. Null outside one. */\n let appliedLog: { kind: string; payload: unknown }[] | null = null;\n\n // ── Helpers ────────────────────────────────────────────────────────────\n // When `batchDepth > 0` the per-op `notify()` is coalesced: we still bump\n // the version so getVersion() reflects in-progress mutations, but we defer\n // listener dispatch until the outermost batch closes. This avoids one\n // React re-render per op during high-frequency gestures (e.g. snap moves\n // that emit ~10 transform ops per pointer-move).\n let batchDirty = false;\n // Mutable accessor for the active journal — seeded from options and\n // swappable via `scene.setActiveJournalAccessor(fn)` so mode machines that\n // depend on `scene.history` can wire it after construction.\n let activeJournalAccessor: (() => Journal | null) | null =\n options.getActiveJournal ?? null;\n\n // Container layout. `arrivals` is open (non-null) while a live edit is\n // collecting the nodes that joined a container, and `changed` every\n // container whose children or size it changed; whoever opened the window\n // settles it before the edit closes. Undo, redo and journal replays never\n // open it: they restore an arrangement that was already decided.\n let arrivalHandler: SceneArrivalHandler<TPose> | null = null;\n let arrivals: Map<NodeId, NodeId[]> | null = null;\n let departures = new Map<NodeId, NodeId[]>();\n let changed = new Set<NodeId>();\n /** What the last settle wrote, reported to `onReflow` once its edit lands. */\n let reflowDue: LayoutMove<TPose>[] | null = null;\n const reflowListeners = new Set<(moves: readonly LayoutMove<TPose>[]) => void>();\n\n /** The pass a scene runs over its declared layouts when nothing else is\n * installed. */\n const declaredLayouts: SceneArrivalHandler<TPose> = (arrived, touched, departed) =>\n runLayoutPass(scene, layoutOfInternal, arrived, touched, layoutFrame, departed);\n\n function activeHandler(): SceneArrivalHandler<TPose> | null {\n return arrivalHandler ?? (hasLayouts ? declaredLayouts : null);\n }\n\n function noteArrival(id: NodeId, parent: NodeId | null, from: NodeId | null): void {\n if (arrivals === null || parent === null || parent === from) return;\n changed.add(parent);\n const list = arrivals.get(parent);\n if (list === undefined) arrivals.set(parent, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n function noteDeparture(id: NodeId, from: NodeId | null, to: NodeId | null): void {\n if (arrivals === null || from === null || from === to) return;\n changed.add(from);\n // One that joined earlier in this edit was never there to leave.\n if (arrivals.get(from)?.includes(id)) return;\n const list = departures.get(from);\n if (list === undefined) departures.set(from, [id]);\n else if (!list.includes(id)) list.push(id);\n }\n\n /** A container's child set or order changed, or it changed size. */\n function noteChange(id: NodeId | null): void {\n if (arrivals !== null && id !== null) changed.add(id);\n }\n\n /** Whether a bare scene call has to run as a batch of its own, so the\n * layout pass it triggers lands in its undo step. */\n function bareLayoutEdit(): boolean {\n return activeHandler() !== null && arrivals === null && batchDepth === 0 && !suppressRecording;\n }\n\n /** Open the arrival window when a handler wants one — or `always`, for an\n * edit that may give the scene its first layout partway through — and no\n * enclosing edit holds it already; true when this caller now owns it. */\n function openArrivals(always = false): boolean {\n if (arrivals !== null || (!always && activeHandler() === null)) return false;\n arrivals = new Map();\n departures = new Map();\n changed = new Set();\n reflowDue = null;\n return true;\n }\n\n /** Report what the settled edit wrote, now that it has landed. */\n function emitReflow(): void {\n const moves = reflowDue;\n reflowDue = null;\n if (moves === null || moves.length === 0) return;\n for (const listener of [...reflowListeners]) listener(moves);\n }\n\n /** Close the window and ask the handler what the arrivals get. Throws\n * `SceneArrivalRefused` when it refuses, which reverts the edit. */\n function settleArrivals(): ArrangedPose[] {\n const pending = arrivals;\n arrivals = null;\n const handler = activeHandler();\n if (pending === null || handler === null) return [];\n // Only what is still there once the edit's other mutations have landed.\n const landed = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of pending) {\n const still = ids.filter((id) => state.nodes.get(id)?.parent === parent);\n if (still.length > 0 && state.nodes.has(parent)) landed.set(parent, still);\n }\n // Only what is gone from the container once the edit has landed: a child\n // that left and came back did not depart.\n const left = new Map<NodeId, NodeId[]>();\n for (const [parent, ids] of departures) {\n const gone = ids.filter((id) => state.nodes.get(id)?.parent !== parent);\n if (gone.length > 0 && state.nodes.has(parent)) left.set(parent, gone);\n }\n departures = new Map();\n const touched = new Set([...changed].filter((id) => state.nodes.get(id)?.kind === 'container'));\n if (landed.size === 0 && touched.size === 0) return [];\n const poses = handler(landed, touched, left);\n if (poses === null) throw new SceneArrivalRefused(landed);\n const out: ArrangedPose[] = [];\n for (const [id, to] of poses) {\n const node = state.nodes.get(id);\n if (node) out.push({ id, from: node.pose, to });\n }\n reflowDue = out as LayoutMove<TPose>[];\n return out;\n }\n\n function writePose(id: string, pose: unknown): void {\n scene.setPose(asNodeId(id), pose as TPose);\n }\n\n /** Whether `op` is a `createSetLayoutOp` giving a container a layout. An\n * edit's op list is fixed before it runs, so a layout-less scene has to see\n * this coming to append the arrange op its first layout needs. */\n function givesLayout(op: Op): boolean {\n return op.name === 'setLayout' && (op.args as { to?: unknown } | undefined)?.to != null;\n }\n\n /** `ops` plus the op that settles their arrivals, when this call owns the\n * window; `ops` unchanged otherwise. */\n function withArrivalOps(ops: Op[]): { ops: Op[]; owned: boolean } {\n if (!openArrivals(ops.some(givesLayout))) return { ops, owned: false };\n return { ops: [...ops, createArrangeOp({}, settleArrivals, writePose)], owned: true };\n }\n\n /** Run an op-driven edit that may carry arrivals: a refusal reverts it and\n * is swallowed, the way a drop onto a full container is — nothing lands. */\n function runArrivalEdit(ops: Op[], run: (ops: Op[]) => void): void {\n const { ops: all, owned } = withArrivalOps(ops);\n try {\n run(all);\n if (owned) emitReflow();\n } catch (err) {\n if (!(err instanceof SceneArrivalRefused)) throw err;\n } finally {\n if (owned) {\n arrivals = null;\n reflowDue = null;\n }\n }\n }\n\n function isLockedInternal(id: NodeId): boolean {\n if (!state.layers.some((l) => l.locked)) return false;\n let cur = state.nodes.get(id);\n while (cur !== undefined) {\n if (state.layers[state.layerIndex.get(cur.layer) ?? -1]?.locked) return true;\n cur = cur.parent === null ? undefined : state.nodes.get(cur.parent);\n }\n return false;\n }\n\n function refuseUntracked(verb: string): void {\n if (untrackedDepth > 0) throw new Error(`Scene: cannot ${verb} inside untracked() — it records`);\n }\n\n function refuseLocked(id: NodeId, verb: string): void {\n if (lockBypass > 0 || !isLockedInternal(id)) return;\n throw new Error(`Scene: cannot ${verb} \"${id}\" — it is on a locked layer`);\n }\n\n function refuseLockedLayer(layer: TLayer, verb: string): void {\n if (lockBypass > 0 || !state.layers[state.layerIndex.get(layer) ?? -1]?.locked) return;\n throw new Error(`Scene: cannot ${verb} layer \"${layer}\" — it is locked`);\n }\n\n /** The scene's selection never holds a locked node, whoever writes it. */\n function reachable(ids: readonly NodeId[]): readonly NodeId[] {\n if (!state.layers.some((l) => l.locked)) return ids;\n return ids.filter((id) => !isLockedInternal(id));\n }\n\n function withLocksLifted<T>(fn: () => T): T {\n lockBypass++;\n try {\n return fn();\n } finally {\n lockBypass--;\n }\n }\n\n /**\n * Run `fn` as all-or-nothing: if it throws, every kit op it applied is\n * reverted, newest first, and the selection goes back to where it was.\n * The log is at kit-op grain rather than per external op, because one\n * external op can issue several scene mutations (a container move cascading\n * to its children) and fail halfway through its own.\n *\n * On success the ops join an enclosing log only when `ownsEntry` says no\n * history entry holds them: reverting ops an entry still claims would leave\n * undo replaying a change that is no longer there.\n */\n function atomically<T>(fn: () => T, ownsEntry: () => boolean): T {\n const outer = appliedLog;\n const log: { kind: string; payload: unknown }[] = [];\n const selectionBefore = selection;\n appliedLog = log;\n try {\n const result = fn();\n if (outer && !ownsEntry()) outer.push(...log);\n return result;\n } catch (err) {\n appliedLog = null;\n withLocksLifted(() => {\n for (let i = log.length - 1; i >= 0; i--) {\n const { kind, payload } = log[i];\n registered.get(kind)!.revert(payload);\n }\n });\n selection = selectionBefore;\n if (log.length > 0) notify();\n throw err;\n } finally {\n appliedLog = outer;\n }\n }\n\n function notify(): void {\n version++;\n if (batchDepth > 0) {\n batchDirty = true;\n return;\n }\n for (const listener of listeners) listener();\n }\n\n /**\n * Prune the function-field caches of nodes referenced only by ops in entries\n * that just became permanently unreachable (redo entries dropped by a branch\n * edit, or undo entries evicted by `historyLimit`) — wired to the engine's\n * `onEvict`. An entry is safe to drop when the node is absent from\n * `state.nodes`: its only path back into the scene was through these\n * now-unreachable ops.\n */\n function pruneCacheForDroppedOps(ops: readonly Op[]): void {\n if (fnFields.every((f) => f.pending.size === 0)) return;\n for (const op of ops) {\n if (op.name !== 'kit:add') continue;\n const id = (op.args as { id?: NodeId } | null)?.id;\n if (id && !state.nodes.has(id)) {\n for (const field of fnFields) field.pending.delete(id);\n }\n }\n }\n\n function requireNode(id: NodeId): Node<TData, TLayer, TPose> {\n const n = state.nodes.get(id);\n if (!n) throw new Error(`Scene: unknown node id \"${id}\"`);\n return n;\n }\n\n function requireLayerIndex(layer: TLayer): number {\n const i = state.layerIndex.get(layer);\n if (i === undefined) throw new Error(`Scene: unknown layer \"${layer}\"`);\n return i;\n }\n\n /** Repopulate `state.layerIndex` from the current `state.layers` order.\n * Call after any op that inserts, removes, or reorders a layer record. */\n function rebuildLayerIndex(): void {\n invalidateOrder();\n state.layerIndex.clear();\n for (let i = 0; i < state.layers.length; i++) {\n state.layerIndex.set(state.layers[i].id, i);\n }\n }\n\n /**\n * A child may sit on its parent's layer **or any layer above it** (higher\n * render index) — never below. `renderOrder()` / `toJSON()` are layer-major\n * (each node yielded in its OWN layer's pass) and `buildSceneTree` buckets by\n * each node's own layer, so a child on a higher layer than its parent renders\n * correctly on top while staying a tree child for hit-testing / move /\n * reparent (e.g. plantings tagged into a top `plantings` layer while remaining\n * children of their container). Rejecting only the *below* case keeps the\n * sensible invariant that a child never paints under its own parent.\n */\n function assertSubtreeLayer(\n nodeId: string | undefined,\n nodeLayer: TLayer,\n parentId: NodeId,\n parentLayer: TLayer,\n verb: 'place' | 'relayer' = 'place',\n ): void {\n if (requireLayerIndex(nodeLayer) < requireLayerIndex(parentLayer)) {\n const action = verb === 'place'\n ? `cannot place node '${nodeId ?? '<new>'}' on layer '${nodeLayer}' under parent '${parentId}' on layer '${parentLayer}'`\n : `cannot setLayer('${nodeId ?? '<new>'}', '${nodeLayer}') — node has parent '${parentId}' on layer '${parentLayer}'`;\n throw new Error(`Scene: ${action} — a child may not render below its parent's layer`);\n }\n }\n\n function siblingsOf(parent: NodeId | null): NodeId[] {\n if (parent === null) return state.roots;\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n return p.children;\n }\n\n function detach(id: NodeId): { parent: NodeId | null; index: number } {\n const node = requireNode(id);\n const sibs = siblingsOf(node.parent);\n const idx = sibs.indexOf(id);\n if (idx < 0) throw new Error(`Scene: node \"${id}\" not found in its parent's children`);\n sibs.splice(idx, 1);\n invalidateOrder();\n return { parent: node.parent, index: idx };\n }\n\n function attach(id: NodeId, parent: NodeId | null, index: number): void {\n const sibs = siblingsOf(parent);\n const i = Math.max(0, Math.min(index, sibs.length));\n sibs.splice(i, 0, id);\n const node = requireNode(id);\n (node as { parent: NodeId | null }).parent = parent;\n invalidateOrder();\n }\n\n function descendants(id: NodeId, out: NodeId[]): void {\n const n = state.nodes.get(id);\n if (!n || n.kind !== 'container') return;\n for (const c of n.children) {\n out.push(c);\n descendants(c, out);\n }\n }\n\n /** Everything removing `rootIds` takes with it: each root's subtree, then\n * every node deriving from any of those, then those nodes' subtrees in turn.\n * A dependent is not a descendant, so the second pass is a separate\n * reachability walk; `ids` grows as it runs, which is what carries the\n * cascade transitively and upward through a dependent's own ancestors.\n *\n * Published as {@link Scene.removalClosure}, which is what the delete op and\n * `buildDeleteOps` ask instead of rebuilding the walk from `dependsOn` and\n * `children` — a third cascade relation is then added here alone. */\n function removalClosure(rootIds: readonly NodeId[]): {\n ids: NodeId[];\n removing: Set<NodeId>;\n } {\n const ids: NodeId[] = [];\n const removing = new Set<NodeId>();\n function take(id: NodeId): void {\n if (removing.has(id)) return;\n removing.add(id);\n ids.push(id);\n const sub: NodeId[] = [];\n descendants(id, sub);\n for (const s of sub) {\n if (removing.has(s)) continue;\n removing.add(s);\n ids.push(s);\n }\n }\n for (const root of rootIds) take(root);\n for (let i = 0; i < ids.length; i++) {\n for (const dep of dependents.transitiveDependentsOf(ids[i])) take(dep);\n }\n return { ids, removing };\n }\n\n /** Post-patch the registry-keyed function fields onto a node after its\n * `kit:add` op runs. A function cannot travel through the serializable op\n * payload, so it is attached to the live node here. `cacheForRedo` also\n * keeps the reference in the field's pending map, which is where the\n * `kit:add` redo path reads it from — redo replays the op without a spec.\n * `dependsOn` is plain data and rides the payload instead. */\n function patchNodeFunctions(\n spec: AddNodeSpec<TData, TLayer, TPose>,\n id: NodeId,\n { cacheForRedo }: { cacheForRedo: boolean },\n ): void {\n const node = state.nodes.get(id) as FnBearingNode | undefined;\n if (node === undefined) return;\n for (const field of fnFields) {\n const fn = (spec as unknown as Record<string, unknown>)[field.spec.field] as NodeFn | undefined;\n if (fn === undefined) continue;\n if (field.spec.containersOnly && spec.kind !== 'container') continue;\n field.write(node, fn);\n if (cacheForRedo) field.pending.set(id, fn);\n }\n }\n\n /** Re-attach those fields to a node restored from a `kit:remove` snapshot.\n * In-session the clone already carries them; a persisted history does not,\n * so the registry keys are what is left. */\n function restoreNodeFunctions(\n node: Node<TData, TLayer, TPose>,\n keys: Record<string, string | undefined> | undefined,\n ): void {\n if (!keys) return;\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n if (field.read(target) !== undefined) continue;\n const key = keys[field.spec.opKey];\n if (key === undefined) continue;\n restoreFn(field, target, key, 'kit:remove', dwarn);\n }\n }\n\n // ── Internal kit op kinds ──────────────────────────────────────────────\n // These are registered like any other op; the kit's mutation methods build\n // serializable payloads and route through the same log/replay machinery.\n function registerKitOp<P>(kind: string, handler: RegisteredOp<P>): void {\n registered.set(kind, handler as RegisteredOp<unknown>);\n }\n\n registerKitOp<{\n id: NodeId; kind: 'leaf' | 'container'; layer: TLayer; pose: TPose; data: TData;\n parent: NodeId | null; index: number;\n dependsOn?: readonly NodeId[] | 'children';\n pickable?: boolean;\n } & Record<string, unknown>>('kit:add', {\n apply: (p) => {\n if (state.nodes.has(p.id)) {\n throw new Error(`Scene: id collision on \"${p.id}\"`);\n }\n const node: Node<TData, TLayer, TPose> = p.kind === 'container'\n ? ({ kind: 'container', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent, children: [] } as ContainerNode<TData, TLayer, TPose>)\n : ({ kind: 'leaf', id: p.id, layer: p.layer, pose: p.pose, data: p.data, parent: p.parent } as LeafNode<TData, TLayer, TPose>);\n state.nodes.set(p.id, node);\n attach(p.id, p.parent, p.index);\n if (p.dependsOn !== undefined) node.dependsOn = p.dependsOn;\n if (p.pickable !== undefined) node.pickable = p.pickable;\n dependents.add(p.id, p.dependsOn === 'children' ? [] : p.dependsOn ?? []);\n trackChildDerived(p.id, p.dependsOn);\n // Two ways a function field comes back. The redo path reads the\n // side-channel cache the original `scene.add` filled, because redo\n // replays the op without a spec. The restore path — a fresh session,\n // empty cache — resolves the registry key the payload carries, and\n // seeds the cache so later undo/redo cycles behave like the live one.\n const target = node as unknown as FnBearingNode;\n for (const field of fnFields) {\n const cached = field.pending.get(p.id);\n if (cached !== undefined) {\n field.write(target, cached);\n continue;\n }\n const key = p[field.spec.opKey] as string | undefined;\n if (key !== undefined) restoreFn(field, target, key, 'kit:add', dwarn);\n }\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n state.nodes.delete(p.id);\n dependents.remove(p.id);\n childDerived.delete(p.id);\n invalidateChildDerivedFrom(p.parent);\n invalidateDependents(p.id);\n // Note: we intentionally do NOT delete the pending function-field\n // entries — redo re-applies the node and re-attaches from them.\n },\n });\n\n /**\n * Snapshot of every node a removal deletes, so revert restores it exactly.\n *\n * A cascade unlinks several disjoint subtrees, not one, so `detached` names\n * each node the tree has to re-link; everything else in `nodes` has a parent\n * that is also going and rides back in that parent's cloned `children`.\n * Entries are sorted by ascending sibling index — globally rather than\n * per-parent, because only same-parent order constrains re-insertion and\n * entries under different parents never interact.\n */\n interface RemoveSnapshot {\n nodes: Node<TData, TLayer, TPose>[];\n detached: { id: NodeId; parent: NodeId | null; index: number }[];\n /** Registry keys for the function-valued fields on `nodes`. The functions\n * themselves do not survive a persisted history, so revert re-resolves\n * them the way `kit:add` does. */\n fnKeys?: ({ id: NodeId } & Record<string, string | undefined>)[];\n }\n // Neither half invalidates dependents: removal's closure takes every live one.\n registerKitOp<RemoveSnapshot>('kit:remove', {\n apply: (p) => {\n for (const d of p.detached) detach(d.id);\n for (const n of p.nodes) {\n state.nodes.delete(n.id);\n dependents.remove(n.id);\n childDerived.delete(n.id);\n }\n // A `dependsOn: 'children'` container the removal did not take is now\n // hugging a smaller set.\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n revert: (p) => {\n const keys = new Map((p.fnKeys ?? []).map((k) => [k.id, k]));\n // Order-independent: every clone carries its own parent and children.\n for (const n of p.nodes) {\n const clone: Node<TData, TLayer, TPose> = n.kind === 'container'\n ? { ...n, children: [...n.children] }\n : { ...n };\n restoreNodeFunctions(clone, keys.get(n.id));\n state.nodes.set(n.id, clone);\n dependents.add(n.id, clone.dependsOn === 'children' ? [] : clone.dependsOn ?? []);\n trackChildDerived(n.id, clone.dependsOn);\n }\n for (const d of p.detached) attach(d.id, d.parent, d.index);\n for (const d of p.detached) invalidateChildDerivedFrom(d.parent);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TPose; to: TPose }>('kit:setPose', {\n apply: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { pose: TPose }).pose = p.from;\n invalidateDependents(p.id);\n },\n });\n\n // A derivation is handed its dependencies' nodes, not only their poses, so a\n // connector reading `data` or `layer` goes stale on these two exactly as it\n // does on a move.\n registerKitOp<{ id: NodeId; from: TData; to: TData }>('kit:setData', {\n apply: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.to;\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { data: TData }).data = p.from;\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ id: NodeId; from: TLayer; to: TLayer }>('kit:setLayer', {\n apply: (p) => {\n requireLayerIndex(p.to);\n (requireNode(p.id) as { layer: TLayer }).layer = p.to;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n revert: (p) => {\n (requireNode(p.id) as { layer: TLayer }).layer = p.from;\n invalidateOrder();\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{\n id: NodeId;\n from: Node<TData, TLayer, TPose>['dependsOn'];\n to: Node<TData, TLayer, TPose>['dependsOn'];\n }>('kit:setDependsOn', {\n apply: (p) => { retarget(p.id, p.to); },\n revert: (p) => { retarget(p.id, p.from); },\n });\n\n /** The strategies each live `kit:setLayout` payload swaps between. A payload\n * replayed from a persisted history has none, and resolves its keys. */\n const layoutRefs = new WeakMap<object, { from: LayoutStrategy<TPose> | null; to: LayoutStrategy<TPose> | null }>();\n interface SetLayoutPayload { id: NodeId; fromKey?: string; toKey?: string }\n function placeLayout(p: SetLayoutPayload, side: 'from' | 'to'): void {\n const node = requireNode(p.id) as unknown as FnBearingNode;\n const field = fnField('layout');\n const live = layoutRefs.get(p);\n const key = side === 'from' ? p.fromKey : p.toKey;\n if (live === undefined && key !== undefined) {\n delete node.layout;\n restoreFn(field, node, key, 'kit:setLayout', dwarn);\n return;\n }\n const layout = live?.[side] ?? null;\n if (layout === null) delete node.layout;\n else field.write(node, layout);\n }\n registerKitOp<SetLayoutPayload>('kit:setLayout', {\n apply: (p) => { placeLayout(p, 'to'); },\n revert: (p) => { placeLayout(p, 'from'); },\n });\n\n registerKitOp<{\n id: NodeId; fromParent: NodeId | null; fromIndex: number;\n toParent: NodeId | null; toIndex: number;\n }>('kit:move', {\n apply: (p) => {\n detach(p.id);\n attach(p.id, p.toParent, p.toIndex);\n // Both ends: the container it left no longer hugs it, and the one it\n // joined now does.\n invalidateChildDerivedFrom(p.fromParent);\n invalidateDependents(p.id);\n },\n revert: (p) => {\n detach(p.id);\n attach(p.id, p.fromParent, p.fromIndex);\n invalidateChildDerivedFrom(p.toParent);\n invalidateDependents(p.id);\n },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerVisible', {\n apply: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.to; },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].visible = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from: boolean; to: boolean }>('kit:setLayerLocked', {\n apply: (p) => {\n state.layers[requireLayerIndex(p.layer)].locked = p.to;\n if (p.to) selection = reachable(selection);\n },\n revert: (p) => { state.layers[requireLayerIndex(p.layer)].locked = p.from; },\n });\n\n registerKitOp<{ layer: TLayer; from?: ParallaxOpts; to?: ParallaxOpts }>('kit:setLayerParallax', {\n apply: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.to); },\n revert: (p) => { setParallax(state.layers[requireLayerIndex(p.layer)], p.from); },\n });\n\n registerKitOp<{ record: UserLayerRecord<TLayer>; index: number }>('kit:addLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 0, { ...p.record });\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ record: LayerRecord<TLayer>; index: number }>('kit:removeLayer', {\n apply: (p) => {\n state.layers.splice(p.index, 1);\n rebuildLayerIndex();\n },\n revert: (p) => {\n state.layers.splice(p.index, 0, { ...p.record } as LayerRecord<TLayer>);\n rebuildLayerIndex();\n },\n });\n\n registerKitOp<{ layer: TLayer; from: string; to: string }>('kit:renameLayer', {\n apply: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.to;\n },\n revert: (p) => {\n (state.layers[requireLayerIndex(p.layer)] as UserLayerRecord<TLayer>).name = p.from;\n },\n });\n\n registerKitOp<{ layer: TLayer; from: number; to: number }>('kit:moveLayer', {\n apply: (p) => {\n const [rec] = state.layers.splice(p.from, 1);\n state.layers.splice(p.to, 0, rec);\n rebuildLayerIndex();\n },\n revert: (p) => {\n const [rec] = state.layers.splice(p.to, 1);\n state.layers.splice(p.from, 0, rec);\n rebuildLayerIndex();\n },\n });\n\n // ── Op execution (used by both kit mutations and consumer recordOp) ────\n function runOp(kind: string, payload: unknown): void {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n handler.apply(payload);\n }\n\n /** Bridge a registered scene op into an engine `Op`: a direction-flipping\n * wrapper over the `RegisteredOp`'s `apply`/`revert` pair. `invert()`\n * flips the direction with the same payload, so undo replays `revert`\n * and redo replays `apply` — no per-op inverse code. `name`/`args` carry\n * the (kind, payload) pair for eviction pruning (and, later,\n * serialization). Handler lookup happens at apply time so re-registered\n * kinds take effect on replay, but existence is checked eagerly to fail\n * fast at the call site. */\n function makeOp(kind: string, payload: unknown, dir: 'fwd' | 'rev' = 'fwd'): Op {\n if (!registered.has(kind)) {\n throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n }\n return {\n name: kind,\n args: payload,\n coalesceKey: coalesceKeyFor(kind, payload),\n apply: () => {\n const handler = registered.get(kind);\n if (!handler) throw new Error(`Scene: no registered op for kind \"${kind}\"`);\n (dir === 'fwd' ? handler.apply : handler.revert)(payload);\n },\n invert: () => makeOp(kind, payload, dir === 'fwd' ? 'rev' : 'fwd'),\n };\n }\n\n /** Rebind an external op to the adapter supplied at the `applyBatch` call\n * site — the scene's engine was constructed without an adapter, so ops\n * it stores and later replays must close over the right one. Forwards\n * the apply return value (no-op detection) and preserves\n * `coalesceKey`/`name`/`args`/`label` for coalescing and eviction. See\n * `bindOpToHistoryAdapter` for RESTORED entries (lazy accessor). */\n function bindOpToAdapter(op: Op, adapter: unknown): Op {\n return {\n name: op.name,\n args: op.args,\n label: op.label,\n coalesceKey: op.coalesceKey,\n apply: () => op.apply(adapter),\n invert: () => bindOpToAdapter(op.invert(), adapter),\n };\n }\n\n /** Best-effort coalesce-grouping token: node ops carry `payload.id`,\n * layer ops `payload.layer`. Payloads with neither get no key and never\n * coalesce (the engine treats a missing key on either side as\n * \"new entry\"). Keys only take effect when the scene opts in via\n * `UseSceneOptions.coalesceWindowMs` (default `0`, which disables\n * coalescing entirely). */\n function coalesceKeyFor(kind: string, payload: unknown): string | undefined {\n if (payload === null || typeof payload !== 'object') return undefined;\n const p = payload as { id?: unknown; layer?: unknown };\n const token =\n typeof p.id === 'string' ? p.id\n : typeof p.layer === 'string' ? p.layer\n : undefined;\n return token === undefined ? undefined : `${kind}:${token}`;\n }\n\n /** Run `fn` with scene-side recording suppressed and per-op notifies\n * batched. Used whenever the engine drives mutations (undo/redo/goto):\n * engine-applied ops may re-enter scene mutation methods, which must\n * apply but not record. The caller fires exactly one `notify()` after. */\n function withRecordingSuppressed<T>(fn: () => T): T {\n const prevSuppress = suppressRecording;\n suppressRecording = true;\n batchDepth++;\n const prevDirty = batchDirty;\n try {\n return fn();\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n batchDirty = prevDirty;\n }\n }\n\n function executeAndLog(kind: string, payload: unknown, label: string): void {\n if (suppressRecording) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n notify();\n return;\n }\n if (currentBatch) {\n runOp(kind, payload);\n appliedLog?.push({ kind, payload });\n currentBatch.ops.push(makeOp(kind, payload));\n notify();\n return;\n }\n // The engine applies the op itself (inside applyOps) — no separate\n // runOp call, or the mutation would run twice.\n history.applyOps([makeOp(kind, payload)], label);\n notify();\n }\n\n // ── Public Scene object ────────────────────────────────────────────────\n\n // Register consumer-supplied ops up front.\n if (options.ops) {\n for (const [k, h] of Object.entries(options.ops)) {\n registered.set(k, h);\n }\n }\n\n /**\n * Layer-major DFS-preorder ids, and the same sequence as nodes. Four walks\n * for two sequences, which wants explaining, because collapsing them is the\n * obvious cleanup and each collapse was measured to cost something:\n *\n * - ids vs nodes: projecting one from the other is a whole extra pass, worth\n * 20% of `renderOrder()` on a multi-layer scene.\n * - flat vs bucketed: a single layer needs no buckets and can compare the\n * layer id instead of indexing it, which is 1.4x. Behind a branch in one\n * function it also slows the bucketed path by 20% — the two shapes share\n * one optimized body, and whichever ran first wins it.\n *\n * All four emit the same order and `renderOrder.test.ts` holds them to it.\n */\n function renderOrderInternal(): NodeId[] {\n return state.layers.length === 1 ? renderOrderFlat() : renderOrderBucketed();\n }\n\n function renderOrderNodesInternal(): Node<TData, TLayer, TPose>[] {\n return state.layers.length === 1 ? renderOrderNodesFlat() : renderOrderNodesBucketed();\n }\n\n /**\n * Render order survives everything except a structural edit, so both walks\n * are cached against a counter the structural writers bump: `attach` and\n * `detach` (add / remove / reparent / reorder), `kit:setLayer` (which bucket\n * a node lands in), `rebuildLayerIndex` (the layer list itself), and\n * `loadState`. Pose and data edits leave order alone and must NOT invalidate\n * — they fire per frame during a drag, which is exactly when the cache pays.\n *\n * A missed bump is a silent wrong answer: nodes painted in the wrong z-order,\n * or unpickable. `renderOrder.test.ts` walks each structural op and asserts\n * the order moved.\n */\n let structureGeneration = 0;\n let orderCache: {\n gen: number;\n ids?: NodeId[];\n nodes?: Node<TData, TLayer, TPose>[];\n byLayer?: Map<TLayer, Node<TData, TLayer, TPose>[]>;\n } = { gen: 0 };\n\n function invalidateOrder(): void {\n structureGeneration++;\n }\n\n const EMPTY_NODES: readonly Node<TData, TLayer, TPose>[] = [];\n\n function currentOrderCache(): typeof orderCache {\n if (orderCache.gen !== structureGeneration) {\n orderCache = { gen: structureGeneration };\n }\n return orderCache;\n }\n\n function renderOrderFlat(): NodeId[] {\n const only = state.layers[0].id;\n const out: NodeId[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n function renderOrderNodesFlat(): Node<TData, TLayer, TPose>[] {\n const only = state.layers[0].id;\n const out: Node<TData, TLayer, TPose>[] = [];\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n if (node.layer === only) out.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n return out;\n }\n\n /** One DFS of the tree, bucketed by layer: appending in preorder keeps each\n * bucket in preorder, so concatenating them is the layer-major sequence. */\n function renderOrderBucketed(): NodeId[] {\n const buckets: NodeId[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(id);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: NodeId[] = [];\n for (const bucket of buckets) {\n for (const id of bucket) out.push(id);\n }\n return out;\n }\n\n function renderOrderNodesBucketed(): Node<TData, TLayer, TPose>[] {\n const buckets: Node<TData, TLayer, TPose>[][] = state.layers.map(() => []);\n const stack: NodeId[] = [...state.roots].reverse();\n while (stack.length > 0) {\n const id = stack.pop()!;\n const node = state.nodes.get(id);\n if (!node) continue;\n const bucket = buckets[state.layerIndex.get(node.layer) ?? -1];\n if (bucket) bucket.push(node);\n if (node.kind === 'container') {\n for (let i = node.children.length - 1; i >= 0; i--) {\n stack.push(node.children[i]);\n }\n }\n }\n const out: Node<TData, TLayer, TPose>[] = [];\n for (const bucket of buckets) {\n for (const node of bucket) out.push(node);\n }\n return out;\n }\n\n // ── scene.history ──────────────────────────────────────────────────────\n // The `History` the kit's `undo`/`redo` actions resolve their `history` dep\n // to, and the handle a mode machine opens journals against. Handing out\n // `history` (the engine) directly would let an action-driven undo replay ops\n // with scene-side recording still armed and without bumping the version, so\n // every member that mutates routes through the scene's own wrapper\n // (`withRecordingSuppressed` + one `notify()`); reads forward to the engine.\n\n /** Wrapped journal → the engine's own, for `resumeJournal`: the engine keys\n * resumability off journal identity, which a wrapper would not match. */\n const rawJournals = new WeakMap<Journal, Journal>();\n\n /** Same treatment as the façade: a journal drives adapter mutation itself,\n * so its applies/undos re-enter scene mutation methods. */\n function wrapJournal(raw: Journal): Journal {\n const wrapped: Journal = {\n targetId: raw.targetId,\n forkedAtEntryId: raw.forkedAtEntryId,\n applyBatch(ops, label) {\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => raw.applyBatch(all, label)), () => true);\n notify();\n });\n },\n undo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.undo()));\n notify();\n },\n redo() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.redo()));\n notify();\n },\n canUndo: () => raw.canUndo(),\n canRedo: () => raw.canRedo(),\n entries: () => raw.entries(),\n seal: () => raw.seal(),\n getVersion: () => raw.getVersion(),\n subscribe: (listener) => raw.subscribe(listener),\n commit(label) {\n // Flushes the session's net ops to the parent stack — no apply, but\n // the parent's undo depth changes and listeners read that.\n raw.commit(label);\n notify();\n },\n cancel() {\n withLocksLifted(() => withRecordingSuppressed(() => raw.cancel()));\n notify();\n },\n suspend: () => raw.suspend(),\n isActive: () => raw.isActive(),\n };\n rawJournals.set(wrapped, raw);\n return wrapped;\n }\n\n const sceneHistory: History = {\n // Mutating: applied ops re-enter the scene's own mutation methods.\n apply(op, label) {\n refuseUntracked('history.apply');\n runArrivalEdit([op], (all) => {\n const run = () => (all.length === 1\n ? history.apply(op, label)\n : history.applyOps(all, label ?? op.label ?? ''));\n atomically(() => withRecordingSuppressed(run), () => true);\n notify();\n });\n },\n applyOps(ops, label) {\n refuseUntracked('history.applyOps');\n runArrivalEdit(ops, (all) => {\n atomically(() => withRecordingSuppressed(() => history.applyOps(all, label)), () => true);\n notify();\n });\n },\n undo: () => { scene.undo(); },\n redo: () => { scene.redo(); },\n goto: (n) => { scene.jumpToHistoryIndex(n); },\n // Stack-only: nothing applies, but what `canUndo()` answers changes.\n clear() {\n history.clear();\n notify();\n },\n recordEntry(ops, label, opts) {\n history.recordEntry(ops, label, opts);\n notify();\n },\n prune(t) {\n history.prune(t);\n notify();\n },\n switchBranch(id) {\n history.switchBranch(id);\n notify();\n },\n restore: (snapshot) => { scene.restoreHistory(snapshot); },\n // Reads forward to the engine, `version` included: it counts history\n // operations, where the scene's counts every mutation.\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n undoDepth: () => history.undoDepth(),\n redoDepth: () => history.redoDepth(),\n entries: () => history.entries(),\n timestampAt: (i) => history.timestampAt(i),\n depthAt: (t) => history.depthAt(t),\n branches: () => history.branches(),\n getVersion: () => history.getVersion(),\n subscribe: (listener) => history.subscribe(listener),\n serialize: () => history.serialize(),\n allForwardOps: () => history.allForwardOps(),\n seal: () => history.seal(),\n currentEntryId: () => history.currentEntryId(),\n beginJournal: (opts) => wrapJournal(history.beginJournal(opts)),\n resumeJournal: (journal) => history.resumeJournal(rawJournals.get(journal) ?? journal),\n };\n\n function applyBatchNow(ops: Op[], label: string, adapter: unknown): void {\n const journal: Journal | null = (activeJournalAccessor ?? (() => null))();\n // Either route drives mutations from a history engine (the journal's\n // inner history, or the scene's own), so scene-side recording is\n // suppressed for the duration: op applies that re-enter scene\n // mutation methods via the adapter must mutate without re-recording.\n // batchDepth coalesces the per-op notify() calls (same as\n // scene.batch); exactly one listener dispatch fires at the end —\n // mirroring the single-notification semantics callers expect.\n const prevSuppress = suppressRecording;\n const prevDirty = batchDirty;\n suppressRecording = true;\n batchDepth++;\n batchDirty = false;\n try {\n atomically(() => {\n if (journal) {\n journal.applyBatch(ops, label);\n } else {\n // Native path: record the external ops themselves as one engine\n // entry — coalescible across applyBatch calls via their own\n // coalesceKeys — rebound to this call's adapter.\n history.applyOps(ops.map((op) => bindOpToAdapter(op, adapter)), label);\n }\n }, () => true);\n } finally {\n batchDepth--;\n suppressRecording = prevSuppress;\n // Re-merge any outer batch's pending dirt so a nested call can't\n // swallow it; at true top level prevDirty is always false.\n batchDirty = batchDirty || prevDirty;\n // Flush inside finally so a throwing op can't strand subscribers\n // after earlier ops in the batch already mutated state (mirrors\n // scene.batch). Depth-guarded: a nested context defers to the\n // outermost flush.\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n\n const scene: Scene<TData, TLayer, TPose> = {\n get nodes() { return state.nodes; },\n get roots() { return state.roots; },\n get layers() { return state.layers; },\n registry,\n\n get(id) { return state.nodes.get(id); },\n incarnation(id) {\n const node = state.nodes.get(id);\n if (!node) return undefined;\n let token = incarnations.get(node);\n if (token === undefined) {\n token = nextIncarnation++;\n incarnations.set(node, token);\n }\n return token;\n },\n\n childrenOf(id) {\n const n = state.nodes.get(id);\n return n && n.kind === 'container' ? n.children : [];\n },\n\n ancestorsOf(id) {\n const out: NodeId[] = [];\n let cur = state.nodes.get(id)?.parent ?? null;\n while (cur !== null) {\n out.push(cur);\n cur = state.nodes.get(cur)?.parent ?? null;\n }\n return out;\n },\n\n renderOrder() {\n const c = currentOrderCache();\n return (c.ids ??= renderOrderInternal());\n },\n\n renderOrderNodes() {\n const c = currentOrderCache();\n return (c.nodes ??= renderOrderNodesInternal());\n },\n\n nodesOnLayer(layer) {\n const c = currentOrderCache();\n let byLayer = c.byLayer;\n if (!byLayer) {\n byLayer = new Map();\n for (const node of (c.nodes ??= renderOrderNodesInternal())) {\n let bucket = byLayer.get(node.layer);\n if (!bucket) byLayer.set(node.layer, (bucket = []));\n bucket.push(node);\n }\n c.byLayer = byLayer;\n }\n return byLayer.get(layer) ?? EMPTY_NODES;\n },\n\n add(spec) {\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n refuseLockedLayer(spec.layer, 'add to');\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n refuseLocked(parent, 'add under');\n }\n if (parent !== null && bareLayoutEdit()) {\n // A bare add under a container is an edit of its own, so it settles\n // its arrival like one — as a batch, which is what makes the\n // arrangement part of the same undo step.\n return scene.batch(`add ${spec.kind}`, () => scene.add(spec));\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n noteArrival(id, parent, null);\n executeAndLog('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n ...fnKeysOf(fnFields, { ...spec, id, kind: spec.kind } as unknown as FnBearingNode, 'opKey'),\n }, `add ${spec.kind}`);\n // A function cannot travel through the serializable op payload. Patch it\n // directly onto the live node after the op applies.\n patchNodeFunctions(spec, id, { cacheForRedo: true });\n return id;\n },\n\n remove(id) {\n scene.removeMany([id]);\n },\n\n removalClosure(rootIds) {\n return removalClosure(rootIds).ids;\n },\n\n removeMany(rootIds) {\n if (rootIds.length === 0) return;\n // Every id resolves against the pre-removal tree, so an id another one\n // cascades away is absorbed rather than being a second, failing removal.\n const { ids, removing } = removalClosure(rootIds);\n for (const nid of ids) refuseLocked(nid, 'remove');\n // requireNode is what rejects an id that is not in the scene, and it runs\n // before anything mutates.\n const snapshot: Node<TData, TLayer, TPose>[] = ids.map((nid) => {\n const n = requireNode(nid);\n return n.kind === 'container' ? { ...n, children: [...n.children] } : { ...n };\n });\n // The rest is reachable through a snapshotted parent's cloned `children`.\n const detached = snapshot\n .filter((n) => n.parent === null || !removing.has(n.parent))\n .map((n) => ({ id: n.id, parent: n.parent, index: siblingsOf(n.parent).indexOf(n.id) }))\n .sort((l, r) => l.index - r.index);\n // Ephemeral, and ids are reusable: an override left behind would\n // reattach itself to whatever is added under this id next.\n for (const nid of ids) overrides.clear(nid);\n const fnKeys = snapshot.flatMap((n) => {\n const keys = fnKeysOf(fnFields, n as unknown as FnBearingNode, 'opKey');\n return Object.keys(keys).length === 0 ? [] : [{ id: n.id, ...keys }];\n });\n const payload: RemoveSnapshot = {\n nodes: snapshot, detached,\n ...(fnKeys.length > 0 ? { fnKeys } : {}),\n };\n if (detached.some((d) => d.parent !== null) && bareLayoutEdit()) {\n scene.batch('remove', () => scene.removeMany(rootIds));\n return;\n }\n for (const d of detached) noteDeparture(d.id, d.parent, null);\n executeAndLog('kit:remove', payload, 'remove');\n },\n\n update(id, patch) {\n const node = requireNode(id);\n refuseLocked(id, 'update');\n executeAndLog('kit:setData', { id, from: node.data, to: patch.data }, 'update');\n },\n\n setPose(id, pose) {\n const node = requireNode(id);\n refuseLocked(id, 'set the pose of');\n if (node.kind === 'container' && resized(layoutFrame, id, node.pose, pose)) {\n if (bareLayoutEdit()) {\n scene.batch('setPose', () => scene.setPose(id, pose));\n return;\n }\n noteChange(id);\n }\n executeAndLog('kit:setPose', { id, from: node.pose, to: pose }, 'setPose');\n },\n\n setLayer(id, layer) {\n requireLayerIndex(layer);\n const node = requireNode(id);\n refuseLocked(id, 'relayer');\n if (node.layer !== layer) refuseLockedLayer(layer, 'move nodes onto');\n if (node.parent !== null) {\n const parentNode = requireNode(node.parent);\n assertSubtreeLayer(id, layer, node.parent, parentNode.layer, 'relayer');\n }\n if (node.layer === layer) return;\n // DFS preorder: collect id + all descendants.\n const subtree: NodeId[] = [];\n const stack: NodeId[] = [id];\n while (stack.length > 0) {\n const curId = stack.pop()!;\n const cur = state.nodes.get(curId);\n if (!cur) continue;\n subtree.push(curId);\n refuseLocked(curId, 'relayer');\n if (cur.kind === 'container') {\n for (let i = cur.children.length - 1; i >= 0; i--) {\n stack.push(cur.children[i]);\n }\n }\n }\n if (subtree.length === 1) {\n // Fast path: single node, no batch needed.\n executeAndLog('kit:setLayer', { id, from: node.layer, to: layer }, 'setLayer');\n } else {\n scene.batch('setLayer', () => {\n for (const sid of subtree) {\n const cur = requireNode(sid);\n if (cur.layer === layer) continue;\n executeAndLog('kit:setLayer', { id: sid, from: cur.layer, to: layer }, 'setLayer');\n }\n });\n }\n },\n\n setDependsOn(id, dependsOn) {\n const node = requireNode(id);\n refuseLocked(id, 'retarget');\n if (sameDependsOn(node.dependsOn, dependsOn)) return;\n executeAndLog(\n 'kit:setDependsOn',\n { id, from: node.dependsOn, to: dependsOn },\n 'setDependsOn',\n );\n },\n\n setLayout(id, layout) {\n const node = requireNode(id);\n if (node.kind !== 'container') throw new Error(`Scene: \"${id}\" is not a container`);\n refuseLocked(id, 'set the layout of');\n const field = fnField('layout');\n let to: LayoutStrategy<TPose> | null;\n if (typeof layout === 'string') {\n to = (field.fnOf(layout) as LayoutStrategy<TPose> | undefined) ?? null;\n if (to === null) throw new Error(`Scene: no layout \"${layout}\" in this scene's registry`);\n } else {\n to = layout;\n }\n const from = node.layout ?? null;\n if (from === to) return;\n if (to !== null) hasLayouts = true;\n if (bareLayoutEdit()) {\n scene.batch('setLayout', () => scene.setLayout(id, to));\n return;\n }\n noteChange(id);\n const fromKey = from === null ? undefined : field.keyOf(from);\n const toKey = to === null ? undefined : field.keyOf(to);\n const payload: SetLayoutPayload = {\n id,\n ...(fromKey !== undefined ? { fromKey } : {}),\n ...(toKey !== undefined ? { toKey } : {}),\n };\n layoutRefs.set(payload, { from, to });\n executeAndLog('kit:setLayout', payload, 'setLayout');\n },\n\n move(id, parent, index) {\n const node = requireNode(id);\n refuseLocked(id, 'move');\n if (parent !== null) {\n refuseLocked(parent, 'move nodes into');\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(id, node.layer, parent, p.layer);\n // Cycle check: parent must not be id or a descendant of id.\n if (parent === id) throw new Error('Scene: cannot parent a node to itself');\n const desc: NodeId[] = [];\n descendants(id, desc);\n if (desc.includes(parent)) {\n throw new Error('Scene: cannot parent a node to its own descendant');\n }\n }\n if ((parent !== null || node.parent !== null) && bareLayoutEdit()) {\n scene.batch('move', () => scene.move(id, parent, index));\n return;\n }\n const fromSibs = siblingsOf(node.parent);\n const fromIndex = fromSibs.indexOf(id);\n const toSibs = parent === node.parent ? fromSibs : siblingsOf(parent);\n const toIndex = index ?? toSibs.length;\n noteArrival(id, parent, node.parent);\n noteDeparture(id, node.parent, parent);\n noteChange(node.parent);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: parent, toIndex,\n }, 'move');\n },\n\n reorder(id, index) {\n const node = requireNode(id);\n refuseLocked(id, 'reorder');\n if (node.parent !== null && bareLayoutEdit()) {\n scene.batch('reorder', () => scene.reorder(id, index));\n return;\n }\n noteChange(node.parent);\n const sibs = siblingsOf(node.parent);\n const fromIndex = sibs.indexOf(id);\n executeAndLog('kit:move', {\n id, fromParent: node.parent, fromIndex, toParent: node.parent, toIndex: index,\n }, 'reorder');\n },\n\n setLayerVisible(layer, visible) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerVisible', { layer, from: state.layers[i].visible, to: visible }, 'setLayerVisible');\n },\n\n setLayerLocked(layer, locked) {\n const i = requireLayerIndex(layer);\n executeAndLog('kit:setLayerLocked', { layer, from: state.layers[i].locked, to: locked }, 'setLayerLocked');\n },\n\n setLayerParallax(layer, parallax) {\n const i = requireLayerIndex(layer);\n executeAndLog(\n 'kit:setLayerParallax',\n { layer, from: state.layers[i].parallax, to: parallax },\n 'setLayerParallax',\n );\n },\n\n isLocked: (id) => isLockedInternal(id),\n\n unlocked: (fn) => withLocksLifted(fn),\n\n addLayer(spec) {\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene: duplicate layer id \"${spec.id}\"`);\n }\n const index = spec.index ?? state.layers.length;\n const clamped = Math.max(0, Math.min(index, state.layers.length));\n const record: UserLayerRecord<TLayer> = {\n kind: 'user',\n id: spec.id,\n name: spec.name,\n visible: spec.visible ?? true,\n locked: spec.locked ?? false,\n ...(spec.parallax ? { parallax: spec.parallax } : {}),\n };\n executeAndLog('kit:addLayer', { record, index: clamped }, 'addLayer');\n },\n\n removeLayer(layer) {\n const index = requireLayerIndex(layer);\n const rec = state.layers[index];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot remove system layer \"${layer}\"`);\n }\n // A layer operation, like the lock toggle: taking a locked layer away\n // takes its nodes with it.\n withLocksLifted(() => scene.batch('removeLayer', () => {\n const tagged: NodeId[] = [];\n for (const [id, node] of state.nodes) {\n if (node.layer === layer) tagged.push(id);\n }\n scene.removeMany(tagged);\n const finalIndex = requireLayerIndex(layer);\n executeAndLog('kit:removeLayer', { record: rec, index: finalIndex }, 'removeLayer');\n }));\n },\n\n renameLayer(layer, name) {\n const rec = state.layers[requireLayerIndex(layer)];\n if (rec.kind !== 'user') {\n throw new Error(`Scene: cannot rename system layer \"${layer}\"`);\n }\n executeAndLog('kit:renameLayer', { layer, from: rec.name, to: name }, 'renameLayer');\n },\n\n moveLayer(layer, index) {\n const from = requireLayerIndex(layer);\n const to = Math.max(0, Math.min(index, state.layers.length - 1));\n if (from === to) return;\n // Build the proposed order and a temp index map, then verify the\n // child-below-parent invariant holds for every node before mutating.\n const proposed = [...state.layers];\n const [rec] = proposed.splice(from, 1);\n proposed.splice(to, 0, rec);\n const tempIndex = new Map<TLayer, number>();\n for (let i = 0; i < proposed.length; i++) tempIndex.set(proposed[i].id, i);\n for (const node of state.nodes.values()) {\n if (node.parent === null) continue;\n const parent = state.nodes.get(node.parent);\n if (!parent) continue;\n if (tempIndex.get(node.layer)! < tempIndex.get(parent.layer)!) {\n throw new Error(\n `Scene: moveLayer(\"${layer}\", ${index}) — a child may not render below its parent's layer`,\n );\n }\n }\n executeAndLog('kit:moveLayer', { layer, from, to }, 'moveLayer');\n },\n\n registerOp(kind, handler) {\n if (kind.startsWith('kit:')) {\n throw new Error(`Scene: op kind \"${kind}\" is reserved (kit:* prefix)`);\n }\n registered.set(kind, handler as RegisteredOp<unknown>);\n },\n\n recordOp(op) {\n executeAndLog(op.kind, op.payload, op.kind);\n },\n\n setActiveJournalAccessor(fn) {\n activeJournalAccessor = fn;\n },\n\n applyBatch(ops, label, adapter) {\n refuseUntracked('applyBatch');\n runArrivalEdit(ops, (all) => applyBatchNow(all, label, adapter));\n },\n\n setArrivalHandler(handler) {\n arrivalHandler = handler;\n return () => {\n if (arrivalHandler === handler) arrivalHandler = null;\n };\n },\n\n layoutOf(id) {\n return layoutOfInternal(id);\n },\n\n onReflow(listener) {\n reflowListeners.add(listener);\n return () => { reflowListeners.delete(listener); };\n },\n\n overrides,\n\n getSelection: () => selection,\n\n setSelection(ids) {\n selection = reachable([...ids]);\n notify();\n },\n\n history: sceneHistory,\n\n undo() {\n if (!history.canUndo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.undo()));\n notify();\n return true;\n },\n\n redo() {\n if (!history.canRedo()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.redo()));\n notify();\n return true;\n },\n\n canUndo: () => history.canUndo(),\n canRedo: () => history.canRedo(),\n\n /** Read-only snapshot of every history entry currently reachable from\n * the present state. Order: oldest applied first, then redoable\n * entries in the order they'd be re-applied (top of redo stack last).\n * Each entry's `id` is stable for the entry's lifetime. */\n historyEntries() {\n const { undo, redo } = history.entries();\n const out: { id: string; label: string }[] = [];\n for (const e of undo) out.push({ id: String(e.id), label: e.label });\n // entries().redo is already chronological: the next redo comes first.\n for (const e of redo) out.push({ id: String(e.id), label: e.label });\n return out;\n },\n\n /** Index of the \"current state\". `0` = nothing applied (initial);\n * equals the number of applied (undoable) entries —\n * `historyEntries().length` when fully redone. */\n historyIndex: () => history.undoDepth(),\n\n /** Walk to a target history index by calling undo/redo repeatedly.\n * Caps at the valid range; returns true if the index changed. */\n jumpToHistoryIndex(targetIndex: number) {\n const total = history.undoDepth() + history.redoDepth();\n const target = Math.max(0, Math.min(total, targetIndex));\n if (target === history.undoDepth()) return false;\n withLocksLifted(() => withRecordingSuppressed(() => history.goto(target)));\n notify();\n return true;\n },\n\n serializeHistory: () => history.serialize(),\n\n restoreHistory(snapshot: SerializedHistory) {\n // restore() only rebuilds the stacks — no op applies, no node-state\n // mutation. The caller guarantees state already matches the head.\n history.restore(snapshot);\n notify();\n },\n\n setHistoryAdapter(fn) {\n historyAdapterAccessor = fn;\n },\n\n batch(label, fn) {\n // Captured at open, not at recordEntry: by the time the batch closes\n // the selection has already moved to wherever the batch put it.\n const outermost = batchDepth === 0;\n if (outermost) currentBatch = { label, ops: [], selectionBefore: selection };\n const ownsArrivals = outermost && openArrivals(true);\n batchDepth++;\n try {\n if (!outermost) return fn();\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => (currentBatch?.ops.length ?? 0) > 0);\n if (ownsArrivals) emitReflow();\n return result;\n } catch (err) {\n // Reverted already; the half-built entry must not reach history.\n currentBatch = null;\n throw err;\n }\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n if (batchDepth === 0) {\n if (currentBatch) {\n const finished = currentBatch;\n currentBatch = null;\n // Ops were applied live as they were issued (state stays\n // readable mid-batch); recordEntry pushes without re-applying.\n if (finished.ops.length > 0) {\n history.recordEntry(finished.ops, finished.label, { selectionBefore: finished.selectionBefore });\n }\n }\n // Fire one coalesced notify if any op inside the batch dirtied\n // state. Nested batches contribute to the same flush — only the\n // outermost emits.\n if (batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n }\n },\n\n untracked(fn) {\n const prevSuppress = suppressRecording;\n const versionBefore = version;\n suppressRecording = true;\n untrackedDepth++;\n const ownsArrivals = openArrivals(true);\n batchDepth++;\n try {\n const result = atomically(() => {\n const r = fn();\n if (ownsArrivals) for (const p of settleArrivals()) scene.setPose(asNodeId(p.id), p.to as TPose);\n return r;\n }, () => false);\n if (ownsArrivals) emitReflow();\n return result;\n } finally {\n batchDepth--;\n if (ownsArrivals) {\n arrivals = null;\n reflowDue = null;\n }\n untrackedDepth--;\n suppressRecording = prevSuppress;\n if (version !== versionBefore) history.seal();\n if (batchDepth === 0 && batchDirty) {\n batchDirty = false;\n for (const listener of listeners) listener();\n }\n }\n },\n\n toJSON(): SerializedScene<TData, TLayer, TPose> {\n const nodes: SerializedNode<TData, TLayer, TPose>[] = [];\n for (const n of renderOrderNodesInternal()) {\n const id = n.id;\n const out: SerializedNode<TData, TLayer, TPose> = {\n id,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent != null) out.parent = n.parent;\n if (n.dependsOn === 'children') out.dependsOn = 'children';\n else if (n.dependsOn && n.dependsOn.length > 0) out.dependsOn = n.dependsOn;\n if (n.pickable === false) out.pickable = false;\n Object.assign(\n out,\n fnKeysOf(fnFields, n as unknown as FnBearingNode, 'jsonKey', (field) => {\n throw new Error(\n `Scene.toJSON: node '${id}' has ${field.spec.field} but no matching registry key. ` +\n `The function must be registered via createScene's registry option to round-trip.`\n );\n }),\n );\n nodes.push(out);\n }\n const systemLayers = state.layers.map((l) => {\n const layer: SerializedLayer<TLayer> = { id: l.id };\n if (l.visible === false) layer.visible = false;\n if (l.locked === true) layer.locked = true;\n if (l.parallax) layer.parallax = l.parallax;\n if (l.kind === 'user') {\n layer.kind = 'user';\n layer.name = l.name;\n }\n return layer;\n });\n return { version: 1, systemLayers, nodes };\n },\n\n loadState(json) {\n // Validate + map up front (throws before we touch live state on a bad\n // version or unknown registry key).\n const specs = specsFromSerialized(json, registry);\n // Reset node + layer state.\n dependents.clear();\n state.nodes.clear();\n state.roots.length = 0;\n state.layers.length = 0;\n state.layerIndex.clear();\n invalidateOrder();\n for (let i = 0; i < json.systemLayers.length; i++) {\n const spec = json.systemLayers[i];\n if (state.layerIndex.has(spec.id)) {\n throw new Error(`Scene.loadState: duplicate system layer id \"${spec.id}\"`);\n }\n state.layers.push(layerFromSerialized(spec));\n state.layerIndex.set(spec.id, i);\n }\n // Clear history + the transient batch and function-field caches.\n history.clear();\n for (const field of fnFields) field.pending.clear();\n currentBatch = null;\n batchDepth = 0;\n batchDirty = false;\n // Rebuild nodes (bypass the log, exactly like construction).\n applyConstructionSpecs(specs);\n notify();\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n getVersion: () => version,\n };\n\n /** Insert nodes without writing to the undo log — used by construction\n * (`options.initial`) and by `loadState`. Specs must list parents before\n * children (the order `toJSON()` emits). Throws on id collision, unknown\n * layer, non-container parent, or cross-layer subtree. */\n function applyConstructionSpecs(specs: readonly AddNodeSpec<TData, TLayer, TPose>[]): void {\n for (const spec of specs) {\n // Bypass the log: we want construction to start with empty history.\n const id = spec.id ?? generateId();\n if (state.nodes.has(id)) {\n throw new Error(`Scene: id collision on \"${id}\"`);\n }\n requireLayerIndex(spec.layer);\n const parent = spec.parent ?? null;\n if (parent !== null) {\n const p = requireNode(parent);\n if (p.kind !== 'container') {\n throw new Error(`Scene: parent \"${parent}\" is not a container`);\n }\n assertSubtreeLayer(spec.id, spec.layer, parent, p.layer);\n }\n const sibs = siblingsOf(parent);\n const index = spec.index ?? sibs.length;\n runOp('kit:add', {\n id, kind: spec.kind, layer: spec.layer, pose: spec.pose, data: spec.data,\n parent, index,\n ...(spec.dependsOn !== undefined ? { dependsOn: spec.dependsOn } : {}),\n ...(spec.pickable !== undefined ? { pickable: spec.pickable } : {}),\n });\n // No `kit:add` reaches history here, so nothing ever replays these and\n // `pruneCacheForDroppedOps` — which only scans `kit:add` — could never\n // drop the entries. A restore after `remove` comes from `kit:remove`'s\n // revert, which clones the whole node and carries every field along.\n patchNodeFunctions(spec, id, { cacheForRedo: false });\n }\n }\n\n // Apply initial nodes (not undoable — they're part of the construction).\n if (options.initial) {\n applyConstructionSpecs(options.initial);\n notify();\n }\n\n // ── Internal / test-only access ───────────────────────────────────────\n // Attach private state accessors directly on the returned object, hidden\n // behind `as unknown` because Scene<> is the public interface.\n // __clipCacheSize / __derivePathCacheSize: used only by test files to assert\n // prune behaviour.\n (scene as unknown as { __clipCacheSize: () => number }).__clipCacheSize =\n () => fnField('clipFromPose').pending.size;\n (scene as unknown as { __derivePathCacheSize: () => number }).__derivePathCacheSize =\n () => fnField('derivePath').pending.size;\n (scene as unknown as { __derivePoseCacheSize: () => number }).__derivePoseCacheSize =\n () => fnField('derivePose').pending.size;\n\n return scene;\n}\n\n/** Map a `SerializedScene` to construction specs. Shared by `sceneFromJSON`\n * (new instance) and `Scene.loadState` (in-place). Validates version and\n * resolves every `NODE_FN_FIELDS` key → function via the registry;\n * throws on an unsupported version or an unknown registry key. */\nfunction specsFromSerialized<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n registry: SceneRegistry<TPose>,\n): AddNodeSpec<TData, TLayer, TPose>[] {\n if (json.version !== 1) {\n throw new Error(`Scene: unsupported version ${json.version}; only v1 supported`);\n }\n return json.nodes.map((n) => {\n const spec: AddNodeSpec<TData, TLayer, TPose> = {\n id: n.id as NodeId,\n kind: n.kind,\n layer: n.layer,\n pose: n.pose,\n data: n.data,\n };\n if (n.parent !== undefined) spec.parent = n.parent as NodeId;\n if (n.pickable !== undefined) spec.pickable = n.pickable;\n if (n.dependsOn !== undefined) {\n spec.dependsOn = n.dependsOn === 'children'\n ? 'children'\n : (n.dependsOn as readonly NodeId[]);\n }\n const serialized = n as unknown as Record<string, string | undefined>;\n for (const field of NODE_FN_FIELDS) {\n const key = serialized[field.jsonKey];\n if (key === undefined) continue;\n const fn = (registry[field.field] as Record<string, unknown> | undefined)?.[key];\n if (!fn) {\n throw new Error(\n `Scene: unknown ${field.field} key '${key}'. ` +\n `Register a function with this key in the registry option.`,\n );\n }\n (spec as unknown as Record<string, unknown>)[field.field] = fn;\n }\n return spec;\n });\n}\n\n/** The scene's selection in the shape `createHistory` wants, for a consumer\n * building a second History over the same scene (a modality machine, a\n * journal owner) that should restore selection the way the scene's own\n * history does. */\nexport function sceneSelectionStore(scene: {\n getSelection(): readonly NodeId[];\n setSelection(ids: readonly NodeId[]): void;\n}): HistorySelection {\n return {\n get: () => scene.getSelection(),\n set: (ids) => scene.setSelection(ids as readonly NodeId[]),\n };\n}\n\n/** Reconstruct a Scene from a JSON snapshot produced by `scene.toJSON()`.\n * Function fields (e.g., `clipFromPose`) are resolved by string key via the\n * registry passed in `options`. Throws on unknown version, unknown registry\n * keys, or invalid scene shape (cross-layer subtrees, unknown layer ids).\n * Loaded scenes start with empty history — undo/redo is NOT serialized. */\nexport function sceneFromJSON<TData, TLayer extends string, TPose>(\n json: SerializedScene<TData, TLayer, TPose>,\n options: {\n registry?: SceneRegistry<TPose>;\n historyLimit?: number;\n coalesceWindowMs?: number;\n generateId?: () => NodeId;\n ops?: Readonly<Record<string, RegisteredOp<unknown>>>;\n layoutFrame?: UseSceneOptions<TData, TLayer, TPose>['layoutFrame'];\n } = {},\n): Scene<TData, TLayer, TPose> {\n const registry = options.registry ?? {};\n // Built empty and then loaded, so the snapshot's layer stack is rebuilt by\n // the one reader that knows how — `createScene` mints system layers only.\n const scene = createScene<TData, TLayer, TPose>({\n systemLayers: json.systemLayers.map((l) => ({ id: l.id })),\n registry,\n ...(options.historyLimit !== undefined ? { historyLimit: options.historyLimit } : {}),\n ...(options.coalesceWindowMs !== undefined ? { coalesceWindowMs: options.coalesceWindowMs } : {}),\n ...(options.generateId !== undefined ? { generateId: options.generateId } : {}),\n ...(options.ops !== undefined ? { ops: options.ops } : {}),\n ...(options.layoutFrame !== undefined ? { layoutFrame: options.layoutFrame } : {}),\n });\n scene.loadState(json);\n return scene;\n}\n"],"mappings":";;;;;;;;;;;;;AAiDA,IAAIC,IAAmB,GACjBC,WAC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