@weasel-js/core 1.4.3 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +1299 -2197
  2. package/README.md +118 -75
  3. package/dist/{pointSnapToGrid-D1bRdq-j.d.ts → autoPoseDescriptor-CvjflWJK.d.ts} +35 -17
  4. package/dist/{chunk-ORZNKVXM.js → chunk-BDWAA634.js} +4 -22
  5. package/dist/chunk-BDWAA634.js.map +1 -0
  6. package/dist/{chunk-WYPSGIYS.js → chunk-MG7OXCAI.js} +4149 -5316
  7. package/dist/chunk-MG7OXCAI.js.map +1 -0
  8. package/dist/{chunk-BLJNRMKB.js → chunk-MQI4PIX3.js} +3 -3
  9. package/dist/chunk-MQI4PIX3.js.map +1 -0
  10. package/dist/{chunk-SBFC6J3C.js → chunk-UCPV7JXC.js} +201 -256
  11. package/dist/chunk-UCPV7JXC.js.map +1 -0
  12. package/dist/clipboard.d.ts +2 -3
  13. package/dist/clone.d.ts +3 -2
  14. package/dist/depSchema-nMqj_qTM.d.ts +3490 -0
  15. package/dist/{grid-Bw8cSde-.d.ts → grid-BrIa38gG.d.ts} +7 -23
  16. package/dist/index.d.ts +2134 -1210
  17. package/dist/index.js +4 -5
  18. package/dist/insert.d.ts +4 -4
  19. package/dist/insert.js +1 -1
  20. package/dist/move.d.ts +5 -6
  21. package/dist/move.js +3 -6
  22. package/dist/move.js.map +1 -1
  23. package/dist/{options-DYfUlZxk.d.ts → options-BDyCnrp8.d.ts} +3 -2
  24. package/dist/poseDescriptor-CGOgIgf8.d.ts +134 -0
  25. package/dist/renderer.d.ts +10 -4
  26. package/dist/renderer.js +4 -5
  27. package/dist/resize.d.ts +10 -11
  28. package/dist/resize.js +2 -2
  29. package/dist/routing.d.ts +1 -142
  30. package/dist/routing.js +1 -1
  31. package/dist/routing.js.map +1 -1
  32. package/dist/{types-BJqsTlXl.d.ts → types-DMyo7dnM.d.ts} +12 -41
  33. package/dist/{types-CoVTbo_y.d.ts → types-DtjCJA5r.d.ts} +10 -9
  34. package/package.json +13 -10
  35. package/dist/DrawCommand-CD-ug3d9.d.ts +0 -332
  36. package/dist/builtins-CtGORLCG.d.ts +0 -740
  37. package/dist/chunk-BLJNRMKB.js.map +0 -1
  38. package/dist/chunk-LEURURX3.js +0 -561
  39. package/dist/chunk-LEURURX3.js.map +0 -1
  40. package/dist/chunk-ORZNKVXM.js.map +0 -1
  41. package/dist/chunk-SBFC6J3C.js.map +0 -1
  42. package/dist/chunk-WYPSGIYS.js.map +0 -1
  43. package/dist/geometry-CHR36Ub_.d.ts +0 -114
  44. package/dist/path-JEV2c5If.d.ts +0 -48
  45. package/dist/registry-DnoTWGED.d.ts +0 -4003
  46. package/dist/types-BHK2dkMu.d.ts +0 -172
  47. package/dist/types-H7o6MaPo.d.ts +0 -512
  48. package/dist/view-DSQgxBJB.d.ts +0 -63
@@ -1,172 +0,0 @@
1
- /** One bit per debug feature; absent keys are off. */
2
- interface DebugConfig {
3
- hitboxes?: boolean;
4
- handles?: boolean;
5
- bounds?: boolean;
6
- origins?: boolean;
7
- snap?: boolean;
8
- layers?: boolean;
9
- /** Render each tracked node's id as a label at the top-left of its
10
- * bounds. Pulls from the same `recordBounds` stream `bounds` uses, so
11
- * no extra sink calls are required to enable. */
12
- ids?: boolean;
13
- /** Rolling FPS counter rendered in the top-left corner of the canvas.
14
- * Tracks the rate at which the debug overlay's draw callback runs;
15
- * this matches the canvas's effective repaint rate. */
16
- fps?: boolean;
17
- /** Optional per-feature color overrides; falls back to the default theme. */
18
- theme?: Partial<DebugTheme>;
19
- /** Optional per-feature line-width / dash overrides; falls back to
20
- * {@link DEFAULT_DEBUG_STROKES}. */
21
- strokes?: Partial<DebugStrokes>;
22
- }
23
- /** The name of one debug-overlay feature — the keys of {@link DebugConfig}
24
- * that toggle a visualization. */
25
- type DebugFeature = 'hitboxes' | 'handles' | 'bounds' | 'origins' | 'snap' | 'layers' | 'ids' | 'fps';
26
- /** Colors the debug overlay draws with, one entry per feature. */
27
- interface DebugTheme {
28
- hitboxFill: string;
29
- hitboxStroke: string;
30
- handle: string;
31
- bounds: string;
32
- origin: string;
33
- snap: string;
34
- layerText: string;
35
- layerTextBg: string;
36
- /** Color for the per-node id label rendered when `config.ids` is on. */
37
- idText: string;
38
- /** Foreground / background for the FPS panel. */
39
- fpsText: string;
40
- fpsTextBg: string;
41
- }
42
- /** Line width and dash pattern for one stroked debug feature. An empty (or
43
- * omitted) `dash` is a solid line. */
44
- interface DebugStroke {
45
- width: number;
46
- dash?: readonly number[];
47
- }
48
- /** The stroked half of the debug overlay's appearance, split from
49
- * {@link DebugTheme} because only some features draw a line at all — text
50
- * panels and filled origin dots take color and nothing else. */
51
- interface DebugStrokes {
52
- hitbox: DebugStroke;
53
- bounds: DebugStroke;
54
- handle: DebugStroke;
55
- /** Rejected snap candidates only; accepted ones paint as a filled dot. */
56
- snap: DebugStroke;
57
- }
58
- /** Which kind of handle a recorded handle marker represents. */
59
- type HandleKind = 'corner' | 'rotation' | 'anchor';
60
- /** The geometry a hit region actually tests against, as reported to the debug
61
- * sink so the overlay can draw the real shape rather than its bounding box. */
62
- type HitShape = {
63
- kind: 'rect';
64
- x: number;
65
- y: number;
66
- width: number;
67
- height: number;
68
- rotation?: number;
69
- } | {
70
- kind: 'circle';
71
- cx: number;
72
- cy: number;
73
- r: number;
74
- } | {
75
- kind: 'path';
76
- d: Path2D;
77
- };
78
- /** A hit region tested during the current frame. */
79
- interface RecordedHitbox {
80
- id: string;
81
- kind: 'body' | 'handle' | 'rotation' | 'anchor';
82
- shape: HitShape;
83
- }
84
- /** A handle drawn during the current frame, and where. */
85
- interface RecordedHandle {
86
- id: string;
87
- position: {
88
- x: number;
89
- y: number;
90
- };
91
- kind: HandleKind;
92
- }
93
- /** A node's bounds as computed during the current frame. */
94
- interface RecordedBounds {
95
- id: string;
96
- bounds: {
97
- x: number;
98
- y: number;
99
- width: number;
100
- height: number;
101
- };
102
- }
103
- /** A node's transform origin as used during the current frame. */
104
- interface RecordedOrigin {
105
- id: string;
106
- point: {
107
- x: number;
108
- y: number;
109
- };
110
- }
111
- /** A snap candidate considered during the current gesture, and whether it
112
- * won. Unlike the other records these survive across frames, until the
113
- * gesture ends. */
114
- interface RecordedSnap {
115
- point: {
116
- x: number;
117
- y: number;
118
- };
119
- accepted: boolean;
120
- }
121
- /** A render layer that drew during the current frame. */
122
- interface RecordedLayer {
123
- id: string;
124
- label: string;
125
- space: 'world' | 'screen';
126
- index: number;
127
- }
128
- /** Everything the sink collected, ready for the overlay to draw. */
129
- interface DebugSnapshot {
130
- hitboxes: RecordedHitbox[];
131
- handles: RecordedHandle[];
132
- bounds: RecordedBounds[];
133
- origins: RecordedOrigin[];
134
- snap: RecordedSnap[];
135
- layers: RecordedLayer[];
136
- }
137
- /**
138
- * Where the kit reports what it is doing so the debug overlay can draw it.
139
- *
140
- * Recording is push-based and cheap: hit-testers, handle painters and snap
141
- * strategies call these as they run, whether or not any overlay is watching.
142
- * Nothing here affects behavior — a sink that discards everything is a valid
143
- * sink.
144
- */
145
- interface DebugSink {
146
- recordHitbox(id: string, kind: 'body' | 'handle' | 'rotation' | 'anchor', shape: HitShape): void;
147
- recordHandle(id: string, position: {
148
- x: number;
149
- y: number;
150
- }, kind: HandleKind): void;
151
- recordBounds(id: string, bounds: {
152
- x: number;
153
- y: number;
154
- width: number;
155
- height: number;
156
- }): void;
157
- recordOrigin(id: string, point: {
158
- x: number;
159
- y: number;
160
- }): void;
161
- recordSnapCandidate(point: {
162
- x: number;
163
- y: number;
164
- }, accepted: boolean): void;
165
- recordLayer(id: string, label: string, space: 'world' | 'screen', index: number): void;
166
- /** Clears every non-snap array. Called at the start of each Canvas render. */
167
- beginFrame(): void;
168
- /** Clears the snap array. Called at gesture end. */
169
- clearSnap(): void;
170
- }
171
-
172
- export type { DebugSink as D, HandleKind as H, RecordedBounds as R, DebugConfig as a, DebugSnapshot as b, DebugStrokes as c, DebugTheme as d, DebugFeature as e, DebugStroke as f, HitShape as g, RecordedHandle as h, RecordedHitbox as i, RecordedLayer as j, RecordedOrigin as k, RecordedSnap as l };
@@ -1,512 +0,0 @@
1
- import * as _weasel_js_history from '@weasel-js/history';
2
- import { Op, SerializedHistory } from '@weasel-js/history';
3
- import { P as Path } from './path-JEV2c5If.js';
4
-
5
- /**
6
- * Axis-aligned rectangle pose with optional rotation. The canonical pose
7
- * shape used by `composeRectPose` and the `unionBounds` helper. Rotation is
8
- * in radians, pivoted on the unrotated AABB center; absent === 0. Kit-side
9
- * code that consumes rotation already reads `pose.rotation ?? 0`
10
- * (`wrapNodeOutput`, `rotate/handle.ts`, `pathInWorld.ts`), so
11
- * the slot exists on every default scene whether or not the consumer
12
- * populates it.
13
- */
14
- interface RectPose {
15
- x: number;
16
- y: number;
17
- width: number;
18
- height: number;
19
- /** Rotation in radians around the unrotated AABB center. Absent === 0. */
20
- rotation?: number;
21
- }
22
- /**
23
- * # SceneNode — the thing in the scene
24
- *
25
- * A `SceneNode` is the single canonical unit of a weasel scene. Everything
26
- * the user sees on the canvas — a shape, a group, an annotation, a tile —
27
- * is one of these. Containers and leaves are both nodes; the kit has no
28
- * other concept of "scene element."
29
- *
30
- * ## Three orthogonal slots
31
- *
32
- * Every node carries three independent slots, plus its tree position:
33
- *
34
- * - **`data: TData`** — app-defined payload. The kit never inspects it.
35
- * Color, label, kind, glyph, sample-rate, whatever the app's domain
36
- * calls for. Mutated via `Scene.update(id, { data })`.
37
- *
38
- * - **`pose: TPose`** — local transform, relative to the node's direct
39
- * parent (or world, for root nodes). Default `RectPose` is
40
- * `{ x, y, width, height }`, but `TPose` is fully generic so apps can
41
- * use rotated rects, paths, ellipses, etc. The kit composes world
42
- * poses via `composeWorldPose` when rendering / hit-testing / snapping.
43
- *
44
- * - **`layer: TLayer`** — a string tag associating the node with a
45
- * visual `RenderLayer` at draw time. Separate from `LayerRecord` (the
46
- * per-layer visible/locked metadata held by the `Scene`).
47
- *
48
- * Tree position lives on the node itself: every node has a `parent` (or
49
- * `null` for roots), and `ContainerNode` adds an ordered `children: NodeId[]`.
50
- *
51
- * ## Identity is by `NodeId`, not by reference
52
- *
53
- * Nodes are addressed by `NodeId` everywhere outside the scene tree:
54
- * selection is `NodeId[]`, ops reference `NodeId`s, adapter methods accept
55
- * `string` ids and look up the node on demand. The `Node` object itself is
56
- * a snapshot of current state — don't hold references to it across scene
57
- * updates; look up by id when you need the latest.
58
- *
59
- * Picking helpers (`pickBest`, `pickEvery`) likewise return ids, not nodes —
60
- * they're hit-testing primitives that stay ignorant of node payload shape.
61
- *
62
- * ## Vocabulary
63
- *
64
- * The kit-internal name is `Node`; the public re-export is `SceneNode`
65
- * (avoids collision with DOM `Node` at call sites). Adapter methods speak
66
- * the same vocabulary: `getNode`, `getNodes`, `insertNode`, `removeNode`,
67
- * `cloneNode`, `addNode`. Older code, demos, and comments may still say
68
- * "object" or "item" — those are historical aliases for the same concept.
69
- */
70
- /** Opaque branded id. Treat as opaque outside the kit. */
71
- type NodeId = string & {
72
- readonly __brand: 'NodeId';
73
- };
74
- /** Brand a string as a NodeId. */
75
- declare const asNodeId: (s: string) => NodeId;
76
- interface NodeBase<TData, TLayer extends string, TPose> {
77
- id: NodeId;
78
- layer: TLayer;
79
- pose: TPose;
80
- data: TData;
81
- parent: NodeId | null;
82
- /** Nodes whose poses this node's geometry is computed from. Fixed at add
83
- * time. Absent or empty means the node's geometry is authored, which is the
84
- * normal case. */
85
- dependsOn?: readonly NodeId[];
86
- /** Computes this node's path from its dependencies' poses, in `dependsOn`
87
- * order. A dependency that has been removed arrives as `undefined`.
88
- * Returning `null` means "nothing to draw right now". Re-evaluated when a
89
- * dependency's world pose changes, never authored. Absolute-pose `Scene`
90
- * makes that the dependency's own pose, and an ancestor's move reaches it as
91
- * a `setPose` of its own from the container cascade.
92
- * `node` is deliberately widened: naming `TData`/`TLayer` here puts them in
93
- * a contravariant position, making `Scene` invariant in both and breaking
94
- * assignment kit-wide. The cost is that a `derivePath` casts to read `node.data`. */
95
- derivePath?: (node: Node<unknown, string, TPose>, deps: readonly (TPose | undefined)[]) => Path | null;
96
- }
97
- /** A node with no children — a shape, a label, an image. */
98
- interface LeafNode<TData, TLayer extends string, TPose = RectPose> extends NodeBase<TData, TLayer, TPose> {
99
- kind: 'leaf';
100
- }
101
- /** A node with an ordered list of children. This is the real group: what
102
- * Cmd+G creates, what SVG `<g>` round-trips to. A container has its own pose,
103
- * which its children's poses are relative to, and may optionally clip them. */
104
- interface ContainerNode<TData, TLayer extends string, TPose = RectPose> extends NodeBase<TData, TLayer, TPose> {
105
- kind: 'container';
106
- children: NodeId[];
107
- /** Optional clip-path source. Re-evaluated each render. Returning `null`
108
- * means "no clip for this container right now"; an empty / zero-area path
109
- * means "clip everything out" (children render nowhere). When set, the
110
- * renderer rasterizes the returned path into the stencil buffer and
111
- * paints descendants only where it covers. */
112
- clipFromPose?: (pose: TPose) => Path | null;
113
- }
114
- /** A node in the scene tree: either a leaf or a container. Re-exported
115
- * publicly as `SceneNode`, to avoid colliding with the DOM's `Node`. */
116
- type Node<TData, TLayer extends string, TPose = RectPose> = LeafNode<TData, TLayer, TPose> | ContainerNode<TData, TLayer, TPose>;
117
- interface LayerRecordBase<TLayer extends string> {
118
- id: TLayer;
119
- visible: boolean;
120
- locked: boolean;
121
- }
122
- /** A layer declared when the scene was created. Fixed set, no display name —
123
- * these are the kit's own render bands, not something a user manages. */
124
- interface SystemLayerRecord<TLayer extends string> extends LayerRecordBase<TLayer> {
125
- kind: 'system';
126
- }
127
- /** A layer the user created and can rename, reorder or delete. */
128
- interface UserLayerRecord<TLayer extends string> extends LayerRecordBase<TLayer> {
129
- kind: 'user';
130
- name: string;
131
- }
132
- /** Per-layer metadata held by the scene: whether it is visible and locked,
133
- * and where it sits in the render stack. Distinct from a node's `layer` tag,
134
- * which merely names one of these. */
135
- type LayerRecord<TLayer extends string> = SystemLayerRecord<TLayer> | UserLayerRecord<TLayer>;
136
- /** What `Scene.add` needs to mint a node. Everything except the id is
137
- * required; the id is generated unless one is supplied. */
138
- interface AddNodeSpec<TData, TLayer extends string, TPose = RectPose> {
139
- kind: 'leaf' | 'container';
140
- layer: TLayer;
141
- pose: TPose;
142
- data: TData;
143
- parent?: NodeId | null;
144
- index?: number;
145
- /** Explicit id wins over the Scene's `generateId` and the kit default. */
146
- id?: NodeId;
147
- /** Only meaningful when `kind === 'container'`. Attach a clip-path function
148
- * to the node; ignored for leaves. Mirrors `ContainerNode.clipFromPose`. */
149
- clipFromPose?: (pose: TPose) => Path | null;
150
- /** Mirrors `SceneNode.dependsOn`. */
151
- dependsOn?: readonly NodeId[];
152
- /** Mirrors `SceneNode.derivePath`. Taken as a live function; its registry key is
153
- * looked up from it, never passed in. */
154
- derivePath?: (node: Node<unknown, string, TPose>, deps: readonly (TPose | undefined)[]) => Path | null;
155
- }
156
- /** A custom scene mutation registered with `Scene.registerOp`: how to apply
157
- * it and how to undo it. The pair is what makes it participate in history. */
158
- interface RegisteredOp<P> {
159
- apply: (payload: P) => void;
160
- revert: (payload: P) => void;
161
- }
162
- /** One of the layers a scene is created with. */
163
- interface SystemLayerSpec<TLayer extends string> {
164
- id: TLayer;
165
- visible?: boolean;
166
- locked?: boolean;
167
- }
168
- /** Argument to `Scene.addLayer`. Always produces a `UserLayerRecord`
169
- * (`kind: 'user'`). */
170
- interface AddLayerSpec<TLayer extends string> {
171
- id: TLayer;
172
- name: string;
173
- /** Default `true`. */
174
- visible?: boolean;
175
- /** Default `false`. */
176
- locked?: boolean;
177
- /** Render-stack position. Default: top of stack (highest render index). */
178
- index?: number;
179
- }
180
- /** One layer as it appears in a snapshot. A snapshot written before layer
181
- * kind was serialized carries neither field, and loads as a system layer —
182
- * which is what every layer in such a snapshot was. */
183
- interface SerializedLayer<TLayer extends string> extends SystemLayerSpec<TLayer> {
184
- kind?: 'system' | 'user';
185
- /** Present on a user layer, absent on a system one. */
186
- name?: string;
187
- }
188
- /** JSON-serializable shape of a Scene's current state. Produced by
189
- * `scene.toJSON()`; consumed by `sceneFromJSON()`. Function fields
190
- * (e.g., `clipFromPose`) appear as string keys (`clipFromPoseKey`) and
191
- * are resolved through `SceneRegistry` at load time. */
192
- interface SerializedScene<TData, TLayer extends string, TPose> {
193
- version: 1;
194
- /** The whole layer stack, system and user alike — the name predates user
195
- * layers and is kept so existing snapshots still parse. */
196
- systemLayers: readonly SerializedLayer<TLayer>[];
197
- nodes: readonly SerializedNode<TData, TLayer, TPose>[];
198
- }
199
- /** JSON-serializable shape of a single node. Mirrors `AddNodeSpec` but
200
- * with function fields replaced by registry keys. */
201
- interface SerializedNode<TData, TLayer extends string, TPose> {
202
- id: string;
203
- kind: 'leaf' | 'container';
204
- layer: TLayer;
205
- pose: TPose;
206
- data: TData;
207
- /** Parent id; omitted for roots. */
208
- parent?: string;
209
- /** Registry key for the container's clip-path factory.
210
- * Containers only; omitted when the container has no clip. */
211
- clipFromPoseKey?: string;
212
- /** Ids this node's geometry derives from. Omitted when it derives from nothing. */
213
- dependsOn?: readonly string[];
214
- /** Registry key for the node's `derivePath` function. Omitted when it has none. */
215
- derivePathKey?: string;
216
- }
217
- /** Per-scene registry mapping string keys to live function references.
218
- * Passed to `createScene({ ..., registry })` and `sceneFromJSON(json, { registry })`.
219
- * Each function-field type has its own keyed map. */
220
- interface SceneRegistry<TPose> {
221
- /** Maps registry keys to `clipFromPose` factory functions for container nodes. */
222
- clipFromPose?: Readonly<Record<string, (pose: TPose) => Path | null>>;
223
- /** Maps registry keys to `derivePath` functions for nodes with `dependsOn`. */
224
- derivePath?: Readonly<Record<string, (node: Node<unknown, string, TPose>, deps: readonly (TPose | undefined)[]) => Path | null>>;
225
- }
226
- /** Options for `useScene` — the layers the scene has, what it starts out
227
- * holding, and how its history behaves. */
228
- interface UseSceneOptions<TData, TLayer extends string, TPose = RectPose> {
229
- systemLayers: readonly SystemLayerSpec<TLayer>[];
230
- initial?: readonly AddNodeSpec<TData, TLayer, TPose>[];
231
- ops?: Readonly<Record<string, RegisteredOp<unknown>>>;
232
- historyLimit?: number;
233
- /** Window (ms) within which consecutive same-shaped mutations merge into
234
- * the previous undo entry (matching per-op coalesce keys — e.g. repeated
235
- * `setPose` on the same node, or repeated `applyBatch` calls whose ops
236
- * carry matching `coalesceKey` multisets). `0` (default) disables
237
- * coalescing: every mutation is a discrete undo entry. Undo of a
238
- * coalesced entry returns to the state before the first merged mutation;
239
- * redo restores the latest. `scene.batch` entries never coalesce. */
240
- coalesceWindowMs?: number;
241
- generateId?: () => NodeId;
242
- /** Per-scene registry for non-serializable function fields (clipFromPose, etc.).
243
- * Required only when serializing/deserializing scenes that use function fields. */
244
- registry?: SceneRegistry<TPose>;
245
- /** When supplied, `scene.applyOps(ops, label)` consults this on every call.
246
- * If it returns a non-null `Journal`, ops are routed to the journal's
247
- * `applyBatch` instead of recording a new parent-history entry. The journal
248
- * drives adapter mutation internally (via `op.apply(adapter)`), so the
249
- * scene state changes as normal; only the history tracking differs.
250
- *
251
- * The accessor is called on every `applyOps` invocation so the caller can
252
- * swap the active journal in and out by updating the closure's reference
253
- * (e.g., an app's mode machine holds `let activeJournal: Journal | null`
254
- * and the accessor reads that variable).
255
- *
256
- * When the accessor isn't known at scene-construction time (typical for
257
- * mode machines that depend on `scene.history`), pass nothing here and
258
- * wire it after construction via `scene.setActiveJournalAccessor(fn)`. */
259
- getActiveJournal?: () => _weasel_js_history.Journal | null;
260
- /** Re-render the host on every scene mutation. Default `true`. Set `false`
261
- * when the scene is read by a frame loop rather than by a render — a game
262
- * loop, a simulation — and nothing in the host's DOM derives from it.
263
- * Read by `useScene`; `createScene` ignores it. */
264
- subscribe?: boolean;
265
- }
266
- /**
267
- * One node's ephemeral presentation override — what a frame loop wants to say
268
- * about a node without saying it about the document.
269
- *
270
- * Not document content: never recorded in history, never in `toJSON`, and
271
- * writing one does not bump `Scene.getVersion()`. Hoist one entry per node and
272
- * mutate it in place on a frame loop; `PoseOverrides.commit()` is what makes a
273
- * mutation visible.
274
- */
275
- interface PoseOverride<TPose> {
276
- /** Replaces the node's document pose everywhere the render and hit-test
277
- * paths read one, including the clip a container derives from its pose.
278
- * Resolved by `effectivePose` — reading `node.pose` directly is how those
279
- * paths came to disagree about where a node is. */
280
- pose?: TPose;
281
- /** Multiplied into the node's painted alpha, on top of any `alphaFor`. */
282
- alpha?: number;
283
- }
284
- /**
285
- * The scene's ephemeral per-node overrides — see {@link PoseOverride}.
286
- *
287
- * The intended shape of a frame is: `set` each node once, mutate the entries
288
- * in place per frame, `commit()` once. `commit` is not optional bookkeeping —
289
- * the painter memo keys on pose *reference*, so a mutation without a commit
290
- * paints the previous frame with no error.
291
- *
292
- * To promote a frame to document state (dropping a drag, baking an animation),
293
- * write it once through `Scene.setPose` and `clear` the override.
294
- */
295
- interface PoseOverrides<TPose> {
296
- /** Store `entry` for `id` **by reference**; the caller keeps mutating it. */
297
- set(id: NodeId, entry: PoseOverride<TPose>): void;
298
- get(id: NodeId): PoseOverride<TPose> | undefined;
299
- has(id: NodeId): boolean;
300
- /** The overridden ids, as a snapshot array. */
301
- ids(): readonly NodeId[];
302
- clear(id: NodeId): void;
303
- clearAll(): void;
304
- /** Publish this frame's in-place mutations: invalidate the painter memo for
305
- * every overridden node, then notify subscribers. */
306
- commit(): void;
307
- /** Notified after every write. The canvas uses this to repaint without a
308
- * scene version bump. */
309
- subscribe(fn: () => void): () => void;
310
- /** Monotonic write counter. A snapshot for observers that poll. */
311
- getGeneration(): number;
312
- }
313
- /**
314
- * The kit-owned scene tree: nodes, layers, and the undo history over both.
315
- *
316
- * A scene is logical, not visual — it says what exists and where, and nothing
317
- * about how it is painted. Every mutating method is undoable, and reads are
318
- * snapshots rather than live views. Nodes are addressed by `NodeId`; hold ids
319
- * across mutations, not node objects.
320
- *
321
- * Three type parameters keep it domain-agnostic: `TData` is the app's payload,
322
- * which the kit never inspects; `TPose` is the transform shape, `RectPose` by
323
- * default; `TLayer` is the union of layer names.
324
- */
325
- interface Scene<TData, TLayer extends string, TPose = RectPose> {
326
- readonly nodes: ReadonlyMap<NodeId, Node<TData, TLayer, TPose>>;
327
- readonly roots: readonly NodeId[];
328
- readonly layers: readonly LayerRecord<TLayer>[];
329
- get(id: NodeId): Node<TData, TLayer, TPose> | undefined;
330
- childrenOf(id: NodeId): readonly NodeId[];
331
- ancestorsOf(id: NodeId): readonly NodeId[];
332
- renderOrder(): Iterable<NodeId>;
333
- /** The same layer-major sequence as {@link Scene.renderOrder}, as the nodes
334
- * themselves. Prefer this wherever the ids are only going to be resolved
335
- * back to nodes: the traversal already holds them, and re-looking each one
336
- * up was ~40% of the area hit-test's per-node cost. Cached until a
337
- * structural edit, so repeat calls hand back the same array — a snapshot,
338
- * not a live view, and not yours to mutate. */
339
- renderOrderNodes(): readonly Node<TData, TLayer, TPose>[];
340
- add(spec: AddNodeSpec<TData, TLayer, TPose>): NodeId;
341
- /** Delete `id`, its **entire subtree**, and **everything that derives from**
342
- * any of those nodes — a node listing one of them in `dependsOn` goes too,
343
- * along with its own subtree, transitively. A dependent can live anywhere in
344
- * the tree, so this deletes nodes the caller never named and may unlink
345
- * several disjoint subtrees at once. Recorded as one undoable step; `undo()`
346
- * restores every one of them where it was, child order intact. */
347
- remove(id: NodeId): void;
348
- /** {@link remove} over several roots at once, as a **single** undoable step.
349
- * Ids resolve against the tree as it stands at the call, so an id that
350
- * another one would cascade away is absorbed rather than removed twice —
351
- * which is what makes it safe to pass a whole selection. Throws if any id is
352
- * not in the scene; an empty list does nothing and records no step. */
353
- removeMany(ids: readonly NodeId[]): void;
354
- /** Every node {@link removeMany} would take if given `ids`: each id, its
355
- * subtree, everything deriving from any of those, and those nodes' subtrees
356
- * in turn. The authoritative answer — the cascade relations live here, and
357
- * a caller reconstructing them from `dependsOn` and `children` drifts the
358
- * moment a third one is added. Ids not in the scene come back unchanged.
359
- *
360
- * A set, not a restore order: a dependent can be reached before the parent
361
- * it sits under, which is also in the closure. */
362
- removalClosure(ids: readonly NodeId[]): readonly NodeId[];
363
- update(id: NodeId, patch: {
364
- data: TData;
365
- }): void;
366
- setPose(id: NodeId, pose: TPose): void;
367
- /** Retag `id` to `layer`. On a **container this cascades**: every descendant
368
- * is moved to the same layer, recorded as a **single** undo step.
369
- *
370
- * Invariants:
371
- * - **Layer floor** — a child may not render below its parent, so retagging
372
- * to a layer *below* the node's parent throws. Retagging to the parent's
373
- * layer or any higher one is allowed; a node with no parent is
374
- * unconstrained.
375
- * - **No-op elision** — setting the layer a node already has does nothing
376
- * and pushes **no** history entry. */
377
- setLayer(id: NodeId, layer: TLayer): void;
378
- /** Reparent `id` under `parent` (or to a root when `parent` is `null`) at
379
- * `index` within the new sibling list, appending when `index` is omitted.
380
- * Siblings are reindexed. Recorded as one undoable step.
381
- *
382
- * Rejected (throws) when:
383
- * - `parent` exists but is a **leaf**, not a container;
384
- * - the move would form a **cycle** — `parent` is `id` itself or one of
385
- * `id`'s own descendants;
386
- * - it would drop `id` **below its new parent's layer** (child may not
387
- * render below its parent).
388
- *
389
- * `move(id, null)` — detaching to a root — is always allowed regardless of
390
- * layer, since a root has no parent to render beneath. */
391
- move(id: NodeId, parent: NodeId | null, index?: number): void;
392
- /** Shift `id` to `index` within its **current** parent's child list. Unlike
393
- * {@link move}, the parent never changes — only sibling order. */
394
- reorder(id: NodeId, index: number): void;
395
- setLayerVisible(layer: TLayer, visible: boolean): void;
396
- setLayerLocked(layer: TLayer, locked: boolean): void;
397
- addLayer(spec: AddLayerSpec<TLayer>): void;
398
- /** Drop a user layer and every node tagged to it, as one undoable step.
399
- * Removal cascades, so this also deletes nodes **on other layers** that
400
- * derive from a node on this one. */
401
- removeLayer(layer: TLayer): void;
402
- renameLayer(layer: TLayer, name: string): void;
403
- moveLayer(layer: TLayer, index: number): void;
404
- registerOp<P>(kind: string, handler: RegisteredOp<P>): void;
405
- recordOp<P>(op: {
406
- kind: string;
407
- payload: P;
408
- }): void;
409
- /** Install (or clear) the active-journal accessor after scene construction.
410
- * Useful when the journal source (typically a mode machine) is built
411
- * with `scene.history` as a dependency — a chicken-and-egg situation
412
- * where the accessor can't be passed in via `UseSceneOptions`.
413
- *
414
- * Pass `null` to detach. Overrides any `getActiveJournal` set in
415
- * `UseSceneOptions`. */
416
- setActiveJournalAccessor(fn: (() => _weasel_js_history.Journal | null) | null): void;
417
- /** Apply a batch of ops with journal-aware routing.
418
- *
419
- * - **Without active journal** (or no `getActiveJournal` in options):
420
- * the ops themselves are recorded as one undo entry on the scene's own
421
- * history, rebound to `adapter` — undo replays each op's `invert()`
422
- * against that same adapter. Consecutive `applyBatch` entries can
423
- * coalesce via matching op `coalesceKey`s when the scene opts into
424
- * `coalesceWindowMs`.
425
- * - **With active journal**: routes ops to `journal.applyBatch(ops, label)`.
426
- * The scene's history recording is suppressed for the duration so the
427
- * journal's inner history — not the scene's undo stack — tracks the batch.
428
- * Mutations still happen on `adapter` / scene state.
429
- *
430
- * `adapter` must be the same adapter the ops expect (typically a
431
- * `SceneCanvasAdapter`). Pass `this` from `sceneToAdapter` or a compatible
432
- * adapter. */
433
- applyBatch(ops: Op[], label: string, adapter: unknown): void;
434
- /** The transient set of active ids — "operate on these N as a unit".
435
- * Shared by every view over this scene unless a view supplies its own
436
- * (see `CanvasView.selection`). Not document content: it never appears
437
- * in `toJSON`. It does ride on history entries, so undo and redo put
438
- * back the selection an edit was made under; changing it is never an
439
- * undo step of its own. */
440
- getSelection(): readonly NodeId[];
441
- setSelection(ids: readonly NodeId[]): void;
442
- /** Per-node pose / alpha overrides the render and hit-test paths read
443
- * through. Like {@link Scene.getSelection} this is not document content:
444
- * writes are never recorded, never serialized, and do not bump
445
- * {@link Scene.getVersion}. See {@link PoseOverrides}. */
446
- readonly overrides: PoseOverrides<TPose>;
447
- undo(): boolean;
448
- redo(): boolean;
449
- canUndo(): boolean;
450
- canRedo(): boolean;
451
- batch<T>(label: string, fn: () => T): T;
452
- /** Read-only snapshot of every history entry currently reachable from
453
- * the present state. Oldest applied first, then redoable entries in
454
- * the order they'd be re-applied. Each entry id is stable. */
455
- historyEntries(): readonly {
456
- id: string;
457
- label: string;
458
- }[];
459
- /** Index of the "current state". Equals the count of applied entries;
460
- * `0` means "nothing applied" (initial). */
461
- historyIndex(): number;
462
- /** Jump to the given history index by calling undo/redo repeatedly.
463
- * Clamps to [0, total]. Returns true if any movement occurred. */
464
- jumpToHistoryIndex(index: number): boolean;
465
- /** Snapshot the undo/redo history in a JSON-serializable form (the
466
- * engine's `SerializedHistory`). Entries containing any nameless op are
467
- * dropped (hand-rolled anonymous ops passed to `applyBatch`); kit and
468
- * consumer-registered ops always carry names. Payload JSON-safety
469
- * (e.g. typed arrays inside poses) is the caller's concern. Do not call
470
- * mid-`batch` — the open batch's ops are not yet recorded. */
471
- serializeHistory(): SerializedHistory;
472
- /** Replace the undo/redo history from a `serializeHistory()` snapshot.
473
- * Call on a scene whose node/layer state already matches the snapshot's
474
- * head state (i.e. right after `loadState` from the paired scene
475
- * snapshot); node state is NOT mutated. Ops re-registered via
476
- * `registerOp` before this call round-trip; unknown kinds become no-op
477
- * placeholders; external ops rebuild via the global op-factory registry
478
- * and replay against the `setHistoryAdapter` accessor. Restored entries
479
- * never coalesce with new ones. Notifies once. Do not call mid-`batch`:
480
- * the stacks are replaced underneath the open batch, whose eventual
481
- * flush would graft onto (and evict against) the restored stacks. */
482
- restoreHistory(snapshot: SerializedHistory): void;
483
- /** Install (or clear with `null`) the accessor for the adapter that
484
- * RESTORED external ops (recorded via `applyBatch`, rebuilt from a
485
- * `restoreHistory` snapshot) apply against on undo/redo. Resolved lazily
486
- * at each apply, so wiring order relative to `restoreHistory` doesn't
487
- * matter. Live `applyBatch` entries are unaffected (they bind their
488
- * call-site adapter). If unset when a restored op applies, the op is a
489
- * debug-warned no-op. */
490
- setHistoryAdapter(fn: (() => unknown) | null): void;
491
- /** Snapshot the current scene state to a JSON-serializable shape.
492
- * History (undo/redo stacks) is NOT captured. Function fields like
493
- * `ContainerNode.clipFromPose` are translated to string keys via the
494
- * scene's registry; throws if any function field has no matching key. */
495
- toJSON(): SerializedScene<TData, TLayer, TPose>;
496
- /** Replace this scene's entire node + layer state in place from a snapshot
497
- * produced by `toJSON()`. Unlike `sceneFromJSON`, the existing Scene
498
- * instance is preserved — holders such as `<SceneCanvas>` keep their
499
- * reference. History (undo/redo) is cleared, matching `sceneFromJSON`.
500
- * Bumps `getVersion()` and notifies subscribers exactly once.
501
- *
502
- * Throws on an unsupported version or unknown registry/layer ids; on a
503
- * malformed snapshot the scene is left empty or partially populated (callers should treat a
504
- * `loadState` throw as fatal and reload). Snapshots from `toJSON()` are
505
- * always well-formed. */
506
- loadState(json: SerializedScene<TData, TLayer, TPose>): void;
507
- subscribe(listener: () => void): () => void;
508
- /** Monotonically increasing version. Snapshot for `useSyncExternalStore`. */
509
- getVersion(): number;
510
- }
511
-
512
- export { type AddLayerSpec as A, type ContainerNode as C, type LayerRecord as L, type NodeId as N, type PoseOverride as P, type RectPose as R, type Scene as S, type UseSceneOptions as U, type Node as a, type SerializedScene as b, type SceneRegistry as c, type RegisteredOp as d, type AddNodeSpec as e, type LeafNode as f, type PoseOverrides as g, type SerializedNode as h, type SystemLayerRecord as i, type SystemLayerSpec as j, type UserLayerRecord as k, asNodeId as l };