@invana/canvas-core 0.0.12

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.
@@ -0,0 +1,4063 @@
1
+ import { F as FlushMode, S as SpecFlush, L as Listener, C as CameraTransform$1, R as Rect, a as SpecStore, P as Point, B as BaseShapeSpec, b as BaseConnectorSpec, D as DecorationSpec, c as BadgeOptions, E as EffectSpec, d as LabelContent, e as LabelWrap, H as HitResult, f as EventEmitter, g as ElementEventMap, h as EventMap, I as IAnchor, i as IRouter, j as IPathStyle, k as Path, V as Vec2, l as BadgePlacement, m as ShapeFill, n as ShapeStroke } from './index-C-drjwfS.js';
2
+ export { A as AnchorCtx, o as AnchorShapeRef, p as AnchorSpec, q as ArcSpec, r as BadgeShapeSpec, s as CircleSpec, t as CompositePart, u as CompositePartFill, v as CompositePartStroke, w as CompositeRootSpec, x as CompositeSpec, y as ConnectorBadgePlacement, z as ConnectorEndpointSpec, G as ConnectorLabelPlacement, J as ConnectorLabelStyle, K as ConnectorPaintStyle, M as DecorationTarget, N as EffectTarget, O as EffectTargetKind, Q as EllipseSpec, T as Endpoint, U as FlowParticlesConnectorDecorationStyle, W as FlyMarkerConnectorDecorationStyle, X as GlowConnectorDecorationStyle, Y as GlowDecorationStyle, Z as HtmlTagStyle, _ as InsetAnchor, $ as InsetFillLayer, a0 as LabelBackground, a1 as LabelStyleCommon, a2 as LabelVisibility, a3 as LiquidFillDecorationStyle, a4 as LocalSpec, a5 as MarchingAntsConnectorDecorationStyle, a6 as MarchingAntsDecorationStyle, a7 as MarkerShapeSpec, a8 as NamedBadgePlacement, a9 as Obstacle, aa as PathCommand, ab as PathSpec, ac as PathStyleEndpoints, ad as PlaneName, ae as PolygonSpec, af as Polyline, ag as PulseRingDecorationStyle, ah as RectSpec, ai as RegisterDecorationOptions, aj as RegisterEffectOptions, ak as RegularPolygonSpec, al as RenderStats, am as ResizeHandleDecorationStyle, an as ResizeHandlePlacement, ao as RevealConnectorDecorationStyle, ap as RevealDirection, aq as RevealEasingName, ar as RevealHostStroke, as as RevealRepeat, at as RingConnectorDecorationStyle, au as RingDecorationStyle, av as RippleConnectorDecorationStyle, aw as RoundedCorner, ax as RouterCtx, ay as SelectionFrameBorderStyle, az as SelectionFrameDecorationStyle, aA as SelectionFrameHandleHit, aB as SelectionFrameHandleShape, aC as SelectionFramePlacement, aD as ShapeFillLayer, aE as ShapeLabelPlacement, aF as ShapeLabelStyle, aG as ShapePaintStyle, aH as ShapeSpec, aI as Size, aJ as StarSpec, aK as StyleOverride, aL as TabAlign, aM as TabbedRectGeometry, aN as TabbedRectGeometrySpec, aO as TabbedRectSpec, aP as ToggleDecorationStyle, aQ as ToggleHitGeometry, aR as TogglePlacement, aS as TransformDelta, aT as boundsOfArc, aU as boundsOfCircle, aV as boundsOfComposite, aW as boundsOfCompositeRoot, aX as boundsOfEllipse, aY as boundsOfPath, aZ as boundsOfPolygon, a_ as boundsOfRect, a$ as boundsOfRegularPolygon, b0 as boundsOfSpec, b1 as boundsOfStar, b2 as collapsedSpec, b3 as collapsedTabbedRect, b4 as compositeRootOffset, b5 as connectorGeometryKey, b6 as containsArc, b7 as containsCircle, b8 as containsComposite, b9 as containsEllipse, ba as containsPath, bb as containsPolygon, bc as containsRect, bd as containsRegularPolygon, be as containsSpec, bf as containsStar, bg as containsTabbedRect, bh as distanceToOutlineSq, bi as distanceToSegmentSq, bj as fitSpecToContent, bk as fitTabbedRectToContent, bl as hasSilhouetteFill, bm as offsetPolygon, bn as pointInPolygon, bo as polygonBounds, bp as polygonContainsInflated, bq as rayPolygonIntersection, br as regularPolygonVertices, bs as resolveCompositeRoot, bt as roundedPolygonOutline, bu as scaleArc, bv as scaleCircle, bw as scaleEllipse, bx as scalePath, by as scalePolygon, bz as scaleRect, bA as scaleRegularPolygon, bB as scaleSpec, bC as scaleStar, bD as scaleTabbedRect, bE as scheduleFlush, bF as starVertices, bG as strokeBandOf, bH as tabbedRectBounds, bI as tabbedRectFoldLine, bJ as tabbedRectGeometry, bK as tabbedRectOutline, bL as tabbedRectTabBox, bM as tabbedRectTabWidth, bN as verticesOfRegularPolygon, bO as verticesOfStar } from './index-C-drjwfS.js';
3
+
4
+ /**
5
+ * The **device-shaped** half of the renderer seam — the part the kernel can
6
+ * legitimately own.
7
+ *
8
+ * ## Why the interface itself moved out
9
+ *
10
+ * This file used to declare `IRenderer` with `applyView` / `applyData`: a push
11
+ * model where the orchestrator handed the renderer view and data deltas. Two
12
+ * things happened to it.
13
+ *
14
+ * 1. **P2 replaced the flow.** Durable visuals became state (`store.specs`) and
15
+ * the renderer now *subscribes* — `specs:flush` → `SpecProjector` → mounted
16
+ * elements. Nothing pushes a view or a data delta at a renderer any more, so
17
+ * those two methods described a design that no longer exists. They had zero
18
+ * implementers and zero callers, which is exactly how a stale interface
19
+ * survives unnoticed.
20
+ * 2. **The real contract is made of spec vocabulary.** Surfaces project
21
+ * `BaseShapeSpec` / `BaseConnectorSpec`; overlays draw in engine geometry.
22
+ * That vocabulary lives above the kernel (re-exported by `@invana/canvas`), and the kernel imports no
23
+ * `@invana` package — so the interface cannot live here without inverting the
24
+ * dependency layering.
25
+ *
26
+ * `IRenderer` therefore lives at `@invana/canvas-core` → `src/contracts/IRenderer.ts`.
27
+ * What stays here is what is genuinely kernel-shaped: the backend name a
28
+ * renderer resolved to, and {@link RendererInitOptions} — the non-syncable
29
+ * device counterpart to the syncable `CanvasSceneOptions`.
30
+ */
31
+ /**
32
+ * The backend a renderer resolved to at mount. Open-ended (`string & {}`) so a
33
+ * concrete adapter can report a backend the kernel doesn't enumerate, while the
34
+ * common trio stays autocompletable.
35
+ */
36
+ type RendererBackend = 'webgpu' | 'webgl' | 'canvas' | (string & {});
37
+
38
+ /**
39
+ * `RendererInitOptions` — the **adapter-local, non-syncable** init bag handed to a
40
+ * renderer at `IRenderer.mount` (the interface lives in `@invana/canvas`).
41
+ *
42
+ * These are deliberately the device/backend knobs that {@link CanvasSceneOptions}
43
+ * (`view/CanvasView.ts`) leaves out on purpose — they belong to the renderer
44
+ * adapter, not the syncable `view.definition`. Where the split falls:
45
+ *
46
+ * - **Syncable scene config** (background, zoom clamp, world bounds, default mode)
47
+ * → `view.definition.canvas` ({@link CanvasSceneOptions}) — converges in a CRDT.
48
+ * - **Device / init options** (which GPU backend, antialias, DPR, canvas size) →
49
+ * **here** — per-client, never synced, only meaningful at mount.
50
+ *
51
+ * A concrete renderer (e.g. `@invana/renderer-pixijs`) may widen this with its own
52
+ * backend-specific fields; the kernel types only the portable subset.
53
+ */
54
+ /**
55
+ * Preferred drawing backend, in descending order of capability:
56
+ *
57
+ * - `'webgpu'` — the fastest path where the browser supports it.
58
+ * - `'webgl'` — the universal fallback; opt out of WebGPU entirely by asking for it.
59
+ * - `'canvas'` — the 2D-context renderer of last resort (no GPU context at all).
60
+ *
61
+ * **This is the single declaration of the preference vocabulary.** The engine's
62
+ * `CanvasOptions.preference` and each backend's own preference type alias *this*,
63
+ * so the seam between them cannot silently diverge — it did once, and a
64
+ * `'canvas'` request was quietly downgraded to WebGL for it. Omit the option
65
+ * entirely to let the backend choose (the documented default); there is no
66
+ * separate `'auto'` spelling of that.
67
+ */
68
+ type RenderPreference = 'webgpu' | 'webgl' | 'canvas';
69
+ interface RendererInitOptions {
70
+ /**
71
+ * Preferred GPU backend ({@link RenderPreference}). The renderer may downgrade
72
+ * (e.g. `'webgpu'` → `'webgl'` on browsers whose WebGPU path is unavailable);
73
+ * the resolved value is reported on `IRenderer.backend` after mount. Omit to
74
+ * let the backend choose.
75
+ */
76
+ preference?: RenderPreference;
77
+ /** Enable multisample antialiasing. */
78
+ antialias?: boolean;
79
+ /** Device-pixel-ratio / resolution override. Defaults to the display DPR. */
80
+ resolution?: number;
81
+ /**
82
+ * Initial drawing-surface size in CSS pixels. Omit to fill (and track) the host
83
+ * element's client box.
84
+ */
85
+ width?: number;
86
+ height?: number;
87
+ /**
88
+ * Initial clear colour (`0xRRGGBB`) applied before the first frame. The ongoing
89
+ * scene background is the syncable {@link CanvasSceneOptions.backgroundColor};
90
+ * this is only the pre-mount clear.
91
+ */
92
+ background?: number;
93
+ }
94
+
95
+ /**
96
+ * `ColumnStore<TSchema>` — typed-array column store for **bulk hot data** (the
97
+ * kernel's machine-rate **DATA-HOT lane**: node `x`/`y`, flags, bulk attrs).
98
+ *
99
+ * Relocated into `@invana/canvas-store` (decision D1) so the renderer-free kernel
100
+ * owns the data hot path; `@invana/canvas` consumes it (and may re-export for
101
+ * back-compat). Imports **no** drawing library.
102
+ *
103
+ * Designed to scale to millions of items at machine-rate mutation (1000s/sec from
104
+ * external feeds). Where the reactive store (immer) makes per-mutation
105
+ * structural-sharing trade-offs that cap out around 5–10k for hot data,
106
+ * `ColumnStore` mutates typed-array slots in place at ~10 ns per write — so
107
+ * layout churn / position streams **never** touch the reactive/CRDT path.
108
+ *
109
+ * **Mental model:** one id-keyed object `{ id:'n-42', x:100, y:50 }` becomes
110
+ * slot 17 across N parallel typed-array columns. Lookup is id → slot
111
+ * (`Map<string, number>`), then columns are read/written by indexing slot. Slots
112
+ * recycle on remove, so buffers stay compact under churn.
113
+ *
114
+ * @example
115
+ * type NodeSchema = { x: 'f32'; y: 'f32'; flags: 'u8' };
116
+ * const nodes = new ColumnStore<NodeSchema>({ x: 'f32', y: 'f32', flags: 'u8' });
117
+ * nodes.add('n-1', { x: 10, y: 20, flags: 0 });
118
+ * // Renderer / layout fast path — hold refs once, write directly:
119
+ * const xCol = nodes.column('x'); const slot = nodes.slot('n-1')!;
120
+ * xCol[slot] = 40; // ~10 ns
121
+ * nodes.touch(); // bump version after fast-path writes
122
+ */
123
+ /**
124
+ * Numeric type tags for typed-array columns. Each maps to a JS TypedArray ctor.
125
+ * `i8/u8` — bytes (booleans, bitfields, packed enums); `i16/u16` — short ints;
126
+ * `i32/u32` — slot refs / packed colours / hashes; `f32` — coordinates / weights
127
+ * (default); `f64` — only when precision matters.
128
+ */
129
+ type ColumnType = 'i8' | 'u8' | 'i16' | 'u16' | 'i32' | 'u32' | 'f32' | 'f64';
130
+ type ColumnSchema = Record<string, ColumnType>;
131
+ type ColumnValue<T extends ColumnType> = T extends 'f32' | 'f64' ? number : number;
132
+ type ColumnArray<T extends ColumnType> = T extends 'i8' ? Int8Array : T extends 'u8' ? Uint8Array : T extends 'i16' ? Int16Array : T extends 'u16' ? Uint16Array : T extends 'i32' ? Int32Array : T extends 'u32' ? Uint32Array : T extends 'f32' ? Float32Array : T extends 'f64' ? Float64Array : never;
133
+ /** Shape of a row in `add()` / `addBulk()`: each schema field maps to a number. */
134
+ type RowOf<TSchema extends ColumnSchema> = {
135
+ [K in keyof TSchema]: ColumnValue<TSchema[K]>;
136
+ };
137
+ interface ColumnStoreOptions {
138
+ /** Initial slot capacity. Doubles on overflow. Default 256. */
139
+ initialCapacity?: number;
140
+ /** Max capacity. Throws on overflow. Default 16_777_216 (~16M). */
141
+ maxCapacity?: number;
142
+ }
143
+ declare class ColumnStore<TSchema extends ColumnSchema = ColumnSchema> {
144
+ private readonly schema;
145
+ private readonly columnNames;
146
+ private readonly maxCapacity;
147
+ /** id → slot. The only object-keyed lookup on the hot path. */
148
+ private readonly idIndex;
149
+ /** slot → id. Filled slots have a string; recycled holes have `undefined`. */
150
+ private readonly idReverse;
151
+ /** Stack of recycled slots. `add()` pops from here before extending. */
152
+ private readonly freeSlots;
153
+ /** TypedArray per column. Replaced on grow (new buffer with copied data). */
154
+ private columns;
155
+ /** Current capacity (length of each TypedArray). */
156
+ private _capacity;
157
+ /** High-water mark — largest slot index ever assigned + 1. Not necessarily filled. */
158
+ private _highWater;
159
+ /** Mutation version. Increments on any add/remove/set or `touch()`. */
160
+ private _version;
161
+ constructor(schema: TSchema, opts?: ColumnStoreOptions);
162
+ /** Number of items currently stored. */
163
+ get size(): number;
164
+ /** Current allocated capacity. Grows automatically when filled. */
165
+ get capacity(): number;
166
+ /** Mutation counter — bumps on any change. Subscribers diff this. */
167
+ get version(): number;
168
+ /** True iff `id` has been added. */
169
+ has(id: string): boolean;
170
+ /** Returns the slot for `id`, or `undefined`. Useful for the renderer fast path. */
171
+ slot(id: string): number | undefined;
172
+ /** Returns the id at `slot`, or `undefined` if the slot is free. */
173
+ idAt(slot: number): string | undefined;
174
+ /**
175
+ * Direct access to a column's TypedArray. **Holds a stable reference until the
176
+ * column is grown** (then the buffer is replaced). Use {@link version} to detect
177
+ * grow events. Renderer/layout fast path: cache `column(name)` + `slot(id)` once
178
+ * per frame and write directly, then call {@link touch}.
179
+ */
180
+ column<K extends keyof TSchema>(name: K): ColumnArray<TSchema[K]>;
181
+ /** Read a single value. ~50 ns: Map.get + TypedArray read. */
182
+ get<K extends keyof TSchema>(id: string, name: K): ColumnValue<TSchema[K]> | undefined;
183
+ /** Materialise a full row by id. Allocates an object — avoid in hot loops. */
184
+ row(id: string): RowOf<TSchema> | undefined;
185
+ /** Add a new item. Throws if `id` already exists. Reuses a recycled slot when available. */
186
+ add(id: string, row: RowOf<TSchema>): number;
187
+ /** Bulk add. Grows once if needed (cheaper than N individual grows). Throws on duplicate id. */
188
+ addBulk(items: ReadonlyArray<{
189
+ id: string;
190
+ row: RowOf<TSchema>;
191
+ }>): void;
192
+ /** Set a single field. ~50 ns. No-op if id doesn't exist. */
193
+ set<K extends keyof TSchema>(id: string, name: K, value: ColumnValue<TSchema[K]>): void;
194
+ /** Update multiple fields of one item in one call (one version bump). */
195
+ update(id: string, partial: Partial<RowOf<TSchema>>): void;
196
+ /** Remove an item. Recycles the slot. No-op if id doesn't exist. */
197
+ remove(id: string): void;
198
+ /** Bulk remove. */
199
+ removeBulk(ids: readonly string[]): void;
200
+ /**
201
+ * Mark the store as mutated without an API change — call after batches of
202
+ * fast-path writes via `column(...)[slot] = ...` so version-driven subscribers
203
+ * re-read.
204
+ */
205
+ touch(): void;
206
+ /** Drop all items + recycled slots. Keeps capacity (no shrink). */
207
+ clear(): void;
208
+ /** Iterate (id, slot) for currently-live ids. O(size) — does not walk holes. */
209
+ forEach(cb: (id: string, slot: number) => void): void;
210
+ /** Iterator over live ids only. */
211
+ ids(): IterableIterator<string>;
212
+ private allocSlot;
213
+ /** Grow each column to at least `target` (doubling past it). */
214
+ private grow;
215
+ }
216
+
217
+ /**
218
+ * `LayerData` — the **non-reactive** graph data for one source: four record
219
+ * collections (nodes · edges · groups · annotations) with full CRUD, **bulk
220
+ * position updates** (layout output), and **one coalesced `flush` per frame**
221
+ * carrying a per-kind delta. Subscribers (the renderer) rebuild only the delta.
222
+ *
223
+ * **Two lanes (the two physics).** Bulk + machine-rate → it lives *outside* the
224
+ * reactive `view` store:
225
+ * - **COLD** — `Map<id, record>` for human-rate fields (payload/label/style/…).
226
+ * - **HOT** — a typed-array {@link ColumnStore} for node **positions** (`x`/`y`)
227
+ * and a `flags` byte (has-position / pinned / disabled / hidden). A position
228
+ * write is ~10 ns (one `Float32Array` slot), no per-node object, no GC. The
229
+ * layout/renderer fast path holds the column ref and writes slots directly
230
+ * (see {@link positions} + {@link touchPositions}).
231
+ *
232
+ * `node(id)` stitches the two lanes back into one record on read (cold reads are
233
+ * human-rate; the hot path reads the column directly). The `flush` delta shape is
234
+ * **unchanged** by the lane split — `moved` (position-only) stays separate from
235
+ * `changed` (structure), so a move is a transform-only re-render.
236
+ *
237
+ * **When** the coalesced flush fires is the {@link FlushMode} (default `'microtask'`);
238
+ * the engine flips its stores to `'manual'` and drains them from one rAF loop. See
239
+ * `docs/canvas-store-data-event-flow.md` §2.2.
240
+ */
241
+
242
+ interface NodeRecord {
243
+ id: string;
244
+ x?: number;
245
+ y?: number;
246
+ [key: string]: unknown;
247
+ }
248
+ interface EdgeRecord {
249
+ id: string;
250
+ source: string;
251
+ target: string;
252
+ [key: string]: unknown;
253
+ }
254
+ interface GroupRecord {
255
+ id: string;
256
+ memberIds: string[];
257
+ /** Derived encapsulating geometry (hull / rect / …) — computed by a deriver. */
258
+ geometry?: unknown;
259
+ [key: string]: unknown;
260
+ }
261
+ interface AnnotationRecord {
262
+ id: string;
263
+ kind: string;
264
+ [key: string]: unknown;
265
+ }
266
+ /** Added / changed / removed ids for one collection. */
267
+ interface KindDelta {
268
+ added: string[];
269
+ changed: string[];
270
+ removed: string[];
271
+ }
272
+ /** Nodes also carry `moved` — position-only changes (transform-only re-render). */
273
+ interface NodeDelta extends KindDelta {
274
+ /** Ids whose position changed this frame. Empty when {@link movedAll} is set. */
275
+ moved: string[];
276
+ /**
277
+ * Every node moved (a force-sim tick via {@link LayerData.touchPositions}) —
278
+ * `moved` is left **empty** so the kernel doesn't allocate an N-id array each
279
+ * frame; the renderer iterates all positions directly. O(1) per flush.
280
+ */
281
+ movedAll: boolean;
282
+ }
283
+ /** The per-frame coalesced delta across all four collections. */
284
+ interface LayerFlush {
285
+ nodes: NodeDelta;
286
+ edges: KindDelta;
287
+ groups: KindDelta;
288
+ annotations: KindDelta;
289
+ /** Monotonic version — bumps once per flush. */
290
+ version: number;
291
+ }
292
+ /** Bulk seed/replace input. */
293
+ interface GraphInput {
294
+ nodes?: readonly NodeRecord[];
295
+ edges?: readonly EdgeRecord[];
296
+ groups?: readonly GroupRecord[];
297
+ annotations?: readonly AnnotationRecord[];
298
+ }
299
+ /** The hot-lane schema: positions (`x`/`y`) + a packed `flags` byte. */
300
+ type PosSchema = {
301
+ x: 'f32';
302
+ y: 'f32';
303
+ flags: 'u8';
304
+ };
305
+ /** Bits in the node `flags` column. `HAS_POSITION` distinguishes unset from `(0,0)`. */
306
+ declare const NODE_FLAG: {
307
+ readonly HAS_POSITION: 1;
308
+ readonly PINNED: 2;
309
+ readonly DISABLED: 4;
310
+ readonly HIDDEN: 8;
311
+ };
312
+ /** Streaming/ingestion lifecycle for a data source. */
313
+ type QueryStatus = 'idle' | 'loading' | 'streaming' | 'error';
314
+ /** A named data mutation, recorded for audit / collaboration (distinct from the per-frame flush). */
315
+ interface IntentLogEntry {
316
+ action: string;
317
+ ids?: readonly string[];
318
+ ts: number;
319
+ }
320
+ declare class LayerData {
321
+ /** COLD lane — node records WITHOUT `x`/`y` (positions live in {@link _pos}). */
322
+ private readonly _nodes;
323
+ /** HOT lane — typed-array `x`/`y`/`flags` columns, keyed by node id. */
324
+ private readonly _pos;
325
+ private readonly _edges;
326
+ private readonly _groups;
327
+ private readonly _annotations;
328
+ private readonly dNodes;
329
+ private readonly dMoved;
330
+ private _movedAll;
331
+ private readonly dEdges;
332
+ private readonly dGroups;
333
+ private readonly dAnnotations;
334
+ private readonly listeners;
335
+ private version;
336
+ private scheduled;
337
+ private flushMode;
338
+ private cancel;
339
+ private _status;
340
+ private readonly _intents;
341
+ private readonly statusListeners;
342
+ /** Subscribe to coalesced `flush` deltas. Returns an unsubscribe. */
343
+ on(event: 'flush', listener: (e: LayerFlush) => void): () => void;
344
+ /** {@link DataSource} contract — alias for `on('flush', …)`. */
345
+ onFlush(listener: (e: LayerFlush) => void): () => void;
346
+ /**
347
+ * Choose **when** a flush fires ({@link FlushMode}). `'manual'` disarms any pending
348
+ * auto-flush so only an explicit {@link flush} emits — used when the engine drives
349
+ * every layer's data from one rAF loop.
350
+ */
351
+ setFlushMode(mode: FlushMode): void;
352
+ /** Read a node, **stitching** its cold record with its hot `x`/`y` (when set). */
353
+ node(id: string): NodeRecord | undefined;
354
+ edge(id: string): EdgeRecord | undefined;
355
+ group(id: string): GroupRecord | undefined;
356
+ annotation(id: string): AnnotationRecord | undefined;
357
+ nodes(): NodeRecord[];
358
+ edges(): EdgeRecord[];
359
+ groups(): GroupRecord[];
360
+ annotations(): AnnotationRecord[];
361
+ get counts(): {
362
+ nodes: number;
363
+ edges: number;
364
+ groups: number;
365
+ annotations: number;
366
+ };
367
+ /**
368
+ * Direct access to the typed-array position columns. Hold the ref + a slot once
369
+ * and write in place (~10 ns/slot), then call {@link touchPositions} to emit one
370
+ * coalesced moved flush. `positions.slot(id)` maps id → column index.
371
+ */
372
+ get positions(): ColumnStore<PosSchema>;
373
+ /**
374
+ * Bulk-apply layout output from an **interleaved** `[x0,y0,x1,y1,…]` buffer —
375
+ * the layout fast path. Skips ids that aren't present; marks each `moved`.
376
+ */
377
+ setPositionsBulk(ids: readonly string[], xy: ArrayLike<number>): void;
378
+ /**
379
+ * After writing position slots directly via {@link positions}, call this to bump
380
+ * the version and emit **one** flush that marks every node `moved` (the per-tick
381
+ * force-sim path — "everything moved", transform-only).
382
+ */
383
+ touchPositions(): void;
384
+ /** Read a node's `flags` byte, or `undefined`. */
385
+ nodeFlags(id: string): number | undefined;
386
+ /** Toggle a {@link NODE_FLAG} bit (e.g. pinned/disabled) — marks the node `changed`. */
387
+ setNodeFlag(id: string, flag: number, on: boolean): void;
388
+ /** Current ingestion lifecycle status. */
389
+ get status(): QueryStatus;
390
+ /** Set the ingestion status; notifies {@link onStatus} listeners on change. */
391
+ setStatus(status: QueryStatus): void;
392
+ /** Subscribe to status changes. Returns an unsubscribe. */
393
+ onStatus(listener: (status: QueryStatus) => void): () => void;
394
+ /** The data-mutation audit trail (one entry per named action). */
395
+ intents(): readonly IntentLogEntry[];
396
+ /** Record a named data intent (audit / collab). */
397
+ logIntent(action: string, ids?: readonly string[], ts?: number): void;
398
+ /** Replace the whole graph — diffs each collection into the next flush. */
399
+ setData(input: GraphInput): void;
400
+ /** Bulk-apply layout output (positions) → marks nodes `moved` (transform-only). */
401
+ applyPositions(positions: Iterable<{
402
+ id: string;
403
+ x: number;
404
+ y: number;
405
+ }>): void;
406
+ addNode(n: NodeRecord): void;
407
+ updateNode(id: string, patch: Partial<NodeRecord>): void;
408
+ removeNode(id: string): void;
409
+ addEdge(e: EdgeRecord): void;
410
+ updateEdge(id: string, patch: Partial<EdgeRecord>): void;
411
+ removeEdge(id: string): void;
412
+ addGroup(g: GroupRecord): void;
413
+ updateGroup(id: string, patch: Partial<GroupRecord>): void;
414
+ removeGroup(id: string): void;
415
+ addAnnotation(a: AnnotationRecord): void;
416
+ updateAnnotation(id: string, patch: Partial<AnnotationRecord>): void;
417
+ removeAnnotation(id: string): void;
418
+ /** Emit the pending delta now (the engine calls this once per frame). */
419
+ flush(): void;
420
+ private schedule;
421
+ private isClean;
422
+ /** Insert/replace a node: cold record (minus x/y) + hot position columns. */
423
+ private upsertNode;
424
+ /**
425
+ * Write a node's position into the hot column. `replace` (used on full upsert)
426
+ * clears the `HAS_POSITION` bit when no `x`/`y` is supplied; otherwise a partial
427
+ * update keeps the existing coordinate for an omitted axis.
428
+ */
429
+ private writePos;
430
+ private replaceNodes;
431
+ private upsert;
432
+ private patchRecord;
433
+ private removeFrom;
434
+ private replaceKind;
435
+ }
436
+
437
+ /**
438
+ * Frame-performance types — the vendor-neutral contract for the engine's
439
+ * per-frame observability signal. The engine (`@invana/canvas`) *measures*
440
+ * frames and emits a {@link FrameTick} on the `render:loop:tick` bus event;
441
+ * an app-side adapter maps those onto OpenTelemetry metrics + spans (see
442
+ * `telemetry/tracing.ts` for the sibling span port). These types live in the
443
+ * kernel because the kernel owns the {@link CanvasGlobalEvents} contract — the
444
+ * measurement lives in the engine, the shape lives here.
445
+ *
446
+ * Design intent (the "F1 telemetry" model): a continuous FPS/frame-time trace
447
+ * (`dt` / {@link FrameTick.fps}), a per-phase breakdown of where the CPU frame
448
+ * went ({@link FramePhaseTimings}), and an {@link InteractionKind} tag so every
449
+ * frame is attributable to the gesture that caused it — the metric dimension
450
+ * that lets a dashboard show *which* action dipped FPS and by how much.
451
+ */
452
+ /**
453
+ * The user-interaction category a frame is attributed to. A deliberately small,
454
+ * closed set so it is safe to use as a metric/span **dimension** (bounded
455
+ * cardinality). `'idle'` is the default when no gesture is active.
456
+ */
457
+ type InteractionKind = 'idle' | 'pan' | 'zoom' | 'drag' | 'hover' | 'layout';
458
+ /**
459
+ * The CPU sub-phases measured inside one engine tick (`Canvas.tickOnce`):
460
+ * - `camera` — advancing viewport plugins (`camera.tick`).
461
+ * - `dataFlush` — draining every registered data source's coalesced flush.
462
+ * - `layers` — per-layer `flush()` + `tickAnimations()`.
463
+ *
464
+ * These sum to {@link FrameTick.cpuMs}. GPU render + browser compositing happen
465
+ * *outside* the tick and are therefore not in this breakdown — the remainder
466
+ * `dt - cpuMs` approximates render + idle.
467
+ */
468
+ type FramePhase = 'camera' | 'dataFlush' | 'layers';
469
+ /** Per-phase wall-clock cost (ms) within a single frame's CPU tick. */
470
+ type FramePhaseTimings = Record<FramePhase, number>;
471
+ /**
472
+ * One measured engine frame — the payload of the `render:loop:tick` bus event.
473
+ * Emitted once per `Canvas.tickOnce`.
474
+ */
475
+ interface FrameTick {
476
+ /** `performance.now()` at the start of this frame's tick. */
477
+ ts: number;
478
+ /**
479
+ * Inter-frame period in ms (the renderer ticker's delta) — the FPS
480
+ * denominator and the primary "speed trace" value.
481
+ */
482
+ dt: number;
483
+ /** `1000 / dt`, clamped to a sane ceiling — instantaneous frames-per-second. */
484
+ fps: number;
485
+ /** Total CPU cost measured inside the tick (sum of {@link phases}). */
486
+ cpuMs: number;
487
+ /** Per-phase CPU breakdown; the values sum to {@link cpuMs}. */
488
+ phases: FramePhaseTimings;
489
+ /** The interaction this frame is attributed to (`'idle'` when no gesture is active). */
490
+ interaction: InteractionKind;
491
+ /** True when `dt` exceeded the long-frame (jank) threshold. */
492
+ longFrame: boolean;
493
+ }
494
+ /**
495
+ * Windowed frame statistics — a cheap pull-model summary for a HUD / status
496
+ * bar, computed on demand from a {@link FrameTick} ring buffer. (The push model
497
+ * is the `render:loop:tick` event; this is the complementary "read the last N"
498
+ * view.)
499
+ */
500
+ interface FrameStats {
501
+ /** Number of samples the stats were computed over. */
502
+ count: number;
503
+ /** Median FPS across the window (`1000 / p50Ms`). */
504
+ fps: number;
505
+ /** Median frame time (ms). */
506
+ p50Ms: number;
507
+ /** 95th-percentile frame time (ms) — the "typical worst" frame. */
508
+ p95Ms: number;
509
+ /** Worst single frame time (ms) in the window — the dip. */
510
+ maxMs: number;
511
+ /** Count of long (jank) frames in the window. */
512
+ dropped: number;
513
+ }
514
+
515
+ /**
516
+ * Renderer-free **theme state** for the kernel — the fully-**resolved** theme the
517
+ * engine publishes and theme-aware layers recolour from. Relocated from the
518
+ * engine (`@invana/canvas`); roles are plain `string` keys → colour numbers (the
519
+ * named `ColorRole` vocabulary stays in `@invana/graph`).
520
+ *
521
+ * Two distinct things, don't conflate them:
522
+ * - **Authored theme config** (registry / active family / mode / accent) lives in
523
+ * `view.definition.theme` (serialisable, synced).
524
+ * - **The resolved theme** below is the *derived* output a `ThemeBehaviour`
525
+ * computes from that config + mode, and publishes via {@link ThemeState.set}.
526
+ */
527
+ /** The concrete kind a theme mode resolves to. */
528
+ type ThemeKind = 'light' | 'dark';
529
+ /** Mode selector. `'system'` follows the host `prefers-color-scheme`; the rest pin. */
530
+ type ThemeMode = 'system' | 'light' | 'dark';
531
+ /** A fully-resolved theme — every role already a colour number. Plain JSON; no pixi. */
532
+ interface ResolvedTheme {
533
+ readonly kind: ThemeKind;
534
+ /** Opaque family name (`'default'` | `'forest'` | …) — meaningful to the app, not the kernel. */
535
+ readonly name: string;
536
+ /** Role name → `0xRRGGBB`. The engine theme has no role *enum*; roles are strings. */
537
+ readonly palette: Readonly<Record<string, number>>;
538
+ /** Optional fill-by-category ramp (consumed by colour-by-label / minimap). */
539
+ readonly categorical?: readonly number[];
540
+ }
541
+ /** The theme channel — read the current resolved theme, or set (and broadcast) a new one. */
542
+ interface ThemeState {
543
+ /** The current resolved theme, or `null` before the first {@link set}. */
544
+ current(): ResolvedTheme | null;
545
+ /** Store + broadcast a resolved theme (emits `theme:change`). */
546
+ set(theme: ResolvedTheme): void;
547
+ }
548
+
549
+ /** Who emitted an event. */
550
+ type EventSourceKind = 'canvas' | 'layer' | 'behaviour' | 'layout' | 'store' | 'data';
551
+ /** The emitting instance — `kind` + its id. */
552
+ interface EventSource {
553
+ kind: EventSourceKind;
554
+ id: string;
555
+ }
556
+ /**
557
+ * A structured event envelope as seen on the **tap** channel: the type, a
558
+ * timestamp, the source instance, and the payload. One tap subscriber reading
559
+ * these reconstructs the whole loop (input → state change → render) for telemetry
560
+ * and collaboration.
561
+ */
562
+ interface CanvasEvent<P = unknown> {
563
+ type: string;
564
+ timestamp: number;
565
+ source: EventSource;
566
+ payload: P;
567
+ }
568
+ /** The default source for bus-level emits with no explicit origin. */
569
+ declare const CANVAS_SOURCE: EventSource;
570
+
571
+ /**
572
+ * The canvas-wide event map. Consumers (engine, domain) **augment** this via
573
+ * declaration merging — `declare module '@invana/canvas-core' { interface
574
+ * CanvasGlobalEvents { 'shape:click': … } }` — so new events are typed without
575
+ * touching the core.
576
+ */
577
+ interface CanvasGlobalEvents {
578
+ /**
579
+ * A `view`-store mutation, bridged onto the bus (see `createCanvasStore`).
580
+ * `durationMs` is the update's produce+commit wall-clock cost, when the store
581
+ * reports it — so a tap can attribute time without a separate telemetry sink.
582
+ */
583
+ 'state:change': {
584
+ action?: string;
585
+ changedPaths: string[];
586
+ durationMs?: number;
587
+ };
588
+ /** A `layer` data flush (nodes/edges/groups/annotations delta), bridged onto the bus. */
589
+ 'data:flush': {
590
+ layerId: string;
591
+ delta: LayerFlush;
592
+ };
593
+ /**
594
+ * One layer's coalesced **spec** changes — the visual description, ids only.
595
+ * Domain-free by construction: a renderer subscribes to this and never learns
596
+ * what a node or an edge is. See `docs/renderer-split-design.md` §4.2b.
597
+ */
598
+ 'specs:flush': {
599
+ layerId: string;
600
+ delta: SpecFlush;
601
+ };
602
+ /** A named data **intent** — one per data action (audit / collab), distinct from the per-frame flush. */
603
+ 'data:intent': {
604
+ action: string;
605
+ layerId: string;
606
+ ids: readonly string[];
607
+ };
608
+ 'scene:layer:add': {
609
+ id: string;
610
+ };
611
+ 'scene:layer:remove': {
612
+ id: string;
613
+ };
614
+ /**
615
+ * A layer's whole-layer `visible` flag changed via `Layer.setVisible`. Lets
616
+ * dependent layers (e.g. a `MiniMapLayer` mirroring a source graph) react
617
+ * without polling. `visible` is the post-change value.
618
+ */
619
+ 'scene:layer:visibilitychange': {
620
+ id: string;
621
+ visible: boolean;
622
+ };
623
+ 'scene:behaviour:register': {
624
+ id: string;
625
+ };
626
+ 'scene:behaviour:enable': {
627
+ id: string;
628
+ };
629
+ 'scene:behaviour:disable': {
630
+ id: string;
631
+ };
632
+ 'scene:layout:add': {
633
+ id: string;
634
+ };
635
+ 'scene:layout:remove': {
636
+ id: string;
637
+ };
638
+ 'input:node:click': {
639
+ layerId: string;
640
+ id: string;
641
+ x: number;
642
+ y: number;
643
+ };
644
+ 'input:node:hover': {
645
+ layerId: string;
646
+ id: string | null;
647
+ };
648
+ 'input:node:drag:start': {
649
+ layerId: string;
650
+ id: string;
651
+ };
652
+ 'input:node:drag:end': {
653
+ layerId: string;
654
+ id: string;
655
+ };
656
+ 'input:background:click': {
657
+ x: number;
658
+ y: number;
659
+ };
660
+ 'input:background:contextmenu': {
661
+ x: number;
662
+ y: number;
663
+ };
664
+ /**
665
+ * A pan **gesture** reported by the renderer (drag / keyboard / inertia) —
666
+ * gesture *intent*, distinct from the resulting `view.interaction.camera` change
667
+ * (a `state:change`). `x`/`y` are the world-origin offset the camera settled on.
668
+ */
669
+ 'input:camera:pan': {
670
+ x: number;
671
+ y: number;
672
+ };
673
+ /** A zoom **gesture** reported by the renderer (wheel / pinch). `scale` is the resolved uniform zoom; `center*` the screen pivot. */
674
+ 'input:camera:zoom': {
675
+ scale: number;
676
+ centerX: number;
677
+ centerY: number;
678
+ };
679
+ /** A layout run started. `nodeCount`/`edgeCount`/`animate` describe the run when the producer knows them. */
680
+ 'layout:run:start': {
681
+ id: string;
682
+ layerId: string;
683
+ nodeCount?: number;
684
+ edgeCount?: number;
685
+ animate?: boolean;
686
+ };
687
+ /** A layout run ended. `reason` distinguishes a natural settle from an external stop / abort. */
688
+ 'layout:run:end': {
689
+ id: string;
690
+ layerId: string;
691
+ reason?: 'settled' | 'stopped' | 'cancelled';
692
+ };
693
+ 'layout:run:tick': {
694
+ id: string;
695
+ progress?: number;
696
+ };
697
+ 'canvas:renderer:ready': {
698
+ backend: string;
699
+ capabilities?: Record<string, unknown>;
700
+ };
701
+ /**
702
+ * The active renderer crashed at **render time** and the engine has halted its
703
+ * render loop. Emitted once (experimental WebGPU only — see
704
+ * `CanvasOptions.preference`); the consumer should tear the canvas down and
705
+ * re-init on `to` (WebGL). `reason` is a short diagnostic tag.
706
+ */
707
+ 'canvas:renderer:fallback': {
708
+ from: string;
709
+ to: string;
710
+ reason?: string;
711
+ };
712
+ /**
713
+ * One measured engine frame — emitted once per `Canvas.tickOnce`. Carries the
714
+ * inter-frame period, per-phase CPU breakdown, and the attributed
715
+ * {@link InteractionKind}, so a tap can drive an FPS trace + attribute dips to
716
+ * the gesture that caused them. See {@link FrameTick}.
717
+ */
718
+ 'render:loop:tick': FrameTick;
719
+ /** The shared status-message channel. `text: null` clears; `timeout` (ms) auto-clears. */
720
+ 'canvas:message:show': {
721
+ text: string | null;
722
+ timeout?: number;
723
+ };
724
+ /** A tap dropped an event (filtered or sampled out) — diagnostic. */
725
+ 'tap:dropped': {
726
+ type: string;
727
+ reason: 'excluded' | 'sampled';
728
+ };
729
+ 'theme:change': ResolvedTheme;
730
+ }
731
+ /**
732
+ * The granular **`<domain>:<subject>:<action>`** types (`view:layer:setStyle`,
733
+ * `data:node:add`, …) are open-ended — emitted via {@link CanvasEventBus.publish}
734
+ * (they ride on the tap, keyed by the action label) rather than enumerated here.
735
+ * The map above types the **finite, engine-emitted** events for `on()`/`emit()`.
736
+ */
737
+ /** Per-tap filters. */
738
+ interface TapOptions {
739
+ /** Event `type`s to drop from this tap. */
740
+ exclude?: readonly string[];
741
+ /** Fraction (0..1) of events to forward — cheap sampling for costly sinks. */
742
+ sampleRate?: number;
743
+ }
744
+ /** A tap receives every emission as a structured {@link CanvasEvent}. */
745
+ type Tap = (event: CanvasEvent) => void;
746
+ /**
747
+ * Canvas-wide event bus: typed `on`/`emit` for known events, **plus a tap
748
+ * channel** that receives every emission (typed *and* forwarded scoped events) as
749
+ * a structured {@link CanvasEvent}. The tap is the single place telemetry /
750
+ * collaboration observe the whole stream — `bus.tap(e => sink(e))`.
751
+ *
752
+ * Renderer-free: the engine wires pixi pointer events *into* this; the bus knows
753
+ * nothing about pixi.
754
+ */
755
+ declare class CanvasEventBus {
756
+ private readonly emitter;
757
+ private readonly taps;
758
+ private readonly now;
759
+ private readonly rand;
760
+ constructor(opts?: {
761
+ now?: () => number;
762
+ random?: () => number;
763
+ });
764
+ /** Subscribe to a typed global event. Returns an unsubscribe fn (or use {@link off}). */
765
+ on<K extends keyof CanvasGlobalEvents>(type: K, listener: Listener<CanvasGlobalEvents[K]>): () => void;
766
+ /** Remove a previously-registered typed listener (the {@link on} handler by reference). */
767
+ off<K extends keyof CanvasGlobalEvents>(type: K, listener: Listener<CanvasGlobalEvents[K]>): void;
768
+ /** Emit a typed global event — reaches typed listeners and the tap channel. */
769
+ emit<K extends keyof CanvasGlobalEvents>(type: K, payload: CanvasGlobalEvents[K], source?: EventSource): void;
770
+ /**
771
+ * Forward a **scoped / foreign** event (not in {@link CanvasGlobalEvents}) to the
772
+ * tap channel only — used by {@link SourceEmitter} so a store/layer/behaviour's
773
+ * own events reach the canvas tap without being global-bus types.
774
+ */
775
+ publish(type: string, payload: unknown, source: EventSource): void;
776
+ private toTaps;
777
+ /** Subscribe to the whole event stream (structured envelopes). */
778
+ tap(fn: Tap, opts?: TapOptions): () => void;
779
+ clearTaps(): void;
780
+ removeAllListeners(): void;
781
+ }
782
+
783
+ /**
784
+ * The default {@link ThemeState} — holds the current {@link ResolvedTheme} and
785
+ * broadcasts `theme:change` on the bus whenever it is {@link set}. Renderer-free;
786
+ * a single publisher (the domain `ThemeBehaviour`) resolves authored config →
787
+ * `ResolvedTheme` and calls {@link set}. Theme-aware layers subscribe to
788
+ * `theme:change` (or read {@link current}) and recolour.
789
+ */
790
+ declare class CanvasThemeState implements ThemeState {
791
+ private readonly bus;
792
+ private _current;
793
+ constructor(bus: CanvasEventBus);
794
+ current(): ResolvedTheme | null;
795
+ set(theme: ResolvedTheme): void;
796
+ }
797
+
798
+ /**
799
+ * `DataSource` — the kernel's contract for a **bulk data store** owned by
800
+ * `CanvasStore.data[id]` (decision **D13**: *interface, not inheritance* — see
801
+ * `docs/canvas-store-d13-data-ownership.md`).
802
+ *
803
+ * The kernel owns sources behind this interface **without knowing their domain**:
804
+ * - the default {@link LayerData} satisfies it out of the box, and
805
+ * - a domain store (e.g. `@invana/graph`'s `GraphStore`) *implements* it and is
806
+ * registered via `CanvasStore.setSource(id, source)`.
807
+ *
808
+ * Only the three members the kernel needs to **own + bridge** a source live here;
809
+ * everything domain-specific (positions fast-path, adjacency, hierarchy, presence)
810
+ * stays off the interface. `CanvasStore` subscribes each source's {@link onFlush}
811
+ * and re-emits it as a coarse `data:flush` on the bus (telemetry / collab); the
812
+ * domain renderer subscribes to the source directly for targeted updates.
813
+ */
814
+ interface DataSource {
815
+ /** Subscribe to the coalesced per-frame change delta. Returns an unsubscribe. */
816
+ onFlush(listener: (delta: LayerFlush) => void): () => void;
817
+ /** Choose **when** the coalesced flush fires; the engine drives `'manual'`. */
818
+ setFlushMode(mode: FlushMode): void;
819
+ /** Drain pending changes now (the engine's single rAF loop calls this once/frame). */
820
+ flush(): void;
821
+ }
822
+
823
+ /**
824
+ * A single change operation — structurally identical to immer's `Patch`, but
825
+ * declared here so the port contract has **zero dependencies, even at the type
826
+ * level**. The store engine (`@invana/canvas-store`) produces immer patches;
827
+ * they satisfy this shape verbatim, and this shape satisfies immer's
828
+ * `applyPatches` input. Do not add fields immer doesn't emit.
829
+ */
830
+ interface Patch {
831
+ op: 'replace' | 'add' | 'remove';
832
+ path: (string | number)[];
833
+ value?: unknown;
834
+ }
835
+ /**
836
+ * The library-agnostic state contract. Consumers program against this — never
837
+ * against zustand (or, later, Yjs) directly — so the backend stays swappable.
838
+ *
839
+ * Two write forms, both declarative at the seam:
840
+ * - an **immer recipe** `(draft) => void` that reads like a direct mutation, or
841
+ * - a **deep-partial patch** object that is deep-merged in.
842
+ *
843
+ * Either way `update` produces immer **patches + inverse patches**, which is what
844
+ * lets telemetry, history/undo, and a future CRDT adapter all hang off the one seam.
845
+ */
846
+ interface ReactiveStore<T> {
847
+ /** Current state snapshot (structurally shared; treat as immutable). */
848
+ getState(): T;
849
+ /** Apply a recipe or a deep-partial patch, with an optional named action. */
850
+ update(update: Update<T>, action?: string): void;
851
+ /** Fires on every change with the new + previous state. */
852
+ subscribe(listener: (state: T, prev: T) => void): () => void;
853
+ /** Richer change stream (action + immer patches) — for telemetry / history. */
854
+ subscribeChanges(listener: (change: StoreChange<T>) => void): () => void;
855
+ /** Run `fn`'s writes as one coalesced change (one notification, one history step). */
856
+ batch(run: () => void, action?: string): void;
857
+ }
858
+ /** An immer recipe — mutate the draft; the produced state is structurally shared. */
859
+ type Recipe<T> = (draft: T) => void;
860
+ /** A write: either a recipe (mutate the draft) or a declarative deep-partial patch. */
861
+ type Update<T> = Recipe<T> | DeepPartial<T>;
862
+ /** What a change carries — the load-bearing payload for telemetry/history/CRDT. */
863
+ interface StoreChange<T> {
864
+ state: T;
865
+ prev: T;
866
+ action?: string;
867
+ /** immer forward patches (apply to `prev` → `state`). */
868
+ patches: Patch[];
869
+ /** immer inverse patches (apply to `state` → `prev` — i.e. undo). */
870
+ inverse: Patch[];
871
+ /** Wall-clock ms the update/batch took (produce + commit) — telemetry / tracing. */
872
+ durationMs?: number;
873
+ }
874
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined;
875
+ /**
876
+ * Deep-partial that **stops at** sets / maps / arrays / functions — those are
877
+ * replaced wholesale, matching the runtime deep-merge (and `CanvasConfig`'s
878
+ * shallow-replace semantics). So `{ interaction: { selection: newSet } }` swaps
879
+ * the set rather than trying to partial-merge its internals.
880
+ */
881
+ type DeepPartial<T> = T extends Primitive ? T : T extends ReadonlySet<unknown> ? T : T extends ReadonlyMap<unknown, unknown> ? T : T extends ReadonlyArray<unknown> ? T : T extends (...args: never[]) => unknown ? T : {
882
+ [K in keyof T]?: DeepPartial<T[K]>;
883
+ };
884
+ /**
885
+ * A minimal state cell an adapter supplies — the only thing that differs between
886
+ * backends. `createStoreFromCell` builds the full {@link ReactiveStore} on top, so
887
+ * the change/patch/batch logic is shared and identical across adapters.
888
+ */
889
+ interface StateCell<T> {
890
+ get(): T;
891
+ /** Replace state; must notify state listeners with (next, prev). */
892
+ set(next: T): void;
893
+ subscribe(listener: (state: T, prev: T) => void): () => void;
894
+ }
895
+
896
+ /**
897
+ * `CanvasView` — the reactive, observable, syncable half of `CanvasStore`: how a
898
+ * visualisation is **defined**, **viewed**, and its small transient **runtime**
899
+ * status. Small + human-rate → it lives on a {@link ReactiveStore}. Bulk data
900
+ * (nodes/edges/positions) is the **other** half (`CanvasStore.data`, typed-array,
901
+ * never reactive).
902
+ *
903
+ * Three compartments, three sync physics (see `docs/canvas-state-plan.md` §9):
904
+ * - **`definition`** — "what it IS": persisted, converges (a CRDT doc later).
905
+ * - **`interaction`** — "the live view": ephemeral / per-user (Awareness later).
906
+ * - **`runtime`** — small observable transient status (layout run, message):
907
+ * reactive so UIs can react, but **never synced**.
908
+ *
909
+ * Per-instance option bags are intentionally loose (`Record<string, unknown>`) at
910
+ * this layer — the engine and the schema-driven editors give them concrete shape,
911
+ * and the kernel stays domain-free (it treats element `style` as opaque).
912
+ */
913
+ interface CanvasView {
914
+ /** "What the visualisation IS" — persisted, converged (a CRDT doc later). */
915
+ definition: {
916
+ /** Canvas/scene-level config (background, zoom limits, world bounds, …). */
917
+ canvas: CanvasSceneOptions;
918
+ /** Layer options keyed by instance id (a rendering layer binds a data source). */
919
+ layers: Record<string, Record<string, unknown>>;
920
+ /** Behaviour options keyed by instance id. `enabled` is explicit (rule 7). */
921
+ behaviours: Record<string, Record<string, unknown>>;
922
+ /** Layout options keyed by instance id. */
923
+ layouts: Record<string, Record<string, unknown>>;
924
+ /** Id of the active layout among {@link layouts}, or `null`. */
925
+ activeLayout: string | null;
926
+ /** Authored node/edge templates (designer output). */
927
+ templates: unknown[];
928
+ /** Theme **config** (registry + active family + mode + accent). The *resolved* theme is derived. */
929
+ theme: Record<string, unknown>;
930
+ };
931
+ /** "The live view onto it" — mostly ephemeral / per-user (Awareness later). */
932
+ interaction: {
933
+ /** The semantic selection set (D11 — owned here, not in a behaviour). */
934
+ selection: ReadonlySet<string>;
935
+ /** Hovered element id, or `null`. */
936
+ hover: string | null;
937
+ /** Visual state sets (highlighted / context-open / …) keyed by state name (presence overlay). */
938
+ states: Record<string, ReadonlySet<string>>;
939
+ /**
940
+ * Elements lifted above their peers, keyed by the **source** that lifted
941
+ * them (a behaviour id) — so independent sources (hover, selection, …)
942
+ * never clobber each other's set, and each can be cleared on its own.
943
+ *
944
+ * The renderer projects the union of every source onto its own paint order
945
+ * and lowers anything absent from it. That single projection is what keeps
946
+ * the lift honest: a raise is *derived from state*, not a side effect, so
947
+ * it self-corrects when the state that motivated it changes (an element
948
+ * stops being hovered, a frame opens and becomes a backdrop, …). Before,
949
+ * each behaviour reparented display objects imperatively and tracked what
950
+ * it had touched privately — nothing could reconcile them, so a stale lift
951
+ * outranked the whole scene until that behaviour happened to run again.
952
+ *
953
+ * Ids only: the kernel stays domain-free. What an id *means* (a frame
954
+ * lifting its contents instead of itself, say) is the renderer's business.
955
+ */
956
+ raised: Record<string, ReadonlySet<string>>;
957
+ /** Abstract camera transform — renderer-agnostic; throttled/ephemeral. */
958
+ camera: CameraTransform$1;
959
+ /**
960
+ * Focal-emphasis: the highlight set + whether the rest is dimmed. O(1) to set;
961
+ * "muted" is a render-time derivation (`dim && !ids.has(id)`), not a per-node
962
+ * write (see `canvas-state-plan.md` §7.1B). `null` when no focus is active.
963
+ */
964
+ focus: {
965
+ ids: ReadonlySet<string>;
966
+ dim: boolean;
967
+ } | null;
968
+ /**
969
+ * Nodes transiently locked during a drag/resize gesture — held against the
970
+ * layout for the gesture's duration. **Distinct from data `pinned`** (the
971
+ * permanent, synced user flag); these are ephemeral and never synced.
972
+ */
973
+ transientPins: ReadonlySet<string>;
974
+ /** Active interaction mode. */
975
+ viewMode: string;
976
+ };
977
+ /** Small observable transient status — reactive (UIs react) but **never synced**. */
978
+ runtime: {
979
+ /** Layout run status — drives spinners / a stop control. */
980
+ layout: {
981
+ running: boolean;
982
+ /** The layout id currently executing, or `null`. */
983
+ activeId: string | null;
984
+ /** Whether the run animates its settle (force sim) vs jumps to final positions. */
985
+ animate: boolean;
986
+ /** 0..1 progress when known (force `alpha`); `null` for one-shot / unknown. */
987
+ progress: number | null;
988
+ };
989
+ /** Transient overlay/status message, or `null`. */
990
+ message: string | null;
991
+ };
992
+ }
993
+ /**
994
+ * Canvas/scene-level configuration — the settings that sit *above* individual
995
+ * layers/behaviours/layouts. Renderer-init options (`preference`, `antialias`,
996
+ * `resolution`, …) are deliberately **not** here: those belong to the renderer
997
+ * adapter, not the syncable definition.
998
+ */
999
+ interface CanvasSceneOptions {
1000
+ /** Scene background colour (`0xRRGGBB`). */
1001
+ backgroundColor?: number;
1002
+ /** Suppress the browser's native context menu over the canvas. */
1003
+ suppressBrowserContextMenu?: boolean;
1004
+ /** Zoom clamp for the abstract camera. */
1005
+ zoom: {
1006
+ min: number;
1007
+ max: number;
1008
+ };
1009
+ /** Initial camera transform applied on load. */
1010
+ initialCamera?: CameraTransform$1;
1011
+ /** Optional world/scene bounds (for fit-on-load / clamping), or `null`. */
1012
+ worldBounds?: Rect | null;
1013
+ /** Default interaction mode the view starts in. */
1014
+ defaultViewMode?: string;
1015
+ }
1016
+ /** The empty-but-valid initial {@link CanvasView}. */
1017
+ declare function defaultCanvasView(): CanvasView;
1018
+
1019
+ /** Loose option/patch bag for the view's per-instance config. */
1020
+ type Bag = Record<string, unknown>;
1021
+ /** Partial camera transform. */
1022
+ type CameraInput = Partial<{
1023
+ x: number;
1024
+ y: number;
1025
+ zoom: number;
1026
+ }>;
1027
+ /**
1028
+ * `createActions` — the **named, action-typed command API** over the kernel.
1029
+ *
1030
+ * Every mutation is a discoverable method (not a raw `view.update(recipe, …)`),
1031
+ * and each **bakes in its action label** (`'view:layer:setStyle'`, `'view:camera:zoom'`, …),
1032
+ * so telemetry, history, and the CRDT op-log all read as intent. View commands go
1033
+ * through the one `view.update(recipe, action)` seam; data commands proxy to the
1034
+ * target {@link LayerData}.
1035
+ *
1036
+ * Group by concern: `node / edge / group / annotation / positions` (data) and
1037
+ * `layers / behaviours / layouts / camera / selection / hover / templates / theme`
1038
+ * (view).
1039
+ *
1040
+ * ⚠ **Data actions target the default {@link LayerData} store only.** The
1041
+ * injected `layer(id)` accessor (see `createCanvasStore`) **throws** for any id
1042
+ * where a *custom* {@link DataSource} was registered via `setSource` — e.g.
1043
+ * `@invana/graph`'s `GraphStore`. For those, mutate through the domain store's
1044
+ * own API (`store.source(id)` / the layer's methods) instead. Unifying the data
1045
+ * actions over the `DataSource` interface is future work — audited and
1046
+ * deliberately deferred 2026-08-13 (the contract would need write methods it
1047
+ * doesn't carry today).
1048
+ */
1049
+ declare function createActions(view: ReactiveStore<CanvasView>, layer: (id: string) => LayerData, events: CanvasEventBus): {
1050
+ node: {
1051
+ add: (l: string, n: NodeRecord) => void;
1052
+ update: (l: string, id: string, patch: Partial<NodeRecord>) => void;
1053
+ remove: (l: string, id: string) => void;
1054
+ moveTo: (l: string, id: string, x: number, y: number) => void;
1055
+ };
1056
+ edge: {
1057
+ add: (l: string, e: EdgeRecord) => void;
1058
+ update: (l: string, id: string, patch: Partial<EdgeRecord>) => void;
1059
+ remove: (l: string, id: string) => void;
1060
+ };
1061
+ group: {
1062
+ add: (l: string, g: GroupRecord) => void;
1063
+ update: (l: string, id: string, patch: Partial<GroupRecord>) => void;
1064
+ remove: (l: string, id: string) => void;
1065
+ };
1066
+ annotation: {
1067
+ add: (l: string, a: AnnotationRecord) => void;
1068
+ update: (l: string, id: string, patch: Partial<AnnotationRecord>) => void;
1069
+ remove: (l: string, id: string) => void;
1070
+ };
1071
+ /** Bulk layout output → node positions (transform-only re-render). */
1072
+ positions: {
1073
+ apply: (l: string, positions: Iterable<{
1074
+ id: string;
1075
+ x: number;
1076
+ y: number;
1077
+ }>) => void;
1078
+ };
1079
+ layers: {
1080
+ add: (id: string, opts: Bag) => void;
1081
+ update: (id: string, patch: Bag) => void;
1082
+ setStyle: (id: string, style: Bag) => void;
1083
+ setVisible: (id: string, visible: boolean) => void;
1084
+ remove: (id: string) => void;
1085
+ };
1086
+ behaviours: {
1087
+ add: (id: string, opts: Bag) => void;
1088
+ update: (id: string, patch: Bag) => void;
1089
+ enable: (id: string) => void;
1090
+ disable: (id: string) => void;
1091
+ remove: (id: string) => void;
1092
+ };
1093
+ layouts: {
1094
+ set: (id: string, opts: Bag) => void;
1095
+ tune: (id: string, patch: Bag) => void;
1096
+ run: (id: string) => void;
1097
+ remove: (id: string) => void;
1098
+ };
1099
+ camera: {
1100
+ set: (c: CameraInput) => void;
1101
+ pan: (dx: number, dy: number) => void;
1102
+ zoom: (factor: number) => void;
1103
+ zoomTo: (zoom: number) => void;
1104
+ reset: () => void;
1105
+ };
1106
+ selection: {
1107
+ set: (ids: Iterable<string>) => void;
1108
+ add: (ids: Iterable<string>) => void;
1109
+ toggle: (id: string) => void;
1110
+ clear: () => void;
1111
+ };
1112
+ hover: {
1113
+ set: (id: string) => void;
1114
+ clear: () => void;
1115
+ };
1116
+ /**
1117
+ * Paint-order lift, per source. `source` is the id of whatever is asking
1118
+ * (a behaviour id) — each owns its own set, so a hover lift and a selection
1119
+ * lift coexist and either can be dropped without disturbing the other.
1120
+ * The renderer projects the union; see `CanvasView.interaction.raised`.
1121
+ */
1122
+ raise: {
1123
+ set: (source: string, ids: Iterable<string>) => void;
1124
+ clear: (source: string) => void;
1125
+ };
1126
+ templates: {
1127
+ create: (template: unknown) => void;
1128
+ update: (id: string, patch: Bag) => void;
1129
+ remove: (id: string) => void;
1130
+ };
1131
+ theme: {
1132
+ set: (patch: Bag) => void;
1133
+ };
1134
+ scene: {
1135
+ set: (patch: Partial<CanvasSceneOptions>) => void;
1136
+ setBackground: (backgroundColor: number) => void;
1137
+ setZoomLimits: (min: number, max: number) => void;
1138
+ };
1139
+ layoutStatus: {
1140
+ begin: (id: string, animate?: boolean) => void;
1141
+ progress: (progress: number) => void;
1142
+ end: () => void;
1143
+ };
1144
+ message: {
1145
+ show: (text: string) => void;
1146
+ clear: () => void;
1147
+ };
1148
+ focus: {
1149
+ set: (ids: Iterable<string>, dim?: boolean) => void;
1150
+ clear: () => void;
1151
+ };
1152
+ transientPins: {
1153
+ add: (ids: Iterable<string>) => void;
1154
+ remove: (ids: Iterable<string>) => void;
1155
+ clear: () => void;
1156
+ };
1157
+ };
1158
+ /** The named, action-typed command API (see {@link createActions}). */
1159
+ type CanvasActions = ReturnType<typeof createActions>;
1160
+
1161
+ /**
1162
+ * `CanvasStore` — the **contract** of the renderer-free store, one per `Canvas`.
1163
+ * The single hub the engine writes to *and* subscribes from:
1164
+ *
1165
+ * - {@link CanvasStore.view} — reactive `ReactiveStore<CanvasView>` (config + interaction state).
1166
+ * - {@link CanvasStore.data} — owned, keyed `LayerData` stores (the bulk graph).
1167
+ * - {@link CanvasStore.events} — the canvas-wide `CanvasEventBus` (tap channel for
1168
+ * telemetry / collaboration).
1169
+ *
1170
+ * The **implementation** (`createCanvasStore` — the zustand/immer-backed factory,
1171
+ * the state↔bus bridges, telemetry wiring) lives in `@invana/canvas-store`; this
1172
+ * package holds only the shape, so contracts and abstracts (`CanvasContext`,
1173
+ * `Camera`) can type against the store without depending on the machinery.
1174
+ */
1175
+
1176
+ interface CanvasStore {
1177
+ /** Reactive config + interaction store (layers/behaviours/layouts settings, interaction). */
1178
+ readonly view: ReactiveStore<CanvasView>;
1179
+ /** Owned data, keyed by **source** id (D13 — each a {@link DataSource}). */
1180
+ readonly data: Record<string, DataSource>;
1181
+ /**
1182
+ * Owned **spec** collections, keyed by layer id — the durable visual
1183
+ * description each renderer projects. Populated via {@link specsFor}.
1184
+ */
1185
+ readonly specs: Record<string, SpecStore>;
1186
+ /** Canvas-wide event bus + tap channel (state:change + data:flush). */
1187
+ readonly events: CanvasEventBus;
1188
+ /** Resolved-theme channel (`theme.current()` / `theme.set(...)` → `theme:change`). */
1189
+ readonly theme: CanvasThemeState;
1190
+ /**
1191
+ * Register a domain {@link DataSource} under `id` (D13) — e.g. `@invana/graph`'s
1192
+ * `GraphStore`. Its {@link DataSource.onFlush} is bridged onto {@link events} as
1193
+ * `data:flush`. Replaces any source previously registered (or lazily created) for `id`.
1194
+ */
1195
+ setSource(id: string, source: DataSource): void;
1196
+ /** The {@link DataSource} registered for `id`, or `undefined`. */
1197
+ source(id: string): DataSource | undefined;
1198
+ /**
1199
+ * Get (lazily creating) the **default** {@link LayerData} for `id`; its flush is
1200
+ * bridged onto {@link events}. Throws if a non-`LayerData` source was registered
1201
+ * for `id` via {@link setSource} — use {@link source} / {@link data} for those.
1202
+ */
1203
+ layer(id: string): LayerData;
1204
+ /**
1205
+ * Get (lazily creating) the {@link SpecStore} for layer `id`; its flush is
1206
+ * bridged onto {@link events} as `specs:flush`.
1207
+ */
1208
+ specsFor<T extends object = object>(id: string): SpecStore<T>;
1209
+ /** Named, action-typed command API (`actions.layers.setStyle`, `actions.camera.zoom`, …). */
1210
+ readonly actions: CanvasActions;
1211
+ }
1212
+
1213
+ /**
1214
+ * `ICameraBinding` — the renderer's half of the camera.
1215
+ *
1216
+ * {@link Camera} is the engine's pan/zoom facade: it owns the semantics
1217
+ * (clamping, anchored zoom, fit-to-rect, bus events, store sync) and holds no
1218
+ * backend type. The *concrete* viewport — a `pixi-viewport` `Viewport` today, an
1219
+ * orthographic three.js camera later — sits behind this interface.
1220
+ *
1221
+ * Everything here is expressed in engine vocabulary: an abstract
1222
+ * `{ x, y, zoom }` transform, screen↔world projection, and **semantic** input
1223
+ * config (`percent`, `modifier`) rather than a plugin registry. The mapping from
1224
+ * `modifier` to physical key codes, and from an input to whatever the backend
1225
+ * calls its pan/zoom machinery, belongs to the implementation
1226
+ * (`docs/renderer-split-design.md` §5, P6).
1227
+ *
1228
+ * The split is what lets `Camera` be tested with no GPU, and what lets P6 move
1229
+ * the pixi realisation into `@invana/renderer-pixijs` without touching a single
1230
+ * camera-input behaviour.
1231
+ */
1232
+
1233
+ /** An absolute transform: world (0,0) sits at `(x, y)` screen px, uniform `zoom`. */
1234
+ interface CameraTransformValue {
1235
+ x: number;
1236
+ y: number;
1237
+ zoom: number;
1238
+ }
1239
+ /**
1240
+ * A modifier key an input gesture can be gated on. Semantic on purpose — the
1241
+ * binding maps these to whatever key codes its backend wants.
1242
+ *
1243
+ * `space` is a held key rather than a true modifier, but it gates drag-pan the
1244
+ * same way (Figma / Sketch style), so it rides the same vocabulary.
1245
+ */
1246
+ type CameraInputModifier = 'control' | 'shift' | 'alt' | 'meta' | 'space';
1247
+ /** Drag-pan input configuration. */
1248
+ interface DragInputOptions {
1249
+ /** Which mouse buttons drag the canvas. Default `'left'`. */
1250
+ mouseButtons?: 'all' | 'left' | 'right' | 'middle';
1251
+ /**
1252
+ * Require this key to be held for a drag to pan, leaving plain drag to other
1253
+ * gestures (lasso, brush, …). `null` / omitted = no modifier.
1254
+ */
1255
+ modifier?: CameraInputModifier | null;
1256
+ /** Momentum glide after the pointer lifts. Default `true`. */
1257
+ decelerate?: boolean;
1258
+ }
1259
+ /** Wheel-zoom input configuration. */
1260
+ interface WheelInputOptions {
1261
+ /** Zoom fraction per wheel tick. Default `0.1` (10%). */
1262
+ percent?: number;
1263
+ /** Smooth-scroll frame count; `false` = instant snap. Default `false`. */
1264
+ smooth?: false | number;
1265
+ /**
1266
+ * Require this modifier to be held for the wheel to zoom, leaving plain
1267
+ * scroll to the page. `null` / omitted = no modifier.
1268
+ */
1269
+ modifier?: CameraInputModifier | null;
1270
+ /** Treat a two-finger trackpad pinch as zoom rather than scroll. Default `true`. */
1271
+ trackpadPinch?: boolean;
1272
+ }
1273
+ /** Pinch-zoom input configuration. */
1274
+ interface PinchInputOptions {
1275
+ /** Suppress the implicit pan that accompanies a pinch. Default `false`. */
1276
+ noDrag?: boolean;
1277
+ /** Zoom speed multiplier. Default `0.1`. */
1278
+ percent?: number;
1279
+ }
1280
+ /**
1281
+ * Patch for camera input. An omitted key leaves that input untouched; `null`
1282
+ * removes it.
1283
+ */
1284
+ interface CameraInputConfig {
1285
+ wheel?: WheelInputOptions | null;
1286
+ pinch?: PinchInputOptions | null;
1287
+ drag?: DragInputOptions | null;
1288
+ }
1289
+ /** What moved, when a binding reports a backend-driven transform change. */
1290
+ type CameraChangeKind = 'pan' | 'zoom';
1291
+ interface ICameraBinding {
1292
+ /** The current transform, read straight from the backend viewport. */
1293
+ getTransform(): CameraTransformValue;
1294
+ /**
1295
+ * Write the transform verbatim — no clamping, no re-anchoring. `Camera` has
1296
+ * already applied its own semantics; this is the raw write.
1297
+ *
1298
+ * Must **not** re-report through {@link onTransformChange}: `Camera` knows it
1299
+ * made this change and emits its own events, so an echo would double-fire.
1300
+ */
1301
+ setTransform(t: CameraTransformValue): void;
1302
+ /**
1303
+ * Zoom about the viewport centre, keeping the centre world point fixed. Split
1304
+ * out from {@link setTransform} because backends implement centre-anchored
1305
+ * zoom themselves and their arithmetic is what users' muscle memory expects.
1306
+ */
1307
+ zoomToCentre(zoom: number): void;
1308
+ /** Viewport size changed (CSS px). */
1309
+ resize(screenWidth: number, screenHeight: number): void;
1310
+ toWorld(screenX: number, screenY: number): Point;
1311
+ toScreen(worldX: number, worldY: number): Point;
1312
+ /** The world-space rectangle currently visible. */
1313
+ getVisibleBounds(): Rect;
1314
+ /**
1315
+ * Install / replace / remove the backend's own pan and zoom inputs. Patch
1316
+ * semantics: an omitted key is untouched, `null` removes that input.
1317
+ */
1318
+ configureInput(config: CameraInputConfig): void;
1319
+ /**
1320
+ * Suspend or restore drag-panning without tearing it down — how gesture
1321
+ * arbitration yields the camera. Momentum is deliberately left running so an
1322
+ * in-flight glide finishes.
1323
+ */
1324
+ setDragSuspended(suspended: boolean): void;
1325
+ /**
1326
+ * Subscribe to transform changes the **backend** made on its own — a wheel
1327
+ * tick, a drag, a momentum glide. Changes `Camera` initiates never arrive
1328
+ * here. Returns an unsubscribe function.
1329
+ */
1330
+ onTransformChange(fn: (kind: CameraChangeKind) => void): () => void;
1331
+ /**
1332
+ * Subscribe to the start of a drag-pan, fired once the pointer has moved
1333
+ * enough to pan. Returns an unsubscribe function.
1334
+ */
1335
+ onDragStart(fn: () => void): () => void;
1336
+ /** Advance time-based input animation (momentum, snap). Driven by the engine's clock. */
1337
+ tick(dtMs: number): void;
1338
+ }
1339
+
1340
+ /**
1341
+ * `Camera` — the engine's pan/zoom/projection facade.
1342
+ *
1343
+ * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.camera) and
1344
+ * §2.6 (camera input is a Behaviour, not a hard-coded gesture).
1345
+ *
1346
+ * **Design notes**
1347
+ *
1348
+ * - **No backend type crosses this class.** The concrete viewport lives behind
1349
+ * {@link ICameraBinding} — `PixiViewportBinding` today, an orthographic
1350
+ * three.js camera later. Camera owns the *semantics* (clamping, anchored zoom,
1351
+ * fit-to-rect, bus events, store sync); the binding owns the realisation
1352
+ * (`docs/renderer-split-design.md` §9, P5/P6).
1353
+ * - The Camera owns no input gestures — those live in opt-in camera-input
1354
+ * `Behaviour`s (proposal §2.6). They configure inputs through
1355
+ * {@link Camera.configureInput} / {@link Camera.setDragSuspended} /
1356
+ * {@link Camera.onDragStart}, described semantically (`percent`, `modifier`),
1357
+ * so a behaviour never names a plugin.
1358
+ * - The **binding is the single source of truth** for the transform: Camera
1359
+ * reads it back rather than caching, so a gesture driven inside the backend
1360
+ * and a programmatic `pan()` can't drift apart.
1361
+ * - Coordinate model (uniform scale, no rotation):
1362
+ *
1363
+ * screen.x = world.x * scale + tx
1364
+ * screen.y = world.y * scale + ty
1365
+ * world.x = (screen.x - tx) / scale
1366
+ * world.y = (screen.y - ty) / scale
1367
+ *
1368
+ * We deliberately keep `scale.x === scale.y` (no anisotropic zoom) and no
1369
+ * rotation. Both are enforceable as needed.
1370
+ *
1371
+ * - Events are emitted on the canvas-wide `CanvasEventBus`:
1372
+ * `camera:zoom`, `camera:pan`. They flow through the tap channel so
1373
+ * telemetry sees every camera change.
1374
+ */
1375
+
1376
+ /** An absolute camera transform — world (0,0) at `(x, y)` screen px, uniform `zoom`. */
1377
+ type CameraTransform = CameraTransformValue;
1378
+ interface CameraOptions {
1379
+ /**
1380
+ * The renderer's viewport, behind the pixi-free {@link ICameraBinding} seam.
1381
+ * Created by the renderer (`Canvas` wires `PixiViewportBinding` today).
1382
+ */
1383
+ binding: ICameraBinding;
1384
+ /** Initial viewport size in CSS pixels. Mirrors the binding's own screen size for projection math. */
1385
+ screenWidth: number;
1386
+ screenHeight: number;
1387
+ /** Optional bus for `input:camera:zoom` / `input:camera:pan` events. */
1388
+ bus?: CanvasEventBus;
1389
+ /**
1390
+ * Optional kernel store. When present, the camera keeps
1391
+ * `store.view.interaction.camera` (the abstract `{x,y,zoom}` transform) in sync
1392
+ * with the binding **both ways** — gestures/mutators push into the store,
1393
+ * and external `actions.camera.*` writes apply to the binding.
1394
+ */
1395
+ store?: CanvasStore;
1396
+ /** Initial uniform scale. Default 1. */
1397
+ initialScale?: number;
1398
+ /** Initial world-container offset (= where world (0,0) lives in screen pixels). Default (0,0). */
1399
+ initialX?: number;
1400
+ initialY?: number;
1401
+ /** Min / max zoom clamp. Defaults: 0.01 .. 100. */
1402
+ minScale?: number;
1403
+ maxScale?: number;
1404
+ }
1405
+ declare class Camera {
1406
+ /**
1407
+ * The renderer's viewport, behind the pixi-free binding seam. **Private** —
1408
+ * nothing outside this class reaches the backend, which is what lets P6 move
1409
+ * the realisation into `@invana/renderer-pixijs` without a public break.
1410
+ */
1411
+ private readonly binding;
1412
+ private readonly bus?;
1413
+ private _screenWidth;
1414
+ private _screenHeight;
1415
+ private readonly _minScale;
1416
+ private readonly _maxScale;
1417
+ /** Kernel store (optional) — the home of the abstract `interaction.camera` transform. */
1418
+ private readonly store?;
1419
+ /** Re-entrancy guard so binding↔store sync never ping-pongs. */
1420
+ private _syncing;
1421
+ /** Unsubscribe for the `interaction.camera` slice subscription. */
1422
+ private _offStoreCam?;
1423
+ /** Unsubscribe for the binding's backend-driven transform reports. */
1424
+ private _offBindingChange?;
1425
+ /** Whether drag-panning is currently yielded to another gesture owner. */
1426
+ private _dragSuspended;
1427
+ constructor(opts: CameraOptions);
1428
+ /**
1429
+ * Push the current transform into `store.view.interaction.camera`. Called from
1430
+ * every camera mutation (gesture + programmatic). No-op when the store already
1431
+ * matches or a store→binding apply is in flight.
1432
+ */
1433
+ private pushToStore;
1434
+ /**
1435
+ * Apply `store.view.interaction.camera` onto the binding — realises an external
1436
+ * `actions.camera.*` write. No-op when the binding already matches or a
1437
+ * binding→store push is in flight.
1438
+ */
1439
+ private applyFromStore;
1440
+ /** Current uniform scale. */
1441
+ get scale(): number;
1442
+ /** Current world-container x in screen pixels. (Where world (0,0) sits.) */
1443
+ get x(): number;
1444
+ get y(): number;
1445
+ get screenWidth(): number;
1446
+ get screenHeight(): number;
1447
+ /**
1448
+ * Set absolute world-container offset. `(x, y)` is where world (0,0) lives
1449
+ * in screen pixels. Most consumers want `pan(dx, dy)` instead.
1450
+ */
1451
+ setPosition(x: number, y: number): void;
1452
+ /** Pan by `(dx, dy)` screen pixels. */
1453
+ pan(dx: number, dy: number): void;
1454
+ /**
1455
+ * Write an absolute `{ x, y, zoom }` transform in one step — the seam for a
1456
+ * layer mirroring an **external** camera authority (a MapLibre basemap, a
1457
+ * remote collaborator's viewport, a replayed session).
1458
+ *
1459
+ * Unlike `setZoom` + `setPosition`, this re-anchors nothing: the transform
1460
+ * lands exactly as given, because the external authority has already solved
1461
+ * for it and any re-anchoring here would desync the two views. `zoom` is
1462
+ * emitted only when it actually changed — most mirrored gestures are pan-only
1463
+ * and the `input:camera:zoom` listeners are O(N) over their tracked elements.
1464
+ *
1465
+ * @param t The transform to apply.
1466
+ * @param opts.clamp Apply the camera's min/max zoom clamp. Default `true`.
1467
+ * Pass `false` when mirroring an authority with its own scale range — a web
1468
+ * mercator basemap runs to `2 ** 22`, far past the camera's default ceiling
1469
+ * of 100, and clamping would silently peg the canvas away from the map.
1470
+ */
1471
+ setTransform(t: CameraTransform, opts?: {
1472
+ clamp?: boolean;
1473
+ }): void;
1474
+ /**
1475
+ * Set absolute scale, anchored at the viewport centre. The world point at
1476
+ * the centre stays put. For zoom-around-an-arbitrary-point semantics use
1477
+ * `zoomAt`.
1478
+ */
1479
+ setZoom(scale: number): void;
1480
+ /**
1481
+ * Multiply scale by `factor`, holding the world point under the screen
1482
+ * cursor `(centerX, centerY)` in place. Default centre = viewport centre.
1483
+ *
1484
+ * Bindings offer only centre-anchored zoom, so the arbitrary-anchor math is
1485
+ * done here: project the anchor to world, change scale, then translate so the
1486
+ * same world point lands at the same screen point.
1487
+ */
1488
+ zoomAt(factor: number, centerX?: number, centerY?: number): void;
1489
+ /**
1490
+ * Fit a world-space rectangle into the viewport. Scales so the whole rect
1491
+ * is visible (limited by the smaller axis), centres it. `padding` is in
1492
+ * screen pixels around the rect.
1493
+ */
1494
+ fitContent(worldRect: Rect | null | undefined, padding?: number): void;
1495
+ /**
1496
+ * Centre the viewport on a world-space point — pan so `(worldX, worldY)`
1497
+ * maps to the screen centre, keeping the current zoom. The pan-only
1498
+ * counterpart to {@link fitContent}: use it for "focus" / "go to" actions
1499
+ * that should locate a target without rescaling the view.
1500
+ */
1501
+ centerOn(worldX: number, worldY: number): void;
1502
+ /** Update on viewport resize. Forwarded so the binding's own math stays correct. */
1503
+ resize(screenWidth: number, screenHeight: number): void;
1504
+ /** Screen → world. */
1505
+ toWorld(screenX: number, screenY: number): Point;
1506
+ /** World → screen. */
1507
+ toScreen(worldX: number, worldY: number): Point;
1508
+ /**
1509
+ * The world-space rectangle currently visible. Used by viewport culling
1510
+ * (per `decorations-plan.md` §11.6) and minimap layers.
1511
+ */
1512
+ getVisibleBounds(): Rect;
1513
+ /**
1514
+ * Configure the camera's own pan / zoom inputs. This is the seam camera-input
1515
+ * behaviours use instead of naming a backend plugin: the options are described
1516
+ * semantically (`percent`, `modifier`) and the realisation lives in the
1517
+ * binding, so `DragPanBehaviour` / `WheelZoomBehaviour` / `PinchZoomBehaviour`
1518
+ * survive the renderer swap unchanged.
1519
+ *
1520
+ * Patch semantics — an omitted key is left alone, `null` removes that input:
1521
+ *
1522
+ * ```ts
1523
+ * camera.configureInput({ wheel: { percent: 0.2, modifier: 'control' } });
1524
+ * camera.configureInput({ wheel: null }); // wheel zoom off, pinch untouched
1525
+ * ```
1526
+ *
1527
+ * Re-configuring an already-installed input replaces it, because the
1528
+ * underlying inputs read their config only at install time.
1529
+ */
1530
+ configureInput(config: CameraInputConfig): void;
1531
+ /**
1532
+ * Suspend / restore drag-panning without tearing the input down. This is how
1533
+ * gesture arbitration yields the camera: while another behaviour owns the
1534
+ * pointer (a node drag, a lasso, a resize) panning is suspended, and it
1535
+ * resumes when that gesture releases.
1536
+ *
1537
+ * Momentum is deliberately left running, so an in-flight glide finishes as it
1538
+ * always has. Edge-triggered — restoring resets the underlying input, so a
1539
+ * repeated call in the same state is a no-op.
1540
+ */
1541
+ setDragSuspended(suspended: boolean): void;
1542
+ /**
1543
+ * Subscribe to the start of a drag-pan gesture — fired once the pointer has
1544
+ * actually moved enough to pan. `DragPanBehaviour` uses it as the cursor
1545
+ * fallback for the `space` modifier, which can't be read off a pointer event.
1546
+ *
1547
+ * @returns an unsubscribe function.
1548
+ */
1549
+ onDragStart(fn: () => void): () => void;
1550
+ /**
1551
+ * Advance time-based input animation (momentum, snap). Called by
1552
+ * `Canvas.tickOnce()` every frame — the engine owns the only clock (G3).
1553
+ * No-op until a camera-input behaviour enables an input that animates.
1554
+ */
1555
+ tick(dt: number): void;
1556
+ /** Tear down subscriptions. Called by `Canvas.destroy`. */
1557
+ dispose(): void;
1558
+ private clampScale;
1559
+ }
1560
+
1561
+ /**
1562
+ * `IOverlayDevice` — immediate-mode drawing for **transient** visuals only.
1563
+ *
1564
+ * A lasso polygon, a brush rectangle, a drag ghost, a minimap viewport
1565
+ * rectangle: things that change at pointer or camera rate, mean nothing once the
1566
+ * gesture ends, and must never reach history, undo, serialisation or export.
1567
+ * Publishing those as specs would put gesture noise into state and force every
1568
+ * writer to remember an exclusion flag — so they get their own path instead
1569
+ * (`docs/renderer-split-design.md` §3, decision D3).
1570
+ *
1571
+ * **Not for layer content.** Anything durable — nodes, edges, group frames,
1572
+ * contour bands, hulls — is a spec in the store, projected by `SpecProjector`.
1573
+ * If a visual survives a reload, it does not belong here.
1574
+ *
1575
+ * The vocabulary is deliberately the eleven operations the transient visuals in
1576
+ * this repo actually use. Every one maps to a `Graphics` path op in pixi and to
1577
+ * `BufferGeometry` in three.js, which is what keeps the device portable.
1578
+ */
1579
+ /** Solid fill. Overlays never need image or inset fills. */
1580
+ interface OverlayFill {
1581
+ readonly color: number | string;
1582
+ readonly alpha?: number;
1583
+ }
1584
+ /**
1585
+ * A bare colour is accepted wherever a fill is, since an opaque solid is the
1586
+ * common case — `fill(0x1677ff)` rather than `fill({ color: 0x1677ff })`.
1587
+ */
1588
+ type OverlayFillLike = OverlayFill | number | string;
1589
+ /** Solid stroke, optionally dashed. */
1590
+ interface OverlayStroke {
1591
+ readonly color: number;
1592
+ readonly width: number;
1593
+ readonly alpha?: number;
1594
+ /** `[dash, gap]` in world units. Omit for a solid line. */
1595
+ readonly dashArray?: readonly [number, number];
1596
+ }
1597
+ interface IOverlayDevice {
1598
+ /** Erase everything drawn so far. Every redraw starts here. */
1599
+ clear(): this;
1600
+ moveTo(x: number, y: number): this;
1601
+ lineTo(x: number, y: number): this;
1602
+ quadraticCurveTo(cx: number, cy: number, x: number, y: number): this;
1603
+ closePath(): this;
1604
+ rect(x: number, y: number, width: number, height: number): this;
1605
+ roundRect(x: number, y: number, width: number, height: number, radius: number): this;
1606
+ ellipse(cx: number, cy: number, radiusX: number, radiusY: number): this;
1607
+ /** Flat `[x0, y0, x1, y1, …]` or point objects. */
1608
+ poly(points: readonly number[] | ReadonlyArray<{
1609
+ x: number;
1610
+ y: number;
1611
+ }>, close?: boolean): this;
1612
+ fill(style: OverlayFillLike): this;
1613
+ stroke(style: OverlayStroke): this;
1614
+ /** Hide without discarding — cheaper than clear + redraw for a blinking overlay. */
1615
+ setVisible(visible: boolean): this;
1616
+ /** Paint order against sibling overlays. */
1617
+ setZIndex(z: number): this;
1618
+ /** Move the whole overlay; useful for screen-space chrome. */
1619
+ setPosition(x: number, y: number): this;
1620
+ destroy(): void;
1621
+ }
1622
+ /** Which space an overlay is drawn in. */
1623
+ type OverlaySpace = 'world' | 'screen';
1624
+
1625
+ /**
1626
+ * `SpecProjector` — drives a renderer from a {@link SpecStore}.
1627
+ *
1628
+ * The store holds the visual description; this turns it into mounted elements.
1629
+ * Every drawing layer uses the same projector, which is what makes "the renderer
1630
+ * is a projection of state" true for the whole engine rather than for one layer.
1631
+ *
1632
+ * Two entry points, and the difference matters:
1633
+ *
1634
+ * - {@link project} — synchronous, for a layer publishing its own spec. Anything
1635
+ * the layer does *after* publishing (attaching a label, a decoration, a badge)
1636
+ * needs the element mounted already, so this path cannot wait for a flush.
1637
+ * - the **flush subscription** — for every other writer: a behaviour, a tool, a
1638
+ * restored session. Ids already projected synchronously in the same frame are
1639
+ * skipped so nothing is drawn twice.
1640
+ *
1641
+ * Shapes and connectors are told apart by **which registry owns the spec's
1642
+ * `kind`**, so no discriminator has to be baked into the spec vocabulary.
1643
+ *
1644
+ * See `docs/renderer-split-design.md` §2 and §4.2b.
1645
+ */
1646
+
1647
+ /** The slice of a renderer this projector drives. */
1648
+ interface SpecProjectionTarget {
1649
+ readonly shapeKinds: ReadonlySet<string>;
1650
+ getShapeKind(id: string): string | undefined;
1651
+ hasConnector(id: string): boolean;
1652
+ addShape<TSpec extends BaseShapeSpec>(id: string, spec: TSpec): void;
1653
+ updateShape<TSpec extends BaseShapeSpec>(id: string, patch: Partial<TSpec>): void;
1654
+ removeShape(id: string): void;
1655
+ addConnector<TSpec extends BaseConnectorSpec>(id: string, spec: TSpec): void;
1656
+ updateConnector<TSpec extends BaseConnectorSpec>(id: string, patch: Partial<TSpec>): void;
1657
+ removeConnector(id: string): void;
1658
+ }
1659
+ interface SpecProjectorOptions {
1660
+ /**
1661
+ * Called before an element is removed and re-added because its `kind` changed.
1662
+ * A host may be tracking decoration / badge slots that the removal disposes.
1663
+ */
1664
+ onKindChange?: (id: string) => void;
1665
+ }
1666
+ declare class SpecProjector<TSpec extends BaseShapeSpec | BaseConnectorSpec> {
1667
+ private readonly specs;
1668
+ private readonly target;
1669
+ private readonly options;
1670
+ private readonly projectedThisFlush;
1671
+ private readonly off;
1672
+ constructor(specs: SpecStore<TSpec>, target: SpecProjectionTarget, options?: SpecProjectorOptions);
1673
+ /**
1674
+ * Mount / update `id` from the store **now**, and mark it handled so the next
1675
+ * flush skips it.
1676
+ */
1677
+ project(id: string): void;
1678
+ /** Remove whatever the renderer holds for `id`, whichever kind it is. */
1679
+ unproject(id: string): void;
1680
+ /** Drop the flush subscription. */
1681
+ destroy(): void;
1682
+ private applyFlush;
1683
+ private apply;
1684
+ }
1685
+
1686
+ /**
1687
+ * `IElementRenderer` — everything a domain layer asks of a drawing backend.
1688
+ *
1689
+ * `SpecProjectionTarget` covers the part driven by state: add / update / remove
1690
+ * an element from `specs:flush`. This interface is the rest — the per-frame
1691
+ * commands and geometry answers a layer still calls directly (decorations,
1692
+ * badges, LOD, transforms, measurement). It exists so `@invana/graph` can drive
1693
+ * a backend it does not import.
1694
+ *
1695
+ * **Every signature here is pixi-free**, which is the whole point and was not a
1696
+ * given: it works because the decoration styles, badge options and label
1697
+ * content moved into the spec vocabulary earlier (P6.0), and because
1698
+ * `IDecorationBase` is generic over its host info rather than naming a display
1699
+ * object. A signature that cannot be expressed without a backend type belongs
1700
+ * on the concrete renderer, not here.
1701
+ *
1702
+ * **This is not the end state.** The classification table in
1703
+ * `docs/renderer-split-design.md` (P4.5) records where each of these is headed:
1704
+ * the three `setShape*Visible` calls collapse into `setLODLevel` (G5), and
1705
+ * decorations and badges become spec state. Until then the interface describes
1706
+ * what is really called, rather than what we wish were called — a smaller
1707
+ * interface that lied would not let the package split at all.
1708
+ */
1709
+
1710
+ /**
1711
+ * A mounted decoration, seen from the engine side. Generic in its host info, so
1712
+ * this reference carries no backend type — a layer can hold one, tick it and
1713
+ * read its padding without knowing what it draws into.
1714
+ */
1715
+ interface MountedDecoration<TStyle = unknown> {
1716
+ readonly style: TStyle;
1717
+ tick?(deltaMs: number): boolean;
1718
+ getEndPadding?(): {
1719
+ readonly source: number;
1720
+ readonly target: number;
1721
+ };
1722
+ getOuterExtent?(): number;
1723
+ }
1724
+ /**
1725
+ * A custom element class, seen from the engine side.
1726
+ *
1727
+ * Registering a new shape kind is **irreducibly backend-specific**: a pixi
1728
+ * implementation extends `ShapeBase` and paints into a `Graphics`, a three.js
1729
+ * one would extend something else entirely. So the engine types the constructor
1730
+ * opaquely — it only routes the registration through to the backend, which is
1731
+ * the thing that can give it meaning.
1732
+ */
1733
+ type CustomElementCtor = abstract new (...args: never[]) => object;
1734
+ interface IElementRenderer extends SpecProjectionTarget {
1735
+ /**
1736
+ * Teach this backend a new element kind. The spec vocabulary stays open —
1737
+ * `containsSpec` / `boundsOfSpec` return `undefined` for kinds they don't
1738
+ * know, and picking falls back to asking the instance.
1739
+ */
1740
+ registerShape(kind: string, ctor: CustomElementCtor): void;
1741
+ hasShape(id: string): boolean;
1742
+ getShapeKind(id: string): string | undefined;
1743
+ hasConnector(id: string): boolean;
1744
+ moveShape(id: string, x: number, y: number): void;
1745
+ scaleShape(id: string, scale: number): void;
1746
+ setConnectorStroke(id: string, stroke: {
1747
+ color: number;
1748
+ width: number;
1749
+ }): void;
1750
+ scaleConnectorStroke(id: string, scale: number): void;
1751
+ setRaised(ids: Iterable<string>): void;
1752
+ setShapeTextVisible(id: string, visible: boolean): void;
1753
+ setShapeIconVisible(id: string, visible: boolean): void;
1754
+ setShapeImageVisible(id: string, visible: boolean): void;
1755
+ setLabelsResolution(resolution: number): void;
1756
+ setVisibleSet(ids: ReadonlySet<string> | null): void;
1757
+ cull(visibleBounds: Rect, padWorld?: number): void;
1758
+ uncull(): void;
1759
+ setDecoration<TStyle = unknown>(targetId: string, slot: string, decoration: DecorationSpec<TStyle> | null): void;
1760
+ getDecoration(id: string, slot: string): MountedDecoration | undefined;
1761
+ setDecorationVisible(targetId: string, slot: string, visible: boolean): void;
1762
+ getDecorationWorldBounds(targetId: string, slot: string): Rect | null;
1763
+ setBadge(hostId: string, slot: string, options: BadgeOptions): void;
1764
+ /**
1765
+ * Attach / replace / clear an effect. Sibling of {@link setDecoration}: a
1766
+ * decoration adds geometry beside the host, an effect modulates the host
1767
+ * itself (transform delta or style override).
1768
+ */
1769
+ setEffect<TStyle = unknown>(targetId: string, slot: string, effect: EffectSpec<TStyle> | null): void;
1770
+ removeBadge(hostId: string, slot: string): void;
1771
+ getShapeWorldBounds(id: string): Rect | null;
1772
+ getShapePosition(id: string): Point | null;
1773
+ getConnectorPolyline(id: string): readonly Point[] | null;
1774
+ connectorGeometryUnchanged(id: string, next: BaseConnectorSpec): boolean;
1775
+ boundsOfSpec(spec: {
1776
+ readonly kind: string;
1777
+ }): Rect | undefined;
1778
+ collapsedShapeSpec(spec: {
1779
+ readonly kind: string;
1780
+ }): Record<string, unknown> | undefined;
1781
+ /** Visual centre of a shape — its bounds' midpoint, not its origin. */
1782
+ getShapeCenter(id: string): Point | null;
1783
+ scaleShapeSpec(spec: {
1784
+ readonly kind: string;
1785
+ }, factor: number): Record<string, unknown> | undefined;
1786
+ fitShapeSpecToContent(spec: {
1787
+ readonly kind: string;
1788
+ }, content: {
1789
+ readonly width: number;
1790
+ readonly height: number;
1791
+ }): Record<string, unknown> | undefined;
1792
+ /**
1793
+ * Text metrics. Backend-provided on purpose — SDF and canvas-2d metrics
1794
+ * genuinely disagree, so this is the `measureText` seam (§5), not a geometry
1795
+ * answer the engine could compute.
1796
+ */
1797
+ measureLabel(content: LabelContent, wrap?: LabelWrap): {
1798
+ width: number;
1799
+ height: number;
1800
+ } | null;
1801
+ hitTest(worldX: number, worldY: number, exclude?: ReadonlySet<string>): HitResult | null;
1802
+ setHitTestEnabled(enabled: boolean): void;
1803
+ reindexScaledShapeHits(ids?: Iterable<string>): void;
1804
+ reanchorAllConnectors(): void;
1805
+ reRouteAllConnectors(): void;
1806
+ tickAnimations(deltaMs: number): void;
1807
+ /** Vector fragment for this renderer's elements. Spec-driven; every backend can answer. */
1808
+ toSVG(): string;
1809
+ /**
1810
+ * Element-scoped pointer events — `shape:click`, `connector:pointerover`,
1811
+ * `shape:partcontextmenu`, … Canvas-wide input goes on the kernel bus; this
1812
+ * channel is per-renderer because the payloads name elements it owns.
1813
+ */
1814
+ readonly events: EventEmitter<ElementEventMap>;
1815
+ /**
1816
+ * Release everything this device holds.
1817
+ *
1818
+ * Called by whoever *owns* the device. A layer that received its renderer
1819
+ * from `surface.primitives` does **not** own it — the surface does, and
1820
+ * destroys it in `ISurface.destroy()`. Calling it from both places is a
1821
+ * double-free.
1822
+ */
1823
+ destroy(): void;
1824
+ }
1825
+
1826
+ /**
1827
+ * `ISurface` — a layer's slice of the renderer.
1828
+ *
1829
+ * A layer asks the renderer for a surface at mount and draws through it. It
1830
+ * never sees a display object, a scene graph, or anything else backend-shaped:
1831
+ * a surface hands back a **drawing device** for durable content, an **overlay
1832
+ * device** for transient gesture visuals, and the three knobs a layer genuinely
1833
+ * needs (visibility, paint order, teardown).
1834
+ *
1835
+ * This is what replaces `new Container()` in `WorldLayer.mount()` — the last
1836
+ * place the orchestrator constructed a pixi object for a layer to fill.
1837
+ *
1838
+ * The two spaces mirror the two layer bases: `'world'` is camera-affected and
1839
+ * pans/zooms with the diagram, `'screen'` stays glued to the viewport.
1840
+ *
1841
+ * See `docs/renderer-split-design.md` §4.
1842
+ */
1843
+
1844
+ /** Which space a surface's contents live in. */
1845
+ type SurfaceSpace = 'world' | 'screen';
1846
+ /**
1847
+ * Per-layer knobs for the device a surface builds. These are *engine policy a
1848
+ * layer owns*, not device config — a graph layer with tiny nodes wants a larger
1849
+ * hit floor than a layer of big cards, and only the layer knows that.
1850
+ */
1851
+ interface SurfaceOptions {
1852
+ /**
1853
+ * Minimum hover/click target in screen pixels, used as a fallback when no
1854
+ * silhouette contains the cursor. See `PrimitivesRendererOptions.hitFloorPx`.
1855
+ */
1856
+ hitFloorPx?: number;
1857
+ }
1858
+ /**
1859
+ * A full-surface backdrop: a solid fill, optionally overlaid with a repeating
1860
+ * tile that can be offset and scaled to follow the camera.
1861
+ *
1862
+ * The split of responsibility is the point. The **engine** decides what the
1863
+ * pattern looks like — dots, grid, lines, spacing, colour, DPR — and rasterises
1864
+ * one tile with a 2D canvas, which needs no backend at all. The **backend**
1865
+ * decides how that tile is repeated across the surface, which is the only part
1866
+ * that touches the GPU.
1867
+ *
1868
+ * This is deliberately not a spec and not an overlay. A backdrop is neither
1869
+ * durable content (it is derived from theme + camera, never authored) nor a
1870
+ * transient gesture visual — it is a property of the surface itself.
1871
+ */
1872
+ interface SurfaceBackdrop {
1873
+ /** Solid fill painted behind everything on the surface. */
1874
+ readonly color: number | string;
1875
+ /** Surface size in CSS pixels. */
1876
+ readonly width: number;
1877
+ readonly height: number;
1878
+ /** Optional repeating tile drawn over the solid fill. */
1879
+ readonly tile?: {
1880
+ /**
1881
+ * One tile, already rasterised by the engine. A plain DOM image source, so
1882
+ * a backend wraps it in whatever texture type it uses.
1883
+ *
1884
+ * Identity matters: a backend may cache its texture and rebuild only when
1885
+ * this changes, so pass the *same* object when only the transform moves.
1886
+ */
1887
+ readonly source: CanvasImageSource;
1888
+ /** Uniform scale applied to the tile. */
1889
+ readonly scale: number;
1890
+ /** Tile offset in surface pixels — how the pattern tracks the camera. */
1891
+ readonly offsetX: number;
1892
+ readonly offsetY: number;
1893
+ readonly alpha?: number;
1894
+ /** `false` hides the tile while keeping the solid fill. */
1895
+ readonly visible?: boolean;
1896
+ };
1897
+ }
1898
+ interface ISurface {
1899
+ /** Stable id — the owning layer's id. Names the surface in a scene tree. */
1900
+ readonly id: string;
1901
+ readonly space: SurfaceSpace;
1902
+ /**
1903
+ * This layer's drawing device: the target a `SpecProjector` drives from the
1904
+ * store, plus the per-frame commands and geometry answers a domain layer
1905
+ * still calls directly. Pixi-free, so `@invana/graph` drives a backend it
1906
+ * never imports.
1907
+ */
1908
+ readonly primitives: IElementRenderer;
1909
+ /**
1910
+ * An immediate-mode device for **transient** visuals owned by this layer
1911
+ * (a minimap's viewport box, a hover outline). Anything durable is a spec.
1912
+ */
1913
+ overlay(label: string): IOverlayDevice;
1914
+ /**
1915
+ * Paint (or clear, with `null`) this surface's backdrop. Cheap to call every
1916
+ * frame: a backend rebuilds its tile texture only when `tile.source` changes
1917
+ * identity, so a camera-following pattern costs a transform write.
1918
+ */
1919
+ setBackdrop(backdrop: SurfaceBackdrop | null): void;
1920
+ setVisible(visible: boolean): void;
1921
+ setZIndex(z: number): void;
1922
+ destroy(): void;
1923
+ }
1924
+ /**
1925
+ * The lifecycle half of the renderer contract: how surfaces come into being.
1926
+ * The drawing half is {@link IElementRenderer}, reached through a surface.
1927
+ */
1928
+ interface ISurfaceHost {
1929
+ createSurface(space: SurfaceSpace, id: string, opts?: SurfaceOptions): ISurface;
1930
+ }
1931
+
1932
+ /**
1933
+ * `IRenderer` — the drawing backend contract.
1934
+ *
1935
+ * ## Why this lives in `@invana/canvas` and not the kernel
1936
+ *
1937
+ * The kernel (`@invana/canvas-store`) is renderer-free and has no spec
1938
+ * vocabulary — and this contract is *made of* spec vocabulary: a surface
1939
+ * projects `BaseShapeSpec` / `BaseConnectorSpec`, an overlay draws in engine
1940
+ * geometry, a camera binding speaks the abstract transform. So the seam belongs
1941
+ * to the orchestrator, which owns that vocabulary. The kernel keeps only the two
1942
+ * genuinely device-shaped types it already had — {@link RendererBackend} and
1943
+ * `RendererInitOptions` — because those are the non-syncable counterpart to
1944
+ * `CanvasSceneOptions` and carry no drawing concepts.
1945
+ *
1946
+ * ## What a renderer actually is here
1947
+ *
1948
+ * Not a push target. `@invana/canvas` hands out **devices** and the renderer
1949
+ * answers with realisations:
1950
+ *
1951
+ * ```
1952
+ * Canvas ──mount()──────────────► stands up the backend + its scene root
1953
+ * ──createSurface(id)────► ISurface → SpecProjectionTarget (durable content)
1954
+ * → IOverlayDevice (transient gestures)
1955
+ * ──createCameraBinding()► ICameraBinding — Camera drives it
1956
+ * ──tick(dt)─────────────► advance backend animation; the engine owns the only rAF (G3)
1957
+ * ```
1958
+ *
1959
+ * Durable content reaches the backend through {@link SpecProjector}, driven by
1960
+ * `specs:flush` from the store — the renderer is a projection of state, not a
1961
+ * thing that gets told what to draw (`docs/renderer-split-design.md` §2, §4).
1962
+ *
1963
+ * ## What is deliberately *not* here
1964
+ *
1965
+ * - **`applyView` / `applyData`.** An earlier draft of this seam had the
1966
+ * orchestrator pushing view and data deltas at the renderer. P2 replaced that
1967
+ * with spec state + `specs:flush`, so those methods described a flow that no
1968
+ * longer exists. They are gone rather than left as decoration.
1969
+ * - **Input.** A renderer emits `input:*` onto the shared `CanvasEventBus`; it
1970
+ * is not a member of this interface. There is exactly one bus, so the seam
1971
+ * stays one-way: devices out, input published on the bus.
1972
+ * - **Picking.** Interaction, not drawing (design D5) — `hit/PickingIndex` owns
1973
+ * it, and the renderer only answers `HitGeometrySource`.
1974
+ */
1975
+
1976
+ /**
1977
+ * What a backend can and cannot do. The engine reads this to degrade rather
1978
+ * than throw — a spec kind a backend doesn't know is skipped with a
1979
+ * `capability:unsupported` event, which is what lets a second backend ship with
1980
+ * a subset (`docs/renderer-split-design.md` §4.2).
1981
+ */
1982
+ interface RendererCapabilities {
1983
+ /** How far visual effects go: none, style-level (tint/alpha), or real shaders. */
1984
+ readonly effects: 'none' | 'style' | 'shader';
1985
+ /** How text is rasterised. Drives which label features are honoured. */
1986
+ readonly textMode: 'native' | 'sdf' | 'dom';
1987
+ /** Whether {@link IRenderer.extract} is available. */
1988
+ readonly rasterExport: boolean;
1989
+ /** Whether the backend has a real depth axis (2D backends: `false`). */
1990
+ readonly depth: boolean;
1991
+ /** Spec kinds this backend can draw. Unknown kinds degrade, never throw. */
1992
+ readonly specKinds: readonly string[];
1993
+ }
1994
+ /** Where a renderer attaches, and the device knobs for standing it up. */
1995
+ interface RendererMountOptions extends RendererInitOptions {
1996
+ /**
1997
+ * Suppress the browser context menu on the drawing surface, so a right-click
1998
+ * can be a canvas gesture. Default `true`.
1999
+ */
2000
+ suppressBrowserContextMenu?: boolean;
2001
+ /** Track the host element's size and resize the surface to match. Default `false`. */
2002
+ autoResize?: boolean;
2003
+ /** Opaque background (`backgroundAlpha: 1`) rather than a transparent surface. */
2004
+ opaque?: boolean;
2005
+ /** GPU power hint forwarded to the backend where it has one. */
2006
+ powerPreference?: 'high-performance' | 'low-power';
2007
+ }
2008
+ interface IRenderer {
2009
+ /**
2010
+ * Stand the backend up against a DOM host: create the drawing surface, attach
2011
+ * it, and build the scene root. May be async (GPU adapter acquisition); the
2012
+ * orchestrator awaits it before creating any surface. {@link backend} and
2013
+ * {@link capabilities} are meaningful only once this resolves.
2014
+ */
2015
+ mount(host: HTMLElement, opts?: RendererMountOptions): Promise<void> | void;
2016
+ /**
2017
+ * A layer's slice of the renderer — durable spec projection, transient
2018
+ * overlays, visibility and paint order. This replaces a layer constructing a
2019
+ * backend container for itself.
2020
+ */
2021
+ createSurface(space: SurfaceSpace, id: string, opts?: SurfaceOptions): ISurface;
2022
+ /**
2023
+ * A standalone transient device not owned by any layer — a lasso, a brush
2024
+ * rectangle, a drag ghost. Behaviours use this, because a gesture overlay
2025
+ * belongs to the gesture rather than to a layer (§3, decision D3).
2026
+ */
2027
+ createOverlay(label: string, space?: OverlaySpace): IOverlayDevice;
2028
+ /**
2029
+ * The concrete viewport behind the engine's {@link Camera}. The renderer owns
2030
+ * the realisation; `Camera` owns clamping, anchored zoom, fit and the bus /
2031
+ * store sync.
2032
+ */
2033
+ createCameraBinding(): ICameraBinding;
2034
+ /**
2035
+ * Hand back the engine's `Camera` once it wraps this renderer's binding.
2036
+ * Surfaces need it (hit-floor scaling, label-raster priority), so the order is
2037
+ * `createCameraBinding` → `new Camera` → `attachCamera` → `createSurface`.
2038
+ */
2039
+ attachCamera(camera: Camera): void;
2040
+ /**
2041
+ * World-space bounds of everything drawn, or `null` when nothing is. Used by
2042
+ * `area: 'content'` export. The backend answers because only it knows what is
2043
+ * actually mounted.
2044
+ */
2045
+ worldContentBounds(): Rect | null;
2046
+ /** The drawing surface, when there is one. `null` on a headless backend. */
2047
+ readonly canvasElement: HTMLCanvasElement | null;
2048
+ /** Viewport size changed (CSS px). */
2049
+ resize(width: number, height: number): void;
2050
+ /**
2051
+ * Advance backend-owned animation and **present the frame**.
2052
+ *
2053
+ * The engine owns the only `requestAnimationFrame` (G3) and calls this once
2054
+ * per frame, after advancing the camera, flushing data and updating layers. A
2055
+ * renderer must **not** schedule frames of its own: two clocks disagree about
2056
+ * frame order, and a test can't drive time by hand.
2057
+ */
2058
+ tick(dtMs: number): void;
2059
+ /**
2060
+ * Raster capture, capability-gated by {@link RendererCapabilities.rasterExport}
2061
+ * (G1). Vector/SVG export is engine-side and spec-driven, so it is *not* here —
2062
+ * it works on every backend including headless.
2063
+ */
2064
+ extract?(opts: {
2065
+ /** World-space region to capture. */
2066
+ region: Rect;
2067
+ /** Output pixels per world unit. */
2068
+ resolution: number;
2069
+ }): HTMLCanvasElement;
2070
+ /** Tear down: release the backend, the DOM surface, and every listener. */
2071
+ destroy(): void;
2072
+ /** The backend actually resolved at {@link mount} (may differ from the preference). */
2073
+ readonly backend: RendererBackend;
2074
+ /** What this backend supports. Read after {@link mount}. */
2075
+ readonly capabilities: RendererCapabilities;
2076
+ }
2077
+
2078
+ /**
2079
+ * `GestureArbiter` — who owns the pointer right now.
2080
+ *
2081
+ * Architecture: see `docs/renderer-split-design.md` §9 (P5).
2082
+ *
2083
+ * **Why this exists.** Before P5, a behaviour that needed the camera to stop
2084
+ * panning during its own gesture reached for `camera.viewport.plugins.pause('drag')`
2085
+ * — sixteen calls across six behaviours, every one of them poking at a
2086
+ * `pixi-viewport` internal from domain code. The thing they actually wanted was
2087
+ * never a camera API: it was *exclusivity*. A node drag, a lasso, a brush, a
2088
+ * resize and an edge draw are all mutually exclusive pointer gestures, and the
2089
+ * camera pan is simply the lowest-priority one of them.
2090
+ *
2091
+ * So the arbiter models the real invariant — **at most one owner at a time** —
2092
+ * and the camera becomes a subscriber like anything else: `DragPanBehaviour`
2093
+ * yields while {@link GestureArbiter.owner} names somebody else. That inverts
2094
+ * the old direction (others suspending the camera) into the camera suspending
2095
+ * itself, which is what lets the pixi-viewport handle move into the renderer
2096
+ * package in P6 without dragging six domain behaviours along with it.
2097
+ *
2098
+ * **Leak safety is the whole design.** A claim that is never released freezes
2099
+ * every gesture *and* the camera, which is worse than the failure it replaces.
2100
+ * Three properties defend against that:
2101
+ *
2102
+ * 1. **Release is token-identified.** The function returned by
2103
+ * {@link GestureArbiter.claim} only clears *that* claim. Calling it twice is a
2104
+ * no-op, and calling a stale one can never evict a later owner.
2105
+ * 2. **A re-claim by the current owner always succeeds.** A behaviour that
2106
+ * leaks its own claim can never deadlock *itself* out of its next gesture —
2107
+ * the old token is simply invalidated.
2108
+ * 3. **`Behaviour` releases on `disable()` and `destroy()`** regardless of what
2109
+ * the subclass did (see `Behaviour.claimGesture`), so unmount and mid-gesture
2110
+ * teardown can't strand a claim.
2111
+ */
2112
+ /** Options for a single {@link GestureArbiter.claim}. */
2113
+ interface GestureClaimOptions {
2114
+ /**
2115
+ * Higher wins. A claim is refused when another owner holds the gesture at an
2116
+ * equal or higher priority; a strictly higher priority **pre-empts** the
2117
+ * current owner (whose {@link GestureClaimOptions.onRevoke} fires and whose
2118
+ * release function goes inert). Default `0` — every built-in behaviour claims
2119
+ * at the default, so no pre-emption happens unless a consumer asks for it.
2120
+ */
2121
+ priority?: number;
2122
+ /**
2123
+ * Called when this claim is pre-empted by a higher-priority owner. The seam
2124
+ * a long-running gesture uses to abort cleanly instead of continuing to move
2125
+ * things while somebody else drives the pointer. Not called on a normal
2126
+ * release, nor when the same owner re-claims.
2127
+ */
2128
+ onRevoke?: () => void;
2129
+ }
2130
+ /**
2131
+ * Arbitrates exclusive ownership of the pointer gesture. Reached as
2132
+ * `ctx.gestures`; provided per-`Canvas`.
2133
+ */
2134
+ interface GestureArbiter {
2135
+ /**
2136
+ * Try to take the gesture for `owner` (by convention the behaviour's `id`).
2137
+ * Returns a **release** function on success, or `null` when another owner
2138
+ * already holds it at an equal-or-higher priority — in which case the caller
2139
+ * should not start its gesture.
2140
+ *
2141
+ * Release is idempotent and identity-checked: calling it after the claim has
2142
+ * already ended (or been pre-empted) does nothing, so it can never clear
2143
+ * somebody else's claim.
2144
+ */
2145
+ claim(owner: string, opts?: GestureClaimOptions): (() => void) | null;
2146
+ /** The current owner id, or `null` when the gesture is free. */
2147
+ readonly owner: string | null;
2148
+ /**
2149
+ * Subscribe to ownership changes — the hook `DragPanBehaviour` uses to
2150
+ * suspend and restore camera panning. Fires with the new owner (`null` when
2151
+ * released). Returns an unsubscribe function.
2152
+ */
2153
+ onOwnerChange(listener: (owner: string | null) => void): () => void;
2154
+ }
2155
+ /**
2156
+ * The default in-memory {@link GestureArbiter}. Renderer-free and DOM-free: it
2157
+ * knows nothing about pointers, only about who asked first.
2158
+ */
2159
+ declare class DefaultGestureArbiter implements GestureArbiter {
2160
+ private active;
2161
+ private readonly listeners;
2162
+ get owner(): string | null;
2163
+ claim(owner: string, opts?: GestureClaimOptions): (() => void) | null;
2164
+ onOwnerChange(listener: (owner: string | null) => void): () => void;
2165
+ /**
2166
+ * Drop the claim identified by `token`. A stale token — from a released or
2167
+ * pre-empted claim — is ignored, which is what makes double-release safe.
2168
+ */
2169
+ private release;
2170
+ /** Snapshot before iterating: a listener may unsubscribe from inside itself. */
2171
+ private emit;
2172
+ }
2173
+
2174
+ /**
2175
+ * `LayerRegistry` — stores the Layers added to a Canvas.
2176
+ *
2177
+ * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.layers).
2178
+ *
2179
+ * **Responsibilities**
2180
+ * - Add / remove (with mount / unmount lifecycle).
2181
+ * - Typed `get<T>(id)`.
2182
+ * - `byZOrder()` iteration — used by the Canvas tick.
2183
+ * - Fires `'scene:layer:add'` / `'scene:layer:remove'` on the bus.
2184
+ *
2185
+ * **Lifecycle wiring**
2186
+ *
2187
+ * The registry doesn't itself construct the `CanvasContext` — it would be
2188
+ * circular (the registry is a field of the context). Instead the Canvas
2189
+ * passes a `getContext()` thunk; `add(layer)` resolves it at the moment of
2190
+ * mount. This keeps the registry decoupled from the context's full shape.
2191
+ */
2192
+
2193
+ interface LayerRegistryOptions {
2194
+ /**
2195
+ * Resolves the `CanvasContext` at the moment of mount, or `undefined` before
2196
+ * the Canvas is initialised. Layers added pre-init are stored and mounted
2197
+ * later by `mountAll()`.
2198
+ */
2199
+ getContext: () => CanvasContext | undefined;
2200
+ /** Bus for `layer:added` / `layer:removed` events. */
2201
+ bus: CanvasEventBus;
2202
+ }
2203
+ declare class LayerRegistry {
2204
+ private readonly layers;
2205
+ private readonly getContext;
2206
+ private readonly bus;
2207
+ /** Cached z-sorted view; invalidated on add/remove/setZIndex. */
2208
+ private zOrderCache;
2209
+ constructor(opts: LayerRegistryOptions);
2210
+ /** Number of registered layers. */
2211
+ get size(): number;
2212
+ /**
2213
+ * Add a Layer to the canvas. Mounts immediately if the Canvas is initialised;
2214
+ * otherwise the layer waits for `mountAll()` (called by `Canvas.init`). Fires
2215
+ * `layer:added`. Throws if `id` is already registered.
2216
+ */
2217
+ add(layer: ILayer): void;
2218
+ /** Mount every not-yet-mounted layer. Called by `Canvas.init` once the context exists. */
2219
+ mountAll(): void;
2220
+ /**
2221
+ * Remove a Layer. Calls `layer.unmount()` and fires `layer:removed`.
2222
+ * No-op if `id` isn't registered.
2223
+ */
2224
+ remove(id: string): void;
2225
+ /** Typed get by id. Returns `undefined` if not found. */
2226
+ get<T extends ILayer = ILayer>(id: string): T | undefined;
2227
+ has(id: string): boolean;
2228
+ /** Snapshot of all layers in insertion order. */
2229
+ list(): readonly ILayer[];
2230
+ /**
2231
+ * Iterate layers in z-order (low → high). The Canvas tick walks layers in
2232
+ * z-order to flush dirty work; rendering order is then determined by
2233
+ * pixi's child order (handled by `SurfaceManager.setWorldLayerZ`).
2234
+ *
2235
+ * The result is cached and reused until `add` / `remove` / `setZIndex` invalidates.
2236
+ */
2237
+ byZOrder(): readonly ILayer[];
2238
+ /**
2239
+ * Update a layer's `zIndex` and propagate to surfaces. Invalidates the
2240
+ * z-order cache. No-op if the layer isn't registered.
2241
+ */
2242
+ setZIndex(id: string, zIndex: number): void;
2243
+ /**
2244
+ * Tear down every registered layer. Called on Canvas destroy.
2245
+ * Iteration is over a snapshot so unmount-triggered side effects don't
2246
+ * corrupt the loop.
2247
+ */
2248
+ clear(): void;
2249
+ }
2250
+
2251
+ /**
2252
+ * `Behaviour` — input subscriber that translates user input into state mutations.
2253
+ *
2254
+ * Architecture: see `architecture-proposal.md` §2.2.
2255
+ *
2256
+ * Behaviours own neither rendering output nor source-of-truth data. They
2257
+ * subscribe to layer events (`'node:hover'`, `'shape:click'`) or canvas events
2258
+ * (`'pointerdown'`) and mutate the appropriate `state` slice.
2259
+ *
2260
+ * **Default `enabled: false`.** Registration wires the behaviour up; the
2261
+ * developer explicitly enables it. Matches the rule that no input behaviour
2262
+ * is auto-active (`architecture-proposal.md` §2.2 + repo CLAUDE.md rule 7).
2263
+ *
2264
+ * **`shortcuts`** is advisory metadata — used by `BehaviourRegistry` to log
2265
+ * conflict warnings when two enabled behaviours claim the same gesture
2266
+ * (e.g. lasso vs. pan both wanting `'shift+drag'`). The framework warns;
2267
+ * it does not enforce — that's the developer's job.
2268
+ */
2269
+
2270
+ /** What `BehaviourRegistry` sees. */
2271
+ interface IBehaviour {
2272
+ readonly id: string;
2273
+ readonly enabled: boolean;
2274
+ /** `true` once `register(ctx)` has run. Lets the registry skip already-wired behaviours. */
2275
+ readonly isRegistered: boolean;
2276
+ readonly scope: 'layer' | 'canvas';
2277
+ readonly targetLayerId?: string;
2278
+ readonly shortcuts?: readonly string[];
2279
+ register(ctx: CanvasContext): void;
2280
+ destroy(): void;
2281
+ enable(): void;
2282
+ disable(): void;
2283
+ /**
2284
+ * Merge a serialisable options patch and apply it live. Every behaviour
2285
+ * supports this (the base provides a generic implementation) so the engine's
2286
+ * `canvas.update({ behaviours })` path can retune any behaviour uniformly.
2287
+ */
2288
+ setOptions(changes: Record<string, unknown>): void;
2289
+ }
2290
+ interface BehaviourOptions {
2291
+ id: string;
2292
+ /**
2293
+ * Layer-scoped behaviours target a specific Layer by id. Canvas-scoped
2294
+ * behaviours have no `targetLayerId` and `scope: 'canvas'`.
2295
+ */
2296
+ targetLayerId?: string;
2297
+ /** Default `false` — the developer explicitly enables. */
2298
+ enabled?: boolean;
2299
+ /**
2300
+ * Gesture identifiers this behaviour claims. Used by `BehaviourRegistry`
2301
+ * for conflict warnings. Format is convention-free (`'shift+drag'`,
2302
+ * `'wheel+ctrl'`, `'rclick'`); registries match strings as-is.
2303
+ */
2304
+ shortcuts?: readonly string[];
2305
+ }
2306
+ declare abstract class Behaviour<TOptions extends BehaviourOptions = BehaviourOptions> implements IBehaviour {
2307
+ readonly id: string;
2308
+ readonly targetLayerId?: string;
2309
+ readonly shortcuts?: readonly string[];
2310
+ /**
2311
+ * Stable **class kind** — a minification-safe discriminator matching the
2312
+ * `@invana/canvas-ui` settings-editor registry key (e.g. `'drag-pan'`,
2313
+ * `'wheel-zoom'`). Distinct from {@link id} (the per-instance key): all
2314
+ * `DragPanBehaviour` instances share `kind: 'drag-pan'`. Concrete behaviours
2315
+ * set it as a class field; left `undefined` on any that haven't, so consumers
2316
+ * fall back (e.g. to the class name). Lets domain-free tooling resolve an
2317
+ * instance's editor without an `instanceof` ladder.
2318
+ */
2319
+ readonly kind?: string;
2320
+ /**
2321
+ * `'layer'` if `targetLayerId` is set, otherwise `'canvas'`. Set automatically
2322
+ * from the constructor — subclasses don't need to re-declare.
2323
+ */
2324
+ readonly scope: 'layer' | 'canvas';
2325
+ protected _enabled: boolean;
2326
+ protected ctx?: CanvasContext;
2327
+ /**
2328
+ * The construction options, merged in-place by {@link setOptions}. Named
2329
+ * `_options` (not `options`) so subclasses that expose a bespoke
2330
+ * `get options()` snapshot don't collide with it. Subclasses read their live
2331
+ * config from here (or from fields re-synced in {@link onOptionsChanged}).
2332
+ */
2333
+ protected _options: TOptions;
2334
+ /**
2335
+ * Release function for this behaviour's live gesture claim, or `null` when it
2336
+ * holds none. Held privately (not `protected`) so the only way to end a claim
2337
+ * is {@link releaseGesture} — which nulls the field *before* invoking it, so a
2338
+ * double release can't happen even under re-entrancy.
2339
+ */
2340
+ private _gestureRelease;
2341
+ constructor(opts: TOptions);
2342
+ get enabled(): boolean;
2343
+ get isRegistered(): boolean;
2344
+ /** Called by `BehaviourRegistry.register(behaviour)`. Subscribes to inputs. */
2345
+ register(ctx: CanvasContext): void;
2346
+ /** Called by `BehaviourRegistry.unregister(id)`. Drops subscriptions. */
2347
+ destroy(): void;
2348
+ enable(): void;
2349
+ disable(): void;
2350
+ /**
2351
+ * Merge a serialisable options patch and apply it live. Reflects an `enabled`
2352
+ * change by enabling/disabling, then calls {@link onOptionsChanged} so the
2353
+ * subclass can apply the rest (re-sync cached fields, re-arm a viewport
2354
+ * plugin, recompute). This is the seam the engine's
2355
+ * `canvas.update({ behaviours: { [id]: patch } })` path invokes — so a settings
2356
+ * editor can retune any behaviour without remounting it.
2357
+ *
2358
+ * Subclasses with bespoke apply logic (e.g. clearing selection state on a
2359
+ * mode change) override this and should call `super.setOptions(changes)` first
2360
+ * to keep `_options` — and thus {@link getOptions} — coherent.
2361
+ */
2362
+ setOptions(changes: Partial<TOptions>): void;
2363
+ /** Snapshot of the current (merged) options — seeds a settings editor. */
2364
+ getOptions(): Readonly<TOptions>;
2365
+ /**
2366
+ * Contribute this behaviour's serialisable config to a canvas-state snapshot
2367
+ * (the engine's `DefinitionSerializable` contract). The base implementation
2368
+ * captures the explicit `enabled` flag (rule 7). Subclasses with additional
2369
+ * JSON-serialisable options should override and spread `super.serializeDefinition()`.
2370
+ */
2371
+ serializeDefinition(): Record<string, unknown> | undefined;
2372
+ /** Subscribe to events / setup any handler resources. */
2373
+ protected abstract onRegister(ctx: CanvasContext): void;
2374
+ /** Cleanup on destroy. Default no-op. */
2375
+ protected onDestroy(_ctx: CanvasContext): void;
2376
+ /** Hook fired when the developer enables the behaviour. */
2377
+ protected onEnable(): void;
2378
+ /** Hook fired on disable. */
2379
+ protected onDisable(): void;
2380
+ /**
2381
+ * Hook fired after {@link setOptions} merges a patch (and after any `enabled`
2382
+ * toggle is applied). Default no-op. Override to apply an option change live:
2383
+ * a behaviour whose effect is wired in {@link onEnable} (a pixi-viewport
2384
+ * plugin, a DOM listener) re-arms here; one that caches option values in
2385
+ * fields re-syncs them from `this._options` here. `changes` is the raw patch;
2386
+ * `this._options` already holds the merged result.
2387
+ */
2388
+ protected onOptionsChanged(_changes: Partial<TOptions>): void;
2389
+ /**
2390
+ * Convenience `if (!enabled) return;` for use inside event handlers
2391
+ * (without rebinding `this` cost).
2392
+ */
2393
+ protected get isEnabled(): boolean;
2394
+ /**
2395
+ * Take exclusive ownership of the pointer gesture for the duration of a drag
2396
+ * (`ctx.gestures`, see `input/GestureArbiter.ts`). Returns `false` when
2397
+ * another behaviour already owns it — the caller must then **not** start its
2398
+ * gesture, because two behaviours steering the same pointer is exactly what
2399
+ * the arbiter exists to prevent.
2400
+ *
2401
+ * Claiming also suspends camera panning: `DragPanBehaviour` watches the
2402
+ * arbiter and yields while anybody else owns the gesture. That replaces the
2403
+ * old `camera.viewport.plugins.pause('drag')` reach-through, which put a
2404
+ * `pixi-viewport` internal in the hands of domain behaviours.
2405
+ *
2406
+ * Pair every successful claim with {@link releaseGesture} on **every** exit
2407
+ * path — pointerup, pointercancel, abort. `disable()` and `destroy()` release
2408
+ * automatically as a backstop.
2409
+ */
2410
+ protected claimGesture(opts?: GestureClaimOptions): boolean;
2411
+ /**
2412
+ * End this behaviour's gesture claim. Safe to call any number of times and
2413
+ * when no claim is held — the arbiter identifies claims by token, so a stale
2414
+ * release can never evict a later owner.
2415
+ */
2416
+ protected releaseGesture(): void;
2417
+ /** Does this behaviour currently hold the gesture? */
2418
+ protected get hasGestureClaim(): boolean;
2419
+ /**
2420
+ * Re-run {@link onDisable} then {@link onEnable} when the behaviour is live, so
2421
+ * an option change wired at enable-time (a pixi-viewport plugin, a listener
2422
+ * bound with the old config) picks up `this._options`. No-op when disabled or
2423
+ * unregistered (the next {@link onEnable} will read the fresh options anyway).
2424
+ * The idiomatic body of an {@link onOptionsChanged} override for such
2425
+ * behaviours.
2426
+ */
2427
+ protected reArm(): void;
2428
+ }
2429
+
2430
+ /**
2431
+ * `BehaviourRegistry` — stores Behaviours and toggles their enabled state.
2432
+ *
2433
+ * Architecture: see `architecture-proposal.md` §2.2.
2434
+ *
2435
+ * **Responsibilities**
2436
+ * - `register` / `unregister` (with register / destroy lifecycle).
2437
+ * - `setEnabled(id, enabled)` — toggles + fires `'scene:behaviour:enable'` /
2438
+ * `'scene:behaviour:disable'`.
2439
+ * - Typed `get<T>(id)`.
2440
+ * - **Gesture-conflict warning**: when two enabled behaviours claim the same
2441
+ * `shortcut`, log a `console.warn`. Doesn't enforce — the developer
2442
+ * decides whether two behaviours can coexist on the same gesture.
2443
+ */
2444
+
2445
+ interface BehaviourRegistryOptions {
2446
+ getContext: () => CanvasContext | undefined;
2447
+ bus: CanvasEventBus;
2448
+ }
2449
+ declare class BehaviourRegistry {
2450
+ private readonly behaviours;
2451
+ private readonly getContext;
2452
+ private readonly bus;
2453
+ constructor(opts: BehaviourRegistryOptions);
2454
+ get size(): number;
2455
+ /**
2456
+ * Register a Behaviour. Wires it (`behaviour.register(ctx)` + events) now if
2457
+ * the Canvas is initialised; otherwise it's stored and wired later by
2458
+ * `registerAll()` (called by `Canvas.init`). Throws on duplicate id.
2459
+ */
2460
+ register(behaviour: IBehaviour): void;
2461
+ /** Wire every not-yet-registered behaviour. Called by `Canvas.init` (after layers mount). */
2462
+ registerAll(): void;
2463
+ /** `behaviour.register(ctx)` + the registered/enabled events. */
2464
+ private wire;
2465
+ /** Remove a behaviour. Calls `destroy()`. No-op if not registered. */
2466
+ unregister(id: string): void;
2467
+ /** Enable / disable a behaviour. Fires the corresponding bus event. */
2468
+ setEnabled(id: string, enabled: boolean): void;
2469
+ get<T extends IBehaviour = IBehaviour>(id: string): T | undefined;
2470
+ has(id: string): boolean;
2471
+ list(): readonly IBehaviour[];
2472
+ /** Tear down all behaviours. Called on Canvas destroy. */
2473
+ clear(): void;
2474
+ private warnOnShortcutConflict;
2475
+ }
2476
+
2477
+ /**
2478
+ * `CanvasContext` — the shared service surface every Layer / Behaviour /
2479
+ * Layout receives at mount/register time.
2480
+ *
2481
+ * Architecture: see `architecture-proposal.md` §2.4.
2482
+ *
2483
+ * **One context, three audiences.** Per the proposal, there is no separate
2484
+ * `LayerContext` / `BehaviourContext` / `LayoutContext` — the same shape is
2485
+ * handed to every participant so cross-cutting access (read peer layers,
2486
+ * fire camera moves, tap telemetry) doesn't need three parallel context types.
2487
+ *
2488
+ * The `Canvas` builds a concrete object that satisfies this interface and
2489
+ * passes it down. Tests can construct a stub by satisfying these fields.
2490
+ */
2491
+
2492
+ interface CanvasContext {
2493
+ /** Layer registry — `add / remove / get<T>(id) / list / byZOrder`. */
2494
+ readonly layers: LayerRegistry;
2495
+ /**
2496
+ * Behaviour registry — `register / setEnabled / get<T>(id) / list`.
2497
+ * Behaviours never auto-enable; the developer registers + enables explicitly
2498
+ * (`architecture-proposal.md` §2.2).
2499
+ */
2500
+ readonly behaviours: BehaviourRegistry;
2501
+ /** Camera — pan/zoom/projection. Wraps a `pixi-viewport` `Viewport`. */
2502
+ readonly camera: Camera;
2503
+ /**
2504
+ * Pointer-gesture arbitration — at most one owner at a time. A behaviour that
2505
+ * needs the pointer to itself (drag, lasso, brush, resize, edge draw) claims
2506
+ * it here rather than suspending the camera's pan plugin behind its back;
2507
+ * `DragPanBehaviour` yields whenever `gestures.owner` names somebody else.
2508
+ *
2509
+ * Behaviours should reach for `Behaviour.claimGesture` /
2510
+ * `Behaviour.releaseGesture` instead of calling this directly — the base class
2511
+ * releases on `disable()` / `destroy()`, and a stranded claim would freeze
2512
+ * both the camera and every other gesture.
2513
+ */
2514
+ readonly gestures: GestureArbiter;
2515
+ /** Canvas-wide event bus + telemetry tap channel. */
2516
+ readonly events: CanvasEventBus;
2517
+ /**
2518
+ * The renderer-free kernel (`@invana/canvas-store`) — `view` (reactive config +
2519
+ * interaction state), `data` (bulk per-source stores), `events`, `theme`,
2520
+ * history. The cross-cutting handle for the state migration: layers
2521
+ * read/subscribe `store.data[id]` + `store.view`; behaviours write interaction
2522
+ * via `store.view.update(...)`. During M0 the engine mirrors its config into
2523
+ * `store.view.definition` (see `Canvas.update`).
2524
+ */
2525
+ readonly store: CanvasStore;
2526
+ /**
2527
+ * The active theme channel. A single publisher (the domain `ThemeBehaviour`)
2528
+ * calls `theme.set(...)`; theme-aware layers read `theme.current()` and/or
2529
+ * subscribe to the `'theme:change'` event to recolour. `current()` is `null`
2530
+ * until a theme is first published.
2531
+ */
2532
+ readonly theme: ThemeState;
2533
+ /**
2534
+ * The underlying HTMLCanvasElement when running in DOM mode (`Canvas.init`).
2535
+ * Undefined for `Canvas.initWithStage` (headless / test path). Layers that
2536
+ * overlay DOM content above the canvas — `DevInfoLayer`, tooltips, popovers —
2537
+ * read this to find a parent element and to attach native DOM listeners.
2538
+ */
2539
+ readonly canvasElement?: HTMLCanvasElement;
2540
+ /**
2541
+ * Build a patch-emitting {@link ReactiveStore} — the factory behind
2542
+ * `Layer.state`. Injected by the engine (which implements it with the
2543
+ * kernel's `createReactiveStore`) because this package is dependency-free
2544
+ * and cannot construct a store itself; the seam is also what makes the
2545
+ * backend swappable (a collaborative canvas injects a Yjs-backed factory).
2546
+ */
2547
+ createStateStore<T extends object>(initial: T): ReactiveStore<T>;
2548
+ /**
2549
+ * A drawing device for a **transient** visual — a lasso, a brush rectangle, a
2550
+ * drag ghost. Not for layer content: anything durable is a spec in the store
2551
+ * (`docs/renderer-split-design.md` §3).
2552
+ *
2553
+ * Available to behaviours as well as layers, because a gesture overlay belongs
2554
+ * to the gesture, not to any one layer.
2555
+ */
2556
+ createOverlay(label: string, space?: OverlaySpace): IOverlayDevice;
2557
+ /**
2558
+ * A layer's slice of the renderer — its drawing device, overlays, visibility
2559
+ * and paint order. Replaces the layer bases constructing a pixi `Container`
2560
+ * themselves, and is the seam a second backend implements
2561
+ * (`docs/renderer-split-design.md` §4).
2562
+ */
2563
+ createSurface(space: SurfaceSpace, id: string, opts?: SurfaceOptions): ISurface;
2564
+ /**
2565
+ * Show a transient message on the shared canvas message channel — the same
2566
+ * call as `Canvas.showMessage`. Lets layers / behaviours / layouts surface a
2567
+ * status line (e.g. a layout announcing "Running…" on start) without reaching
2568
+ * for the bus directly. `timeout` (ms) auto-clears it.
2569
+ */
2570
+ showMessage(text: string, timeout?: number): void;
2571
+ /** Clear the current canvas message. */
2572
+ clearMessage(): void;
2573
+ }
2574
+
2575
+ /**
2576
+ * A scoped {@link EventEmitter} stamped with an {@link EventSource}. When connected
2577
+ * to a bus via {@link setBus}, every emit is **also** forwarded to the bus tap as a
2578
+ * structured envelope — so a store/layer/behaviour's own events reach the
2579
+ * canvas-wide tap (telemetry / collaboration) without each one re-plumbing.
2580
+ *
2581
+ * Local `on(...)` subscribers still get the raw typed payload as usual.
2582
+ */
2583
+ declare class SourceEmitter<M extends object> extends EventEmitter<M> {
2584
+ readonly source: EventSource;
2585
+ private bus;
2586
+ constructor(source: EventSource);
2587
+ /** Connect (or disconnect with `null`/`undefined`) this emitter's stream to a bus tap. */
2588
+ setBus(bus: CanvasEventBus | null | undefined): void;
2589
+ emit<K extends keyof M>(type: K, payload: M[K]): void;
2590
+ }
2591
+
2592
+ /**
2593
+ * `DirtyBatcher<TBucket>` — accumulates "this id changed" signals between frames,
2594
+ * deduplicates them, and hands a per-frame snapshot to a flush callback.
2595
+ *
2596
+ * Relocated into `@invana/canvas-store` (decision D1) alongside {@link ColumnStore}
2597
+ * — the renderer-free machinery behind the kernel's coalesced data flush. Pure;
2598
+ * **no rendering, no pixi, no `requestAnimationFrame` of its own** — the owner
2599
+ * (the engine's single rAF loop) calls {@link flush} once per tick.
2600
+ *
2601
+ * **Performance contract:** `mark` O(1) (Map.get + Set.add, no steady-state
2602
+ * alloc); `markAll` O(1) (a flag); `flush` O(1) (Map swap, no copy). Per-frame
2603
+ * consumer work is proportional to *changed* ids, never total scene size. Sets are
2604
+ * reused across frames (double-buffered) — zero GC pressure in steady state.
2605
+ *
2606
+ * **Double buffering:** `flush()` returns a snapshot of the previous frame's marks
2607
+ * and swaps in the empty buffer, so any `mark()` during the consumer's handler
2608
+ * lands in the *next* frame — never corrupts the iteration in flight.
2609
+ */
2610
+ /**
2611
+ * The snapshot handed to the flush handler. `buckets` is keyed by bucket name →
2612
+ * the Set of dirty ids this frame (untouched buckets are absent). `rebuildAll` is
2613
+ * the set of buckets flagged via {@link DirtyBatcher.markAll} — for those, iterate
2614
+ * the underlying data, not the per-id Set.
2615
+ */
2616
+ interface DirtySnapshot<TBucket extends string = string> {
2617
+ readonly buckets: ReadonlyMap<TBucket, ReadonlySet<string>>;
2618
+ readonly rebuildAll: ReadonlySet<TBucket>;
2619
+ }
2620
+ declare class DirtyBatcher<TBucket extends string = string> {
2621
+ private active;
2622
+ private buffer;
2623
+ private _dirty;
2624
+ /** Mark a single id dirty in a bucket. O(1); bucket Sets are created lazily + reused. */
2625
+ mark(bucket: TBucket, id: string): void;
2626
+ /** Flag a whole bucket for rebuild (theme change, LOD swap, wholesale replace). */
2627
+ markAll(bucket: TBucket): void;
2628
+ /** Cheap check the tick uses to decide whether to call {@link flush}. */
2629
+ hasPending(): boolean;
2630
+ /**
2631
+ * Swap buffers and return the previous frame's snapshot. The returned Sets are
2632
+ * still owned by the batcher — **do not retain references past the flush call**;
2633
+ * the next `flush()` reuses and clears them.
2634
+ */
2635
+ flush(): DirtySnapshot<TBucket>;
2636
+ /** Drop both buffers. Call on unmount; usable again afterwards. */
2637
+ reset(): void;
2638
+ /** Number of dirty ids in a bucket (0 if never touched). Debug. */
2639
+ bucketSize(bucket: TBucket): number;
2640
+ /** True iff the bucket is flagged for rebuild this frame. Debug. */
2641
+ isRebuildAll(bucket: TBucket): boolean;
2642
+ }
2643
+
2644
+ /**
2645
+ * `Layer` — base class for everything composable onto `canvas.layers`.
2646
+ *
2647
+ * Architecture: see `architecture-proposal.md` §2.1.
2648
+ *
2649
+ * **What every Layer owns:**
2650
+ * - `id` — stable identifier; used by registries, events, telemetry envelopes.
2651
+ * - `options` — construction-time, mostly-immutable config.
2652
+ * - `state` — UI / interaction state (`ReactiveStore<T>` from the kernel; small,
2653
+ * observable, and — because it goes through the port — patch-emitting, so
2654
+ * history, telemetry and a future CRDT backend all see it.
2655
+ * - `events` — typed `SourceEmitter` that auto-forwards to the canvas tap.
2656
+ * - `dirty` — `DirtyBatcher` for per-frame batched flush.
2657
+ * - `visible` / `hittable` / `zIndex` / `cullable` — composition flags.
2658
+ *
2659
+ * **Lifecycle:** `mount(ctx)` → … → `unmount()`. `Canvas` calls these via the
2660
+ * `LayerRegistry`. `flush()` is called once per Canvas tick when
2661
+ * `dirty.hasPending()` is true.
2662
+ *
2663
+ * **Bulk hot data (`data`)** is NOT on the base class — it lives on subclasses
2664
+ * that need it (e.g. `GraphLayer` ships `GraphNodeStore`). See
2665
+ * `architecture-proposal.md` §2.1 for the bifurcated state/data model.
2666
+ *
2667
+ * **What subclasses provide:**
2668
+ * - `createState()` — initial UI state.
2669
+ * - `applyDirty(snap)` — translate dirty buckets → renderer commands.
2670
+ * - `onMount()` / `onUnmount()` — domain-specific setup/teardown
2671
+ * (subscribe to feeds, register decorations, etc.).
2672
+ * - `WorldLayer` / `ScreenLayer` add `hitTest(coord, coord)`.
2673
+ */
2674
+
2675
+ /**
2676
+ * The subset of `Layer` the `LayerRegistry` and `Canvas.tick` interact with.
2677
+ * Lets the registry stay decoupled from the abstract class implementation.
2678
+ */
2679
+ interface ILayer {
2680
+ readonly id: string;
2681
+ visible: boolean;
2682
+ hittable: boolean;
2683
+ zIndex: number;
2684
+ cullable: boolean;
2685
+ /** `true` between `mount(ctx)` and `unmount()`. Lets the registry skip already-mounted layers. */
2686
+ readonly mounted: boolean;
2687
+ mount(ctx: CanvasContext): void;
2688
+ unmount(): void;
2689
+ flush(): void;
2690
+ hasPending(): boolean;
2691
+ redraw(): void;
2692
+ setVisible(visible: boolean): void;
2693
+ }
2694
+ interface LayerOptions<TOptions = unknown> {
2695
+ id: string;
2696
+ options: TOptions;
2697
+ visible?: boolean;
2698
+ hittable?: boolean;
2699
+ zIndex?: number;
2700
+ /**
2701
+ * Off-screen culling participation. Default `true`. Set `false` for
2702
+ * full-canvas effect layers (background gradient, overlay) that should
2703
+ * always render regardless of camera visibility.
2704
+ */
2705
+ cullable?: boolean;
2706
+ }
2707
+ declare abstract class Layer<TOptions = unknown, TState extends object = object, TEvents extends EventMap = EventMap, TDirtyBucket extends string = string> implements ILayer {
2708
+ readonly id: string;
2709
+ /**
2710
+ * Stable **class kind** — a minification-safe discriminator matching the
2711
+ * `@invana/canvas-ui` settings-editor registry key (e.g. `'background-layer'`,
2712
+ * `'minimap-layer'`). Distinct from {@link id} (the per-instance key): all
2713
+ * `BackgroundLayer` instances share `kind: 'background-layer'`. Concrete layers
2714
+ * set it as a class field; left `undefined` on any that haven't, so consumers
2715
+ * fall back (e.g. to the class name). Lets domain-free tooling resolve an
2716
+ * instance's editor without an `instanceof` ladder.
2717
+ */
2718
+ readonly kind?: string;
2719
+ readonly options: TOptions;
2720
+ readonly events: SourceEmitter<TEvents>;
2721
+ readonly dirty: DirtyBatcher<TDirtyBucket>;
2722
+ /**
2723
+ * Backing field for {@link state}. Created on **first mount** via
2724
+ * `ctx.createStateStore` (the engine injects the reactive-store factory — this
2725
+ * package is dependency-free and cannot construct one), then kept for the
2726
+ * layer's lifetime: a remount reuses the same store, preserving state.
2727
+ */
2728
+ private _state?;
2729
+ /**
2730
+ * UI / interaction state (`ReactiveStore<TState>`). Because it is built
2731
+ * through the injected kernel factory, every write emits patches and history /
2732
+ * telemetry / a future CRDT backend all observe it.
2733
+ *
2734
+ * **Available from `mount()` onward** — accessing it before the first mount
2735
+ * throws. (`createState()` is also called at first mount, so it may safely
2736
+ * read subclass fields initialised in the subclass constructor.)
2737
+ */
2738
+ get state(): ReactiveStore<TState>;
2739
+ /** Backing field for the `visible` accessor. */
2740
+ private _visible;
2741
+ hittable: boolean;
2742
+ zIndex: number;
2743
+ cullable: boolean;
2744
+ /**
2745
+ * Whether this layer renders. Setting `false` hides the layer's pixi
2746
+ * container (via `onVisibleChange`, overridden by `WorldLayer` /
2747
+ * `ScreenLayer`) and the Canvas tick skips its flush.
2748
+ */
2749
+ get visible(): boolean;
2750
+ set visible(value: boolean);
2751
+ /**
2752
+ * Toggle whole-layer visibility, repaint, and announce it. Unlike assigning
2753
+ * `visible` (which only hides the pixi container via {@link onVisibleChange}),
2754
+ * this also forces a {@link redraw} and emits `scene:layer:visibilitychange`
2755
+ * on the canvas bus so dependent layers (minimap) and the render loop react
2756
+ * automatically. No-op if the value is unchanged.
2757
+ */
2758
+ setVisible(visible: boolean): void;
2759
+ /** Set by `mount(ctx)`; cleared by `unmount()`. */
2760
+ protected ctx?: CanvasContext;
2761
+ /** True between `mount` and `unmount`. */
2762
+ get mounted(): boolean;
2763
+ constructor(opts: LayerOptions<TOptions>);
2764
+ mount(ctx: CanvasContext): void;
2765
+ unmount(): void;
2766
+ /** Convenience accessor; throws when called pre-mount. */
2767
+ protected get context(): CanvasContext;
2768
+ /** Whether `flush()` has work to do this frame. */
2769
+ hasPending(): boolean;
2770
+ /**
2771
+ * Called by Canvas tick when `hasPending()` is true. Swaps the dirty
2772
+ * snapshot, hands it to `applyDirty`. Subclasses normally don't override.
2773
+ */
2774
+ flush(): void;
2775
+ /**
2776
+ * Force a full repaint of this layer from its current state, bypassing the
2777
+ * per-frame dirty path. Base implementation is a no-op — only layers that
2778
+ * mount a renderer override it (e.g. `GraphLayer.redraw` re-renders every
2779
+ * node and edge). Driven by {@link Canvas.redraw}; reach for it after an
2780
+ * external change that sidestepped the normal mutate-and-flush path (theme
2781
+ * swap, palette change) or to recover from a suspected render desync.
2782
+ */
2783
+ redraw(): void;
2784
+ /** Build the initial UI / interaction state. Called once in the constructor. */
2785
+ protected abstract createState(): TState;
2786
+ /**
2787
+ * Translate a dirty snapshot into renderer / pixi commands.
2788
+ * Default: no-op. Override when the layer batches work via `dirty.mark(...)`.
2789
+ */
2790
+ protected applyDirty(_snap: DirtySnapshot<TDirtyBucket>): void;
2791
+ /** Domain-specific mount setup (subscribe to peers, attach renderer, etc.). */
2792
+ protected onMount(_ctx: CanvasContext): void;
2793
+ /** Domain-specific unmount teardown. */
2794
+ protected onUnmount(_ctx: CanvasContext): void;
2795
+ /**
2796
+ * Called whenever `visible` changes (setter only — not on initial
2797
+ * construction). Subclasses override to keep their pixi container's
2798
+ * `.visible` in sync. Default: no-op.
2799
+ */
2800
+ protected onVisibleChange(_value: boolean): void;
2801
+ }
2802
+
2803
+ /**
2804
+ * `Layout` — function from data to positions.
2805
+ *
2806
+ * Architecture: see `architecture-proposal.md` §2.3.
2807
+ *
2808
+ * Per the proposal:
2809
+ * - A Layout does NOT register with the canvas.
2810
+ * - It does NOT render.
2811
+ * - It does NOT subscribe to input.
2812
+ * - You instantiate it and call it against a layer.
2813
+ *
2814
+ * const layout = new D3ForceLayout({ charge: -300 });
2815
+ * layout.events.on('end', () => canvas.camera.fitContent(...));
2816
+ * await layout.apply(graphLayer);
2817
+ *
2818
+ * Continuous-running cases (e.g. always-relax force simulation) are handled
2819
+ * by a thin wrapper Behaviour that calls `apply()` on a tick — keeps the
2820
+ * Layout API clean while supporting the rare continuous case.
2821
+ *
2822
+ * Whether two layouts conflict is a domain concern (don't apply two layouts
2823
+ * to the same data) — not enforced here.
2824
+ *
2825
+ * ## Lifecycle events
2826
+ *
2827
+ * Every layout owns a typed `events` emitter and fires three lifecycle
2828
+ * events around `apply()`:
2829
+ *
2830
+ * - `start` — emitted once, synchronously, after the layout has set up
2831
+ * its internal state and just before it begins producing positions.
2832
+ * - `tick` — emitted whenever the layout writes a fresh batch of positions.
2833
+ * One-shot layouts (e.g. ELK) fire it once. Iterative layouts (force
2834
+ * sims) fire it on every iteration. High-frequency; subscribe sparingly.
2835
+ * - `end` — emitted once when the run terminates. `reason` distinguishes
2836
+ * a natural settle from an external `stop()` call.
2837
+ *
2838
+ * Subscribe to these events to drive camera fits, progress UI, etc. —
2839
+ * instead of listening to per-tick `data:changed` on the layer, which
2840
+ * conflates "structure changed" with "positions updated".
2841
+ */
2842
+
2843
+ /**
2844
+ * Why the run ended.
2845
+ *
2846
+ * - `completed` — the layout settled / finished on its own.
2847
+ * - `stopped` — `stop()` (or a second `apply()`) cancelled it.
2848
+ */
2849
+ type LayoutEndReason = 'completed' | 'stopped';
2850
+ /**
2851
+ * Lifecycle events fired by every `Layout`.
2852
+ *
2853
+ * Subclass-specific telemetry (e.g. d3-force's `alpha`) belongs on a
2854
+ * subclass-specific event map, not here.
2855
+ */
2856
+ type LayoutEvents = {
2857
+ /**
2858
+ * Run is about to produce positions. Optional run-size / animation metadata
2859
+ * lets a `Canvas.runLayout` bridge forward it onto the canvas bus as
2860
+ * `layout:run:start` without reaching into layer internals. Every field is
2861
+ * optional — a layout that doesn't know (or care) emits `{}`, and the bridge
2862
+ * substitutes `0` / `false`.
2863
+ *
2864
+ * - `nodeCount` / `edgeCount` — size of the run, for progress UIs / telemetry.
2865
+ * - `animate` — whether the run animates its settle (iterative force sims)
2866
+ * vs. jumps straight to final positions; render policies branch on it.
2867
+ */
2868
+ start: {
2869
+ nodeCount?: number;
2870
+ edgeCount?: number;
2871
+ animate?: boolean;
2872
+ };
2873
+ tick: Record<string, never>;
2874
+ end: {
2875
+ reason: LayoutEndReason;
2876
+ };
2877
+ };
2878
+ /** Construction options every layout shares (for the `LayoutRegistry`). */
2879
+ interface LayoutOptions {
2880
+ /** Stable id, used to address the layout in a `LayoutRegistry` / config. Default `'layout'`. */
2881
+ id?: string;
2882
+ /** The layer this layout is meant to run against. Informational — `apply(layer)` still takes one explicitly. */
2883
+ targetLayerId?: string;
2884
+ }
2885
+ declare abstract class Layout<TLayer extends Layer<any, any, any, any> = Layer<any, any, any, any>> {
2886
+ /** Stable id (registry / config key). */
2887
+ readonly id: string;
2888
+ /** The layer this layout targets, if declared at construction. */
2889
+ readonly targetLayerId?: string;
2890
+ /**
2891
+ * Stable **class kind** — a minification-safe discriminator matching the
2892
+ * `@invana/canvas-ui` settings-editor registry key (e.g. `'d3-force-layout'`,
2893
+ * `'elk-layout'`). Distinct from {@link id} (the per-instance key): all
2894
+ * `D3ForceLayout` instances share `kind: 'd3-force-layout'`. Concrete layouts
2895
+ * set it as a class field; left `undefined` on any that haven't, so consumers
2896
+ * fall back (e.g. to the class name). Lets domain-free tooling resolve an
2897
+ * instance's editor without an `instanceof` ladder.
2898
+ */
2899
+ readonly kind?: string;
2900
+ /**
2901
+ * Lifecycle event bus. See class docs for the event vocabulary.
2902
+ * Subclasses with richer telemetry can declare their own typed
2903
+ * emitter on top (`override readonly events = new EventEmitter<MyEvents>()`).
2904
+ */
2905
+ readonly events: EventEmitter<LayoutEvents>;
2906
+ constructor(opts?: LayoutOptions);
2907
+ /**
2908
+ * Live-reconfigure. Called by `Canvas.update({ layouts: { id: patch } })`.
2909
+ * Default no-op; iterative layouts (e.g. `D3ForceLayout`) override to merge
2910
+ * the patch and re-heat a running simulation.
2911
+ */
2912
+ setOptions(_patch: unknown): void;
2913
+ /**
2914
+ * Contribute this layout's serialisable config to a canvas-state snapshot (the
2915
+ * engine's `DefinitionSerializable` contract). The base captures the wiring
2916
+ * `targetLayerId`; iterative layouts holding tunable params (e.g. force
2917
+ * strengths) should override and spread `super.serializeDefinition()` with a
2918
+ * JSON-safe copy of those params.
2919
+ */
2920
+ serializeDefinition(): Record<string, unknown> | undefined;
2921
+ /**
2922
+ * Run the layout against `layer`. Resolves when the run terminates
2923
+ * (either a natural settle or an external `stop()`).
2924
+ *
2925
+ * Calling `apply()` again on the same instance must cancel any in-flight
2926
+ * run first.
2927
+ */
2928
+ abstract apply(layer: TLayer): Promise<void>;
2929
+ }
2930
+
2931
+ /**
2932
+ * `LayoutRegistry` — stores the Layouts registered on a Canvas, addressed by id.
2933
+ *
2934
+ * Simpler than `LayerRegistry` / `BehaviourRegistry`: layouts aren't mounted,
2935
+ * z-ordered, or wired to input — they're held so `Canvas.update()` can push
2936
+ * config to them by id and consumers can fetch + `apply()` them. A graph runs
2937
+ * one layout at a time, but several may be registered (e.g. a layout picker).
2938
+ */
2939
+
2940
+ interface LayoutRegistryOptions {
2941
+ bus: CanvasEventBus;
2942
+ }
2943
+ declare class LayoutRegistry {
2944
+ private readonly layouts;
2945
+ private readonly bus;
2946
+ constructor(opts: LayoutRegistryOptions);
2947
+ get size(): number;
2948
+ /** Register a layout. Fires `layout:added`. Throws on duplicate id. */
2949
+ add(layout: Layout): void;
2950
+ /** Remove a layout, stopping it first if it exposes `stop()`. Fires `layout:removed`. */
2951
+ remove(id: string): void;
2952
+ get<T extends Layout = Layout>(id: string): T | undefined;
2953
+ has(id: string): boolean;
2954
+ list(): readonly Layout[];
2955
+ /** Stop + drop every layout. Called on Canvas destroy. */
2956
+ clear(): void;
2957
+ }
2958
+
2959
+ /**
2960
+ * `ICameraBinding` with no backend behind it.
2961
+ *
2962
+ * The projection math mirrors the engine's coordinate model exactly
2963
+ * (`screen = world * zoom + offset`), so camera semantics — clamping, anchored
2964
+ * zoom, fit, the bus and store sync — are exercisable with no GPU.
2965
+ * `emitTransformChange` simulates a backend-driven gesture (a wheel tick, a
2966
+ * momentum glide), the one path `Camera` cannot trigger itself.
2967
+ *
2968
+ * Shipped rather than test-only: §7 keeps a headless backend deliberately, so
2969
+ * consumers can test layouts, picking and projection without a renderer.
2970
+ */
2971
+
2972
+ declare class HeadlessCameraBinding implements ICameraBinding {
2973
+ private t;
2974
+ private screenWidth;
2975
+ private screenHeight;
2976
+ private readonly changeListeners;
2977
+ private readonly dragStartListeners;
2978
+ /** Every `configureInput` patch received, in order — for asserting input wiring. */
2979
+ readonly inputConfigs: CameraInputConfig[];
2980
+ /** Latest `setDragSuspended` value. */
2981
+ dragSuspended: boolean;
2982
+ /** Accumulated `tick` time, to prove the engine drives the clock. */
2983
+ tickedMs: number;
2984
+ constructor(screenWidth?: number, screenHeight?: number);
2985
+ getTransform(): CameraTransformValue;
2986
+ setTransform(t: CameraTransformValue): void;
2987
+ zoomToCentre(zoom: number): void;
2988
+ resize(screenWidth: number, screenHeight: number): void;
2989
+ toWorld(screenX: number, screenY: number): Point;
2990
+ toScreen(worldX: number, worldY: number): Point;
2991
+ getVisibleBounds(): Rect;
2992
+ configureInput(config: CameraInputConfig): void;
2993
+ setDragSuspended(suspended: boolean): void;
2994
+ onTransformChange(fn: (kind: CameraChangeKind) => void): () => void;
2995
+ onDragStart(fn: () => void): () => void;
2996
+ tick(dtMs: number): void;
2997
+ /** Simulate a backend-driven transform change (wheel, drag, momentum). */
2998
+ emitTransformChange(t: CameraTransformValue, kind: CameraChangeKind): void;
2999
+ /** Simulate the backend reporting the start of a drag-pan. */
3000
+ emitDragStart(): void;
3001
+ }
3002
+
3003
+ /**
3004
+ * `HeadlessRenderer` — a complete `IRenderer` that draws nothing.
3005
+ *
3006
+ * Not a product renderer: a **test double**, kept deliberately (§7) so layouts,
3007
+ * picking, bounds, spec projection and the whole layer / behaviour lifecycle can
3008
+ * be exercised with no GPU and no DOM. It is why `@invana/canvas` needs a
3009
+ * drawing library neither as a dependency nor a devDependency.
3010
+ *
3011
+ * It doubles as the reference for how small the contract really is: if a new
3012
+ * feature means adding a method here that cannot be implemented without pixels,
3013
+ * that method belongs on a concrete backend, not on `IRenderer`.
3014
+ *
3015
+ * ```ts
3016
+ * const canvas = new Canvas();
3017
+ * canvas.initWithRenderer(new HeadlessRenderer(), 800, 600);
3018
+ * ```
3019
+ */
3020
+
3021
+ /**
3022
+ * An `IElementRenderer` that tracks which ids exist and their specs, and
3023
+ * answers geometry from the spec alone. Enough for a layer test to assert that
3024
+ * elements were mounted, moved and removed.
3025
+ */
3026
+ declare class HeadlessElementRenderer implements IElementRenderer {
3027
+ readonly events: EventEmitter<ElementEventMap>;
3028
+ readonly shapes: Map<string, {
3029
+ kind: string;
3030
+ x: number;
3031
+ y: number;
3032
+ }>;
3033
+ readonly connectors: Set<string>;
3034
+ readonly shapeKinds: Set<string>;
3035
+ registerShape(kind: string): void;
3036
+ getShapeKind(id: string): string | undefined;
3037
+ hasShape(id: string): boolean;
3038
+ hasConnector(id: string): boolean;
3039
+ addShape(id: string, spec: {
3040
+ kind: string;
3041
+ x?: number;
3042
+ y?: number;
3043
+ }): void;
3044
+ updateShape(id: string, patch: {
3045
+ x?: number;
3046
+ y?: number;
3047
+ }): void;
3048
+ removeShape(id: string): void;
3049
+ addConnector(id: string): void;
3050
+ updateConnector(): void;
3051
+ removeConnector(id: string): void;
3052
+ moveShape(id: string, x: number, y: number): void;
3053
+ getShapePosition(id: string): {
3054
+ x: number;
3055
+ y: number;
3056
+ } | null;
3057
+ scaleShape(): void;
3058
+ setConnectorStroke(): void;
3059
+ scaleConnectorStroke(): void;
3060
+ setRaised(): void;
3061
+ setShapeTextVisible(): void;
3062
+ setShapeIconVisible(): void;
3063
+ setShapeImageVisible(): void;
3064
+ setLabelsResolution(): void;
3065
+ setVisibleSet(): void;
3066
+ cull(): void;
3067
+ uncull(): void;
3068
+ setDecoration(): void;
3069
+ setEffect(): void;
3070
+ getDecoration(): undefined;
3071
+ setDecorationVisible(): void;
3072
+ getDecorationWorldBounds(): null;
3073
+ setBadge(): void;
3074
+ removeBadge(): void;
3075
+ getShapeWorldBounds(): null;
3076
+ getShapeCenter(): null;
3077
+ getConnectorPolyline(): null;
3078
+ connectorGeometryUnchanged(): boolean;
3079
+ /**
3080
+ * Pure geometry, answered for real: the kernel's spec-geometry covers every
3081
+ * built-in kind, so a headless canvas measures node footprints exactly like
3082
+ * a drawing backend would (`GraphLayer.boundsOfNode`, minimap estimates,
3083
+ * ELK size queries — and `getBounds()`'s store-derived fit box — all work
3084
+ * with no GPU). `undefined` only for unregistered third-party kinds.
3085
+ */
3086
+ boundsOfSpec(spec: {
3087
+ readonly kind: string;
3088
+ }): Rect | undefined;
3089
+ scaleShapeSpec(): undefined;
3090
+ collapsedShapeSpec(): undefined;
3091
+ fitShapeSpecToContent(): undefined;
3092
+ measureLabel(): null;
3093
+ hitTest(): null;
3094
+ setHitTestEnabled(): void;
3095
+ reindexScaledShapeHits(): void;
3096
+ reanchorAllConnectors(): void;
3097
+ reRouteAllConnectors(): void;
3098
+ tickAnimations(): void;
3099
+ toSVG(): string;
3100
+ destroy(): void;
3101
+ }
3102
+ declare class HeadlessSurface implements ISurface {
3103
+ readonly id: string;
3104
+ readonly space: SurfaceSpace;
3105
+ readonly primitives: HeadlessElementRenderer;
3106
+ /** Last backdrop pushed — lets a background test assert without pixels. */
3107
+ backdrop: SurfaceBackdrop | null;
3108
+ visible: boolean;
3109
+ zIndex: number;
3110
+ destroyed: boolean;
3111
+ constructor(id: string, space: SurfaceSpace);
3112
+ overlay(): IOverlayDevice;
3113
+ setBackdrop(backdrop: SurfaceBackdrop | null): void;
3114
+ setVisible(visible: boolean): void;
3115
+ setZIndex(z: number): void;
3116
+ destroy(): void;
3117
+ }
3118
+ declare class HeadlessRenderer implements IRenderer {
3119
+ readonly backend: "canvas";
3120
+ readonly canvasElement: HTMLCanvasElement | null;
3121
+ /** Every surface handed out, by layer id — for asserting layer lifecycle. */
3122
+ readonly surfaces: Map<string, HeadlessSurface>;
3123
+ readonly binding: HeadlessCameraBinding;
3124
+ camera?: Camera;
3125
+ destroyed: boolean;
3126
+ /** Every `tick(dt)` the engine drove, in order. */
3127
+ readonly frames: number[];
3128
+ get capabilities(): RendererCapabilities;
3129
+ mount(): void;
3130
+ createSurface(space: SurfaceSpace, id: string): ISurface;
3131
+ createOverlay(): IOverlayDevice;
3132
+ createCameraBinding(): ICameraBinding;
3133
+ attachCamera(camera: Camera): void;
3134
+ worldContentBounds(): Rect | null;
3135
+ resize(): void;
3136
+ /** Records the frames the engine drove, so a test can assert the clock ran. */
3137
+ tick(dtMs: number): void;
3138
+ destroy(): void;
3139
+ }
3140
+
3141
+ /**
3142
+ * Default anchor — resolves a shape endpoint to the shape's bounding-box
3143
+ * **centre** in world space. Uses `ref.center` (computed by the renderer
3144
+ * from `origin + bounds`) rather than the raw `(spec.x, spec.y)` origin so
3145
+ * the anchor is uniform regardless of each shape's local-origin convention
3146
+ * (`RectShape` is anchored top-left; `CircleShape` is centred).
3147
+ *
3148
+ * Ignores `fromPoint`; the centre never depends on the other endpoint.
3149
+ */
3150
+ declare const centerAnchor: IAnchor;
3151
+
3152
+ /**
3153
+ * Boundary anchor — snaps the endpoint onto the shape silhouette where the
3154
+ * ray from the shape's geometric **centre** toward the *other* endpoint
3155
+ * exits.
3156
+ *
3157
+ * The ray is cast from `ref.center` (the bounding-box centre, computed by
3158
+ * the renderer from `origin + bounds`) rather than from `ref.origin` so the
3159
+ * behaviour is uniform regardless of each shape's local-origin convention.
3160
+ * `RectShape` is anchored top-left, `CircleShape` is centred — `ref.center`
3161
+ * normalises the difference.
3162
+ *
3163
+ * Calls the shape's optional `boundaryIntersect(localFromCenter)` for
3164
+ * analytical shapes (`CircleShape` overrides). For shapes that don't
3165
+ * override, falls back to a centred-AABB ray-exit (provided by
3166
+ * `ShapeBase.boundaryIntersect`). The input is centre-relative; the output
3167
+ * is centre-relative; this anchor converts back to world via `ref.center`.
3168
+ *
3169
+ * Sets an outward-pointing `tangent` on the returned endpoint (unit vector
3170
+ * from shape centre to the boundary point) so port-aware routers can use it
3171
+ * as an exit-direction hint.
3172
+ */
3173
+ declare const boundaryAnchor: IAnchor;
3174
+
3175
+ /**
3176
+ * Perpendicular anchor — exits at the **midpoint of the face** of the
3177
+ * shape's bounding box that is closest to the other endpoint. The face is
3178
+ * picked by comparing `|dx| / halfWidth` against `|dy| / halfHeight`: the
3179
+ * ratio that's larger wins (so a target slightly to the right of a wide,
3180
+ * short rect still picks the right side; a tall, narrow rect picks the top
3181
+ * or bottom more readily).
3182
+ *
3183
+ * Best for **orth-style routing** (`orth`, `manhattan`, `metro`, `er`,
3184
+ * `oneSide`) where the natural exit is along one cardinal axis. Produces
3185
+ * the "lines start at the middle of a side" look common in flowcharts and
3186
+ * ER diagrams.
3187
+ *
3188
+ * For circles (square bounds), this lands at the cardinal points
3189
+ * (N / S / E / W) on the perimeter — a useful default though `boundary`
3190
+ * still gives smoother diagonal exits for non-orthogonal routers.
3191
+ *
3192
+ * Sets the outward tangent to the face normal: `(±1, 0)` for left/right
3193
+ * faces, `(0, ±1)` for top/bottom. Routers like `orth` consume this to
3194
+ * pick H-first vs V-first.
3195
+ */
3196
+ declare const perpendicularAnchor: IAnchor;
3197
+
3198
+ declare const edgePortAnchor: IAnchor;
3199
+
3200
+ declare const silhouettePortAnchor: IAnchor;
3201
+
3202
+ /**
3203
+ * Direct line from source through any waypoints to target.
3204
+ * Output: `[source, ...waypoints, target]` — a flat polyline.
3205
+ *
3206
+ * Routers decide topology (where bends sit). The visual style of segments
3207
+ * between these points is owned by the downstream `PathStyle`:
3208
+ * - `normal` → straight segments (`M, L, L, …`)
3209
+ * - `rounded` → quadratic fillets at corners
3210
+ * - `smooth` → Catmull-Rom cubic spline
3211
+ * - `bezier` → single cubic A→B (intermediate points ignored)
3212
+ */
3213
+ declare const straightRouter: IRouter;
3214
+
3215
+ /**
3216
+ * Orth router — produces a polyline made of horizontal and vertical
3217
+ * segments only. Simple, geometric, **no obstacle awareness**: pick this
3218
+ * for clean H/V routing in layouts you trust to have no shapes in the way.
3219
+ * For obstacle avoidance, use `manhattan` (which is built on top of A*).
3220
+ *
3221
+ * Naming follows X6 / JointJS / mxGraph: their `Orth` is also the simple
3222
+ * H/V router, while their `Manhattan` is the obstacle-aware variant.
3223
+ *
3224
+ * For each consecutive pair `(P, Q)` of `[source, ...waypoints, target]`,
3225
+ * one bend point is inserted (producing an L-shape for that pair). The bend
3226
+ * direction (H-first vs V-first) is chosen by:
3227
+ *
3228
+ * 1. **Source tangent** on the first segment — the line exits along the
3229
+ * tangent's dominant axis. The boundary anchor sets this as an outward
3230
+ * normal hint.
3231
+ * 2. **Target tangent** on the last segment — the line approaches matching
3232
+ * the tangent's dominant axis (so the final leg is perpendicular to the
3233
+ * target boundary).
3234
+ * 3. **Alternation** in between — alternate H ↔ V across consecutive
3235
+ * segments to avoid back-tracking.
3236
+ * 4. **Dominant axis** as a final fallback when no other signal applies.
3237
+ *
3238
+ * Aligned consecutive points (same x or same y) emit no bend.
3239
+ */
3240
+ declare const orthRouter: IRouter;
3241
+
3242
+ /**
3243
+ * Manhattan router — H/V segments only, **routing around obstacles when
3244
+ * necessary**.
3245
+ *
3246
+ * Naming follows X6 / JointJS / mxGraph where `Manhattan` is the
3247
+ * obstacle-aware variant and `Orth` is the simple non-avoiding one.
3248
+ *
3249
+ * Pipeline (lazy A*):
3250
+ * 1. Compute the simple `orthRouter` polyline first (single L-bend or
3251
+ * tangent-aware Z-bend).
3252
+ * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline
3253
+ * crosses an inflated obstacle, return it directly. Same output as the
3254
+ * `orth` router — clean, no stair-stepping.
3255
+ * 3. Otherwise build a coarse `ObstacleGrid` and run A* (connectivity 4)
3256
+ * from source cell to target cell. Simplify the cell path to bend
3257
+ * points only and convert back to world coordinates.
3258
+ *
3259
+ * Failure cases all fall back to the simple `orthRouter` polyline:
3260
+ * - Grid construction returns `null` (cell-count cap exceeded).
3261
+ * - A* finds no path (source/target unreachable through inflated obstacles).
3262
+ *
3263
+ * The fallback emits a `console.warn` so the dev sees why avoidance didn't
3264
+ * kick in; toggle `routerOpts.obstacles: 'none'` to skip the obstacle check
3265
+ * entirely.
3266
+ *
3267
+ * Waypoints are not yet threaded through A* — when present, the simple orth
3268
+ * polyline (which respects waypoints) is checked against obstacles. If it's
3269
+ * clear, return it; if not, A* runs between source and target only.
3270
+ * Routing through waypoints with obstacle awareness is a future extension.
3271
+ */
3272
+ declare const manhattanRouter: IRouter;
3273
+
3274
+ /**
3275
+ * Metro router — manhattan-style topology with 45° diagonals.
3276
+ *
3277
+ * Pipeline (lazy A*):
3278
+ * 1. Compute the simple geometric metro polyline first — one straight
3279
+ * axis-aligned leg followed by a 45° diagonal absorbing the remaining
3280
+ * distance. Mirrors classic transit-map line drawing.
3281
+ * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline
3282
+ * crosses an inflated obstacle, return it directly.
3283
+ * 3. Otherwise run A* with **connectivity 8** (H + V + 45° moves) on a
3284
+ * coarse grid. Simplify cell runs and convert back to world coords.
3285
+ *
3286
+ * Connectivity 8 is what makes this metro-shaped: diagonal cost `√2` is
3287
+ * cheaper than two cardinals (`1 + 1 = 2`), so A* prefers 45° moves where
3288
+ * obstacles permit — producing the metro look around obstacles too.
3289
+ */
3290
+ declare const metroRouter: IRouter;
3291
+
3292
+ /**
3293
+ * ER (entity-relationship) router — exits each endpoint perpendicular to
3294
+ * its boundary, then routes orthogonally between the stub points.
3295
+ *
3296
+ * Reads the outward `tangent` set by the `boundary` anchor on each endpoint.
3297
+ * Each stub leg is `tangent * stubLength`. The bridge between stubs is a
3298
+ * single H-or-V segment plus one bend, picked so the bend axis alternates
3299
+ * with each stub direction (horizontal stubs → vertical bridge first).
3300
+ *
3301
+ * Falls back to a single bend (manhattan-equivalent) when neither endpoint
3302
+ * has a tangent. Waypoints are inserted between the stubs as plain
3303
+ * polyline points (no extra orthogonalisation pass).
3304
+ */
3305
+ declare const erRouter: IRouter;
3306
+
3307
+ /**
3308
+ * oneSide router — forces the line to exit the source on a designated side,
3309
+ * then routes orthogonally to the target. Useful for swimlane / "all on one
3310
+ * side" diagrams where every connector must leave the source in the same
3311
+ * direction regardless of where the target is.
3312
+ *
3313
+ * Polyline shape:
3314
+ * `source → exit → midBend → target`
3315
+ *
3316
+ * - `exit` — source stepped `padLength` along the side direction.
3317
+ * - `midBend` — perpendicular to the side at the target's parallel axis
3318
+ * (so the leg from exit→midBend is along the side direction
3319
+ * inverted, and midBend→target is perpendicular).
3320
+ *
3321
+ * For 'right' / 'left' the exit/midBend legs are horizontal then vertical;
3322
+ * for 'top' / 'bottom' they're vertical then horizontal. When source and
3323
+ * target are perfectly aligned with the side direction the path collapses
3324
+ * to a single-leg traversal.
3325
+ *
3326
+ * Waypoints are not honoured by this router — its purpose is the forced
3327
+ * exit, not free-form routing. Pass `manhattan` for waypoint routing.
3328
+ */
3329
+ declare const oneSideRouter: IRouter;
3330
+
3331
+ /**
3332
+ * Sharp segments. Walks the polyline emitting `M` then `L L L …`.
3333
+ *
3334
+ * For a 2-point polyline, this is `[M source, L target]` — equivalent to
3335
+ * the straight-line baseline. For an N-point polyline (router-produced
3336
+ * bends), this draws straight segments between every consecutive pair with
3337
+ * no corner treatment.
3338
+ */
3339
+ declare const normalPathStyle: IPathStyle;
3340
+
3341
+ /**
3342
+ * Quadratic arc fillets at every interior polyline corner.
3343
+ *
3344
+ * For each interior corner B between segments A→B and B→C:
3345
+ * - Pick a per-corner radius `t = min(radius, |AB|/2, |BC|/2)`.
3346
+ * - Approach point P1 on segment AB at distance `t` from B.
3347
+ * - Departure point P2 on segment BC at distance `t` from B.
3348
+ * - Emit `L P1`, then `Q B P2` — the corner becomes a quadratic with control
3349
+ * at the original corner.
3350
+ *
3351
+ * For a 2-point polyline (no interior corners) the output is identical to
3352
+ * `normal`: `[M, L]`. Collinear corners (parallel incoming/outgoing) emit a
3353
+ * straight `L` through B with no Q (degenerate fillet).
3354
+ */
3355
+ declare const roundedPathStyle: IPathStyle;
3356
+
3357
+ /**
3358
+ * Single cubic Bézier between the first and last polyline points, with
3359
+ * auto-generated control handles. Intermediate polyline points (router
3360
+ * waypoints, manhattan corners, …) are **ignored** — pick `smooth` if you
3361
+ * want the path to follow them.
3362
+ *
3363
+ * Control-point strategy: direction-aware s-curve.
3364
+ * - For horizontal-dominant layouts the controls pull horizontally:
3365
+ * `c1 = source + (dx * tension, 0)`, `c2 = target - (dx * tension, 0)`.
3366
+ * Source leaves and target arrives along the x-axis.
3367
+ * - For vertical-dominant layouts the controls pull vertically.
3368
+ *
3369
+ * Output: `[M source, C target]` — a single curve segment.
3370
+ */
3371
+ declare const bezierPathStyle: IPathStyle;
3372
+
3373
+ /**
3374
+ * Quadratic Bézier from the first polyline point to the last with a single
3375
+ * control point placed **perpendicular to the chord** at `curvePosition`
3376
+ * along it and `curveOffset` units to the side.
3377
+ *
3378
+ * This is the G6-style "quadratic edge": one control point, signed
3379
+ * perpendicular offset, fixed position along the chord. Unlike axis-aligned
3380
+ * `bezier` (whose control handles pull along `axis: 'h' | 'v'`), the
3381
+ * perpendicular construction gives a real bow on **every** orientation —
3382
+ * cardinal chords no longer collapse to straight lines.
3383
+ *
3384
+ * Pair with `router: 'straight'`; intermediate polyline waypoints are
3385
+ * ignored (a router that produces extra points doesn't compose
3386
+ * meaningfully with a single-control-point quadratic).
3387
+ *
3388
+ * Edge cases:
3389
+ * - Polyline shorter than two points → `[]` (matches the other pathStyles).
3390
+ * - Coincident endpoints (`len === 0`) → degenerate `M` only; the
3391
+ * perpendicular is undefined.
3392
+ */
3393
+ declare const quadraticPathStyle: IPathStyle;
3394
+
3395
+ /**
3396
+ * Single cubic Bézier from the first to the last polyline point with control
3397
+ * points placed on the **midradius circle** at the source and target angles.
3398
+ *
3399
+ * This is the same curve `d3.linkRadial()` produces, ported to operate on
3400
+ * cartesian polyline endpoints (we recover the polar coordinates from the
3401
+ * configured origin). It gives a tree edge that:
3402
+ * - leaves the source tangent to the radius (radially outward / inward),
3403
+ * - sweeps through the midradius arc between the two angles,
3404
+ * - arrives at the target tangent to the radius.
3405
+ *
3406
+ * The result reads correctly in any orientation — it doesn't bulge sideways
3407
+ * the way an axis-aligned `bezier` does on near-vertical edges. Pair with
3408
+ * `router: 'straight'`; intermediate polyline waypoints are ignored (a
3409
+ * router that produces extra points doesn't compose meaningfully with a
3410
+ * polar curve).
3411
+ *
3412
+ * Edge cases:
3413
+ * - Co-linear with the origin (`r0` or `r1` is zero, or both angles equal):
3414
+ * falls back to a straight line, since a polar curve isn't defined.
3415
+ * - Polyline shorter than two points: returns `[]` (matches other styles).
3416
+ */
3417
+ declare const bumpRadialPathStyle: IPathStyle;
3418
+
3419
+ /**
3420
+ * Single cubic Bézier from the first to the last polyline point.
3421
+ *
3422
+ * Two modes depending on whether anchor `endpoints` are passed in:
3423
+ *
3424
+ * - **Tangent-aware (preferred)** — when `endpoints.source.tangent` and / or
3425
+ * `endpoints.target.tangent` are available, the control points are placed
3426
+ * along each shape's outward surface normal: `c1 = s + sTan × handle`,
3427
+ * `c2 = t + tTan × handle`, with `handle = |tx − sx| / 2`. The curve
3428
+ * therefore leaves the source flush with its silhouette tangent and
3429
+ * arrives at the target flush with *its* silhouette tangent — no kink
3430
+ * at off-equator anchors (circles, polygons, rounded rects).
3431
+ *
3432
+ * - **Fallback** — when no tangents are available (direct unit-test
3433
+ * invocation, or an anchor that produced no tangent), the control
3434
+ * points fall back to the **vertical midline** between source and
3435
+ * target — `c1 = ((sx + tx)/2, sy)` and `c2 = ((sx + tx)/2, ty)` —
3436
+ * matching d3-shape's `linkHorizontal()` / d3-sankey's
3437
+ * `sankeyLinkHorizontal()` ribbon curve. For rect + horizontal-face
3438
+ * anchors (`edge-port` on `'left'` / `'right'`) the tangent-aware
3439
+ * formula reduces to this same placement, so existing rect-on-rect
3440
+ * visuals are unchanged.
3441
+ *
3442
+ * Pair with `router: 'straight'`; intermediate polyline waypoints are
3443
+ * ignored (a router that produces extra points doesn't compose
3444
+ * meaningfully with a horizontal-bump curve).
3445
+ *
3446
+ * Edge cases:
3447
+ * - Polyline shorter than two points → `[]` (matches the other pathStyles).
3448
+ * - `sx === tx` (vertical link) → tangent-aware path uses `handle = 0`,
3449
+ * collapsing both control points onto the endpoints (a straight line);
3450
+ * fallback degenerates to a vertical line on `x = sx`. Both stay
3451
+ * well-defined.
3452
+ */
3453
+ declare const bumpHorizontalPathStyle: IPathStyle;
3454
+
3455
+ /**
3456
+ * Catmull-Rom spline through every polyline point, emitted as cubic Béziers.
3457
+ * The curve passes through every input point exactly; intermediate router
3458
+ * waypoints / manhattan corners become smoothly interpolated bends.
3459
+ *
3460
+ * For each segment `Pi → Pi+1`, the control points use Catmull-Rom to Bézier
3461
+ * conversion:
3462
+ * `c1 = Pi + (Pi+1 - Pi-1) * tension / 6`
3463
+ * `c2 = Pi+1 - (Pi+2 - Pi) * tension / 6`
3464
+ *
3465
+ * At the endpoints, the missing virtual neighbour is mirrored
3466
+ * (`P-1 = P0`, `Pn+1 = Pn`).
3467
+ *
3468
+ * For a 2-point polyline this produces a single cubic with collinear control
3469
+ * points — visually identical to a straight line.
3470
+ */
3471
+ declare const smoothPathStyle: IPathStyle;
3472
+
3473
+ /**
3474
+ * Two-segment **radial step** (a.k.a. "elbow") link, matching the d3
3475
+ * `linkStep` helper used by the canonical Tree of Life example:
3476
+ *
3477
+ * 1. Circular **arc** at the source's radius from the source angle to the
3478
+ * target angle (constant-radius sweep along the parent's tier).
3479
+ * 2. Straight **radial line** outward from there to the target.
3480
+ *
3481
+ * Visually this produces the boxy / angular cluster-dendrogram look — every
3482
+ * subtree fans out from a horizontal arc at its parent's radius, then shoots
3483
+ * outward as straight spokes. It's the right pick for radial *clusters*
3484
+ * (where all leaves sit on a single outer rim and the eye reads tiers via
3485
+ * the constant-radius arcs); the smooth {@link bumpRadialPathStyle} is the
3486
+ * right pick for radial *trees* (where edges should curve continuously).
3487
+ *
3488
+ * The arc is approximated with cubic Bézier sub-arcs (≤ 90° each) using the
3489
+ * standard `k = (4/3) tan(θ/4) r` handle-length formula — visually
3490
+ * indistinguishable from a true SVG `A` command at any zoom, and stays a
3491
+ * flat sequence of `M / C / L` commands the Pixi renderer already knows
3492
+ * how to consume.
3493
+ *
3494
+ * Pair with `router: 'straight'`; intermediate polyline waypoints are
3495
+ * ignored. Use `anchor: 'center'` on the edge so the tangent is computed
3496
+ * from the true node-centre angle (otherwise the arc would launch from the
3497
+ * trimmed boundary cut-point and read crooked).
3498
+ *
3499
+ * Edge cases:
3500
+ * - `r0 === 0` (source at the origin): emits a single straight `M → L`.
3501
+ * - Source / target angles equal (single-child clade, or angular wrap
3502
+ * collapses to zero): emits a straight radial `M → L`.
3503
+ * - Polyline shorter than two points: returns `[]`.
3504
+ */
3505
+ declare const stepRadialPathStyle: IPathStyle;
3506
+
3507
+ /**
3508
+ * Hierarchical-edge-bundling curve through the polyline, emitted as cubic
3509
+ * Béziers. This is the d3-shape `curveBundle.beta(β)` shape: an open cubic
3510
+ * B-spline driven by control points that are β-blended toward the straight
3511
+ * line from `P_0` to `P_{n-1}`.
3512
+ *
3513
+ * Pair with `router: 'straight'` and feed the hierarchy-ancestor sequence as
3514
+ * `waypoints` on the connector spec (per-edge layout output); the router will
3515
+ * pass `[source, ...waypoints, target]` through unchanged, and this pathStyle
3516
+ * sees the full sequence.
3517
+ *
3518
+ * Reference: d3-shape `src/curve/bundle.js` + `src/curve/basis.js`.
3519
+ */
3520
+ declare const bundlePathStyle: IPathStyle;
3521
+
3522
+ /**
3523
+ * Self-loop pathStyle — orthogonal polyline anchored at the first
3524
+ * polyline point. Designed for edges where source and target reference
3525
+ * the same shape; the router output is `[p, p]` and this style ignores
3526
+ * everything after `polyline[0]`.
3527
+ *
3528
+ * Two geometries dispatch on `side`:
3529
+ *
3530
+ * **Cardinal U-bracket** (`top` / `right` / `bottom` / `left` or any
3531
+ * numeric angle) — three segments. Feet sit on a chord perpendicular
3532
+ * to `side` at distance `baseOffset` from the pivot, separated by
3533
+ * `gap`. From each foot the path runs `stubLength` further along
3534
+ * `side` to the two outer corners, joined by one cross segment.
3535
+ *
3536
+ * **Corner wrap** (`top-right` / `bottom-right` / `bottom-left` /
3537
+ * `top-left`) — four segments. Both feet sit on the host silhouette:
3538
+ * one on the horizontal edge `gap` from the named corner, the other
3539
+ * on the vertical edge `gap` from the same corner. From each foot the
3540
+ * path runs `stubLength` perpendicular to its edge (outward), the two
3541
+ * outward stubs are joined by a cross segment past the corner, and the
3542
+ * arrow lands flush with the perpendicular edge. The wrap's inner
3543
+ * corner sits at `(±baseOffsetX, ±baseOffsetY)` from the pivot.
3544
+ *
3545
+ * Pair with `router: 'straight'`; the polyline content beyond the first
3546
+ * point is ignored.
3547
+ *
3548
+ * Edge cases:
3549
+ * - Polyline shorter than one point: returns `[]`.
3550
+ * - Cardinal `gap = 0`: both stubs collapse onto the same line — the
3551
+ * loop reads as a single out-and-back spike.
3552
+ * - Corner `gap = 0`: both feet land at the corner itself; the wrap
3553
+ * degenerates to a closed rectangle whose inner corner touches the
3554
+ * silhouette.
3555
+ */
3556
+ declare const loopPolylinePathStyle: IPathStyle;
3557
+
3558
+ /**
3559
+ * Named loop-curve shape presets. Each preset carries the four
3560
+ * profile-shaping opts (`baseOffset`, `radius`, `width`, `bulge`); the
3561
+ * caller fills in placement (`side` / `angle`, `pivotOffset`) per
3562
+ * instance. Spread into `pathStyleOpts`:
3563
+ *
3564
+ * pathStyleOpts: { ...LOOP_CURVE_PRESETS.balloon, side: 'top' }
3565
+ *
3566
+ * Definitions:
3567
+ * - `balloon` — fat puffed belly. `bulge >> width/2` → controls
3568
+ * splay wide; `bulge > radius` → belly bulges past the tip.
3569
+ * - `teardrop` — slender pointed petal. `radius >> bulge`, narrow
3570
+ * `width` → long axis with controls converging toward the tip.
3571
+ * - `ring` — near-circular loop. `radius ≈ bulge`, modest neck.
3572
+ * - `hairpin` — parallel-sided U (legacy). `bulge ≈ width/2` →
3573
+ * controls sit directly above the feet, no flare.
3574
+ */
3575
+ declare const LOOP_CURVE_PRESETS: {
3576
+ readonly balloon: {
3577
+ readonly baseOffset: 2;
3578
+ readonly radius: 22;
3579
+ readonly width: 6;
3580
+ readonly bulge: 26;
3581
+ };
3582
+ readonly teardrop: {
3583
+ readonly baseOffset: 2;
3584
+ readonly radius: 34;
3585
+ readonly width: 4;
3586
+ readonly bulge: 8;
3587
+ };
3588
+ readonly ring: {
3589
+ readonly baseOffset: 2;
3590
+ readonly radius: 20;
3591
+ readonly width: 10;
3592
+ readonly bulge: 20;
3593
+ };
3594
+ readonly hairpin: {
3595
+ readonly baseOffset: 2;
3596
+ readonly radius: 28;
3597
+ readonly width: 8;
3598
+ readonly bulge: 4;
3599
+ };
3600
+ };
3601
+ type LoopCurvePresetName = keyof typeof LOOP_CURVE_PRESETS;
3602
+ /**
3603
+ * Self-loop pathStyle — single cubic Bézier "balloon / petal / teardrop"
3604
+ * drawn between two foot points. Mirrors AntV G6's `loop-curve` placement
3605
+ * model: cardinal placements (`top`, `right`, `bottom`, `left`) put both
3606
+ * feet on the same edge of the host; diagonal placements (`top-right`,
3607
+ * `bottom-right`, `bottom-left`, `top-left`) put the two feet on the two
3608
+ * adjacent edges that meet at the named corner.
3609
+ *
3610
+ * The path style runs in one of two modes depending on the polyline it
3611
+ * receives:
3612
+ *
3613
+ * - **Two-foot mode** (preferred): when `polyline[0]` and `polyline[N-1]`
3614
+ * are distinct (chord length > {@link COINCIDENT_EPS}), they are used
3615
+ * as the two feet. The caller positions them via anchors — typically
3616
+ * an `edge-port` anchor on the source endpoint and another on the
3617
+ * target endpoint. The path style only shapes the curve between them.
3618
+ *
3619
+ * - **Single-pivot mode** (legacy): when the two endpoints coincide
3620
+ * (typical when both source and target use the `center` anchor on the
3621
+ * same shape), the feet are synthesised from `pivotOffset`,
3622
+ * `baseOffset` and `width`. `baseOffset` shifts the foot midpoint
3623
+ * along `angle`; `width` separates the feet perpendicular to it.
3624
+ * Useful when no edge-port anchor is configured.
3625
+ *
3626
+ * Geometry (both modes): given two feet `start` and `end`, the tip sits
3627
+ * at `chordMid + bloom * radius`, and the two cubic control points are
3628
+ * placed at `tip ± chordDir * bulge`. `bulge > chordLen/2` → balloon
3629
+ * (controls splayed outward past the feet); `bulge = chordLen/2` →
3630
+ * parallel-sided U; `bulge < chordLen/2` → teardrop (controls converge).
3631
+ *
3632
+ * Pair with `router: 'straight'`. The polyline content between
3633
+ * `polyline[0]` and `polyline[N-1]` is ignored.
3634
+ *
3635
+ * Edge cases:
3636
+ * - Polyline shorter than one point: returns `[]`.
3637
+ * - `width = 0` in single-pivot mode: feet coincide → closed teardrop
3638
+ * cusp; the arrow marker lands on the start point.
3639
+ */
3640
+ declare const loopCurvePathStyle: IPathStyle;
3641
+
3642
+ /**
3643
+ * Path-walking utilities. Used by:
3644
+ * - `PrimitivesRenderer.hitTest` — needs a polyline approximation of the
3645
+ * path for distance-to-segment checks.
3646
+ * - `ConnectorBase.paintMarkers` — needs the tangent angle at the source /
3647
+ * target endpoints to orient marker shapes.
3648
+ * - Any future connector decoration that walks arc length (e.g. label-along-
3649
+ * path). Static / glow / halo decorations don't sample — they call
3650
+ * `connector.paintInto(...)` for native-rendered silhouettes.
3651
+ *
3652
+ * For v0 the only router is `straight` (just `[M, L]`), so the sampling /
3653
+ * tangent paths are degenerate. The functions are written to handle the full
3654
+ * `Path` type so additional router kinds drop in without changes.
3655
+ */
3656
+
3657
+ /**
3658
+ * Densify a `Path` into a flat polyline. Lines emit two endpoints per
3659
+ * segment; quadratic / cubic curves are sampled with fixed substep counts.
3660
+ * Returns at least the move-to point when the path has only one command.
3661
+ */
3662
+ declare function samplePath(path: Path): Point[];
3663
+ /**
3664
+ * Compute the tangent unit vector at `t ∈ [0, 1]` along the path.
3665
+ * For v0 we only need `t = 0` (source) and `t = 1` (target) for marker
3666
+ * orientation; intermediate `t` is sampled via `samplePath` for now.
3667
+ */
3668
+ declare function tangentAt(path: Path, t: number): Vec2;
3669
+ /**
3670
+ * Combined point + unit-tangent sample at parameter `t ∈ [0, 1]` along the
3671
+ * path. Used by labels-along-path and any other decoration that needs both
3672
+ * the location and the local direction at the same parameter (e.g. for
3673
+ * `autoRotate`). Cheaper than calling `samplePath` + `tangentAt` separately
3674
+ * because it walks the polyline once.
3675
+ *
3676
+ * `t` is fractional in arc-length space — the function picks the segment of
3677
+ * the densified polyline whose cumulative length most closely matches `t *
3678
+ * totalLength` and linearly interpolates inside it. For most practical path
3679
+ * kinds this matches an analytical sample to within a pixel; orthogonal
3680
+ * paths reproduce segment endpoints exactly.
3681
+ */
3682
+ declare function samplePathAt(path: Path, t: number): {
3683
+ point: Point;
3684
+ tangent: Vec2;
3685
+ };
3686
+ /** AABB of the path's anchor + control points. Used by hit-test bbox indexing. */
3687
+ declare function pathBounds(path: Path): Rect;
3688
+ /**
3689
+ * Pull the path's start / end anchors inward by the requested arc-length
3690
+ * insets so the connector body stops short of where its markers will be
3691
+ * drawn. Markers themselves still anchor at the *original* endpoints (their
3692
+ * tips touch the target) — only the body is shortened.
3693
+ *
3694
+ * Correctness:
3695
+ * - `L` segments are trimmed in closed form (exact).
3696
+ * - `Q` / `C` segments are trimmed by walking arc length over a fine
3697
+ * sub-step table, refining the parameter `t` between bracketing samples,
3698
+ * and **De Casteljau subdividing** the curve at `t`. The kept half is
3699
+ * emitted as a new `Q` / `C` command, preserving correct curvature on
3700
+ * tight bends — chord-along-tangent approximation would diverge.
3701
+ * - When an inset exceeds the trailing segment's arc length, the segment
3702
+ * is consumed entirely and the trim continues into the prior segment.
3703
+ *
3704
+ * v0 only ships the `straight` router, so curve trimming is forward-looking
3705
+ * scaffolding for the upcoming `bezier` / `orthogonal` routers.
3706
+ */
3707
+ declare function trimPathEnds(path: Path, startInset: number, endInset: number): Path;
3708
+ /**
3709
+ * Squared minimum distance from `(px, py)` to any segment of the polyline.
3710
+ * Squared (no sqrt) so callers can compare against a squared tolerance —
3711
+ * faster + branch-free for the common no-hit case.
3712
+ */
3713
+ declare function distanceToPolylineSq(poly: ReadonlyArray<Point>, px: number, py: number): number;
3714
+
3715
+ /**
3716
+ * Pure placement math for badges. Given the host's world-space AABB and the
3717
+ * badge's local-space AABB, resolve the world-space `(x, y)` to put on the
3718
+ * badge spec so that a chosen point on the badge's AABB lands at a chosen
3719
+ * point on the host's AABB (plus an optional pixel offset).
3720
+ *
3721
+ * No Pixi imports. Trivially testable.
3722
+ *
3723
+ * The maths splits cleanly along two axes:
3724
+ * 1. **Host anchor** — which point on the host AABB is the target. Driven by
3725
+ * `BadgePlacement` (8 named points around the host).
3726
+ * 2. **Badge origin** — which point on the badge AABB lands at that anchor.
3727
+ * Driven by the optional `origin` field. Defaults to the *mirror* of the
3728
+ * placement so the badge sits fully outside the host edge.
3729
+ */
3730
+
3731
+ /**
3732
+ * Returns the point on the badge's local AABB that should land at the host
3733
+ * anchor, given the chosen origin. The default (omitted origin) is the
3734
+ * mirror of `placement` so the badge sits fully outside the host edge.
3735
+ * When `placement` is a raw `{x, y}` point with no inherent mirror, the
3736
+ * default falls back to `'center'`.
3737
+ */
3738
+ declare function originToBadgeLocal(badgeLocalBounds: Rect, placement: BadgePlacement, origin: BadgeOptions['origin']): {
3739
+ x: number;
3740
+ y: number;
3741
+ };
3742
+ /**
3743
+ * Resolve the badge spec's `(x, y)` so that the chosen origin point on the
3744
+ * badge AABB lands at the chosen anchor point on the host AABB, plus the
3745
+ * caller's pixel offset.
3746
+ *
3747
+ * The badge spec's `(x, y)` represents the badge's *local-origin* in world
3748
+ * space (e.g. circle centre, rect top-left). Local AABB origin is at
3749
+ * `(badgeLocalBounds.x, badgeLocalBounds.y)` — for a circle these are
3750
+ * negative (`-r, -r`); for a rect they are `(0, 0)`. We compute the badge's
3751
+ * `(x, y)` such that the chosen origin point — at
3752
+ * `(specX + originLocal.x, specY + originLocal.y)` in world space — equals
3753
+ * the host anchor + offset.
3754
+ */
3755
+ declare function resolveBadgePosition(hostWorldBounds: Rect, badgeLocalBounds: Rect, options: BadgeOptions): {
3756
+ x: number;
3757
+ y: number;
3758
+ };
3759
+
3760
+ /**
3761
+ * Pure placement math for connector-hosted badges. Given a router-resolved
3762
+ * `Path` and the badge's local-space AABB, resolve the world-space `(x, y)`
3763
+ * (plus optional rotation) so that a chosen point on the badge's AABB lands
3764
+ * on a chosen anchor along the path — `'start'` / `'middle'` / `'end'` or
3765
+ * an arbitrary arc-length `t ∈ [0, 1]`.
3766
+ *
3767
+ * No Pixi imports. The math mirrors {@link LabelConnectorDecoration} so
3768
+ * connector badges and connector labels share the same arc-length walk.
3769
+ */
3770
+
3771
+ /**
3772
+ * Resolve the badge spec's `(x, y)` (and optional `rotation`) so that the
3773
+ * chosen origin point on the badge's local AABB lands at the path-anchor
3774
+ * defined by `options.placement`. The origin defaults to `'center'` for
3775
+ * connector hosts (badge centres on the path point); shape-style mirror
3776
+ * defaults don't apply here because the path has no "outside edge".
3777
+ *
3778
+ * The returned `rotation` is `0` unless {@link BadgeOptions.autoRotate} is
3779
+ * `true`. When auto-rotating with `keepUpright !== false` (the default),
3780
+ * tangents whose angle exceeds `±90°` are flipped by `π` so the badge's
3781
+ * top edge keeps facing the viewer.
3782
+ */
3783
+ /**
3784
+ * Per-endpoint extra clearance added to the auto-shift when
3785
+ * {@link BadgeOptions.placement} is `'start'` or `'end'`. The renderer
3786
+ * passes the source / target marker length here (so the badge clears the
3787
+ * arrowhead, not just the trimmed path endpoint) plus a small visual gap.
3788
+ *
3789
+ * Numeric placements (`0`, `1`, raw `t`) ignore this — they're the "raw
3790
+ * arc-length" escape hatch.
3791
+ */
3792
+ interface ConnectorBadgeEndpointClearance {
3793
+ readonly source: number;
3794
+ readonly target: number;
3795
+ }
3796
+ /** Default pixel gap inserted between an endpoint-anchored badge and the
3797
+ * endpoint shape's silhouette (or, when a marker is present, the marker's
3798
+ * far tip). Tunable by callers via the `clearance` parameter — this is
3799
+ * just the engine-side floor when the renderer doesn't know better. */
3800
+ declare const DEFAULT_ENDPOINT_BADGE_GAP_PX = 8;
3801
+ declare function resolveConnectorBadgePosition(path: Path, badgeLocalBounds: Rect, options: BadgeOptions, clearance?: ConnectorBadgeEndpointClearance): {
3802
+ x: number;
3803
+ y: number;
3804
+ rotation: number;
3805
+ };
3806
+
3807
+ /**
3808
+ * Easing functions consumed by `Tween`. Each is a pure `(t: number) => number`
3809
+ * where `t ∈ [0, 1]` is normalised progress and the return value is the eased
3810
+ * progress (also typically in `[0, 1]`, though overshoot easings may exceed).
3811
+ *
3812
+ * Naming follows the standard easing taxonomy (Penner et al). Add new entries
3813
+ * here rather than inline-defining easings in effect / decoration code so the
3814
+ * set stays consistent across animated primitives.
3815
+ */
3816
+ type Easing = (t: number) => number;
3817
+ declare const linear: Easing;
3818
+ declare const easeInOutSine: Easing;
3819
+ declare const easeOutCubic: Easing;
3820
+ declare const easeInOutCubic: Easing;
3821
+ declare const easeOutQuad: Easing;
3822
+ /**
3823
+ * Stable string keys for the built-in easings.
3824
+ *
3825
+ * Serializable easing handle — use this (not an `Easing` function) anywhere an
3826
+ * easing must live in JSON config or bind to a `<select>` / lil-gui dropdown
3827
+ * (e.g. a layout's `transitionEase`). Resolve to the function with
3828
+ * {@link resolveEasing}.
3829
+ */
3830
+ type EasingName = 'linear' | 'easeInOutSine' | 'easeOutCubic' | 'easeInOutCubic' | 'easeOutQuad';
3831
+ /** All built-in easing names — handy for populating a picker. */
3832
+ declare const EASING_NAMES: EasingName[];
3833
+ /**
3834
+ * Resolve an {@link EasingName} (or `undefined`) to its `Easing` function,
3835
+ * falling back to `fallback` (default {@link easeOutCubic}) for an unknown or
3836
+ * missing name. Lets config carry a serializable easing key while runtime code
3837
+ * gets the function.
3838
+ */
3839
+ declare function resolveEasing(name: EasingName | undefined, fallback?: Easing): Easing;
3840
+
3841
+ /**
3842
+ * Options for constructing a `Tween`. `from` / `to` / `duration` are required;
3843
+ * everything else is optional and falls back to a sensible default.
3844
+ *
3845
+ * - `easing` defaults to `linear`.
3846
+ * - `repeat` is either an integer count (number of additional cycles after the
3847
+ * first) or `'forever'`. Defaults to `0` (play once).
3848
+ * - `yoyo` reverses direction on each repeat. Only meaningful when `repeat`
3849
+ * is non-zero. Defaults to `false`.
3850
+ * - `onUpdate(value)` fires every `tick` with the current eased value.
3851
+ * - `onComplete()` fires once when the tween retires (final cycle ends).
3852
+ * Never fires for `repeat: 'forever'`.
3853
+ */
3854
+ interface TweenOptions {
3855
+ readonly from: number;
3856
+ readonly to: number;
3857
+ readonly duration: number;
3858
+ readonly easing?: Easing;
3859
+ readonly repeat?: number | 'forever';
3860
+ readonly yoyo?: boolean;
3861
+ readonly onUpdate?: (value: number) => void;
3862
+ readonly onComplete?: () => void;
3863
+ }
3864
+ /**
3865
+ * Time-based interpolation primitive. Authors call `tick(deltaMs)` once per
3866
+ * frame; the tween advances internal time, applies easing, fires `onUpdate`,
3867
+ * and returns `false` when finished so the caller can retire it.
3868
+ *
3869
+ * The tween itself does no scheduling — it's a pure state machine. Effects
3870
+ * and decorations hold a `Tween` and drive it from their own `tick(dt)`.
3871
+ *
3872
+ * Reusable: call `reset()` to play again from `from`.
3873
+ */
3874
+ declare class Tween {
3875
+ private readonly opts;
3876
+ private readonly easing;
3877
+ private readonly maxRepeat;
3878
+ private elapsed;
3879
+ private cycle;
3880
+ private _value;
3881
+ private _done;
3882
+ constructor(opts: TweenOptions);
3883
+ get value(): number;
3884
+ get done(): boolean;
3885
+ /**
3886
+ * Advance by `dt` milliseconds. Returns `false` when the tween has finished
3887
+ * its final cycle; callers should remove finished tweens from their tick
3888
+ * set. Returns `true` while still running (including indefinitely for
3889
+ * `repeat: 'forever'`).
3890
+ */
3891
+ tick(dt: number): boolean;
3892
+ /** Restart from `from`. Clears `done`. */
3893
+ reset(): void;
3894
+ }
3895
+
3896
+ /**
3897
+ * Options for {@link animatePositions}.
3898
+ *
3899
+ * Positions are passed as flat `Float32Array`s of length `n * 2` — `x, y`
3900
+ * interleaved per node — the same shape `GraphStore.setPositionsBulk` consumes,
3901
+ * so a layout can hand its result buffer straight through.
3902
+ */
3903
+ interface PositionTransitionOptions {
3904
+ /** Start positions (`n * 2`, x/y interleaved). Usually the nodes' current spots. */
3905
+ from: Float32Array;
3906
+ /** Target positions (`n * 2`, x/y interleaved). The computed layout result. */
3907
+ to: Float32Array;
3908
+ /** Transition duration in milliseconds. `<= 0` snaps to `to` immediately. */
3909
+ duration: number;
3910
+ /** Eased progress curve. Default {@link easeOutCubic}. */
3911
+ easing?: Easing;
3912
+ /**
3913
+ * Called once per frame with the interpolated buffer — write it straight to
3914
+ * the store (e.g. `store.setPositionsBulk(ids, xy)`). The SAME buffer is
3915
+ * reused every frame; copy it if you need to retain it.
3916
+ */
3917
+ onFrame: (xy: Float32Array) => void;
3918
+ /** Fires once when the transition finishes naturally. NOT called on `cancel()`. */
3919
+ onComplete?: () => void;
3920
+ }
3921
+ /** Handle to an in-flight {@link animatePositions} transition. */
3922
+ interface PositionTransition {
3923
+ /** Abort the transition. `onComplete` will not fire; positions stop where they are. */
3924
+ cancel(): void;
3925
+ /** `true` once the transition has finished or been cancelled. */
3926
+ readonly done: boolean;
3927
+ }
3928
+ /** Default transition length when a caller opts in without specifying one. */
3929
+ declare const DEFAULT_POSITION_TRANSITION_MS = 500;
3930
+ /**
3931
+ * Tween a set of node positions from `from` to `to` over `duration` ms,
3932
+ * self-driven on `requestAnimationFrame`.
3933
+ *
3934
+ * One-shot layouts (ELK, d3-hierarchy, d3-sankey, …) compute a final position
3935
+ * set in a single pass and would otherwise `setPositionsBulk` it in one write,
3936
+ * teleporting every node. Routing that final buffer through `animatePositions`
3937
+ * instead glides each node from where it currently sits to its computed slot —
3938
+ * a far more legible layout switch / re-layout.
3939
+ *
3940
+ * The `Layout` base class is deliberately canvas-agnostic (it owns no RAF), so
3941
+ * this helper drives its own frame loop — mirroring how `D3ForceLayout` rides
3942
+ * d3's internal timer. It is store-agnostic: it only interpolates buffers and
3943
+ * hands each frame back via `onFrame`; the caller owns the write.
3944
+ *
3945
+ * Cancellation: call `cancel()` (typically from the layout's `stop()` or its
3946
+ * next `apply()`) to abort cleanly — the next run can start a fresh transition
3947
+ * from wherever the nodes currently are. SSR-safe and degenerate-input-safe:
3948
+ * with no `requestAnimationFrame`, a non-positive `duration`, or an empty set,
3949
+ * it writes the final positions once and completes synchronously.
3950
+ *
3951
+ * @throws if `from.length !== to.length`.
3952
+ */
3953
+ declare function animatePositions(opts: PositionTransitionOptions): PositionTransition;
3954
+
3955
+ /**
3956
+ * `Path` → SVG path-data serialisation. Pure: a routed {@link Path} in, a `d`
3957
+ * attribute string out.
3958
+ */
3959
+
3960
+ /** A `Path` (M/L/Q/C commands) → an SVG `d` attribute string. */
3961
+ declare function pathToSvgD(path: Path): string;
3962
+
3963
+ /**
3964
+ * Shape spec → SVG element serialisation — one half of the vector export path
3965
+ * (see `@invana/canvas`'s `exportSVG` for document assembly, and
3966
+ * {@link connectorToSvg} for the other half).
3967
+ *
3968
+ * The serialisers here are **pure and domain-free** (a `CircleSpec` knows
3969
+ * nothing about "nodes"): a spec goes in, markup comes out — no display object,
3970
+ * no canvas handle, which is why they live in `@invana/canvas-core` where a
3971
+ * rendering backend can call them directly.
3972
+ *
3973
+ * ## Coverage (v1)
3974
+ *
3975
+ * Faithful: `circle`, `ellipse`, `rect` (+ `cornerRadius`), `polygon`,
3976
+ * `regular-polygon`, `star`, `arc`, `composite` (root silhouette + `rect` /
3977
+ * `circle` / `line` / `label` parts), solid fills, strokes (colour / width /
3978
+ * alpha / dash / cap / join), per-shape `alpha` and container `rotation`, and
3979
+ * `text`-kind label decorations (approximate placement).
3980
+ *
3981
+ * Not represented (raster export covers these exactly — prefer PNG when they
3982
+ * matter): `image` / `glyph` / `svg` / `svg-url` fills, decorations other than
3983
+ * labels (glow / halo / rings / pulses), effects, blur / shadow filters, and
3984
+ * `html-text` labels. These are skipped rather than approximated.
3985
+ */
3986
+
3987
+ /**
3988
+ * Serialise a single shape spec to an SVG element. Returns `''` for a shape
3989
+ * kind that has no vector representation. `labelStyle` (from an attached
3990
+ * `label` decoration) is rendered as `<text>` when present.
3991
+ */
3992
+ declare function shapeSpecToSvg(spec: BaseShapeSpec, labelStyle?: unknown): string;
3993
+
3994
+ /**
3995
+ * Connector spec → SVG serialisation — the other half of the vector export
3996
+ * path (see {@link shapeSpecToSvg}). Pure: a spec + its routed {@link Path} in,
3997
+ * markup out.
3998
+ */
3999
+
4000
+ /**
4001
+ * Serialise a connector (its routed `path` + stroke + optional arrow markers)
4002
+ * to SVG. `strokeWidthScale` mirrors the renderer's per-instance LOD scaling.
4003
+ */
4004
+ declare function connectorToSvg(spec: BaseConnectorSpec, path: Path, strokeWidthScale?: number, labelStyle?: unknown): string;
4005
+
4006
+ /**
4007
+ * SVG markup primitives — number formatting, XML escaping, attribute
4008
+ * serialisation and colour conversion shared by every serialiser in this
4009
+ * folder (and by the `exportSVG` document assembler in `@invana/canvas`).
4010
+ *
4011
+ * Pure string helpers: no DOM, no canvas, no backend.
4012
+ */
4013
+
4014
+ /** Round to 3 decimals and drop a trailing `.0` — keeps the markup compact. */
4015
+ declare function n(v: number): string;
4016
+ /** Escape text for use in an XML text node / attribute value. */
4017
+ declare function esc(s: string): string;
4018
+ /** Serialise an attribute map, skipping `undefined` / empty values. */
4019
+ declare function attrs(map: Record<string, string | number | undefined>): string;
4020
+ /** `points="x,y x,y …"` for `<polygon>`. */
4021
+ declare function pointsAttr(pts: readonly Point[]): string;
4022
+ /** `0xRRGGBB` → `#rrggbb`. */
4023
+ declare function hexToCss(n: number): string;
4024
+
4025
+ /**
4026
+ * Spec paint → SVG paint attributes — the fill/stroke resolution shared by the
4027
+ * shape and connector serialisers, plus label-content extraction.
4028
+ *
4029
+ * Only the first `solid` fill layer is representable in flat SVG; `image` /
4030
+ * `glyph` / `svg` fills are skipped (→ `fill: none`) — a raster-only feature.
4031
+ */
4032
+
4033
+ /**
4034
+ * Resolve a {@link ShapeFill} to SVG `fill` / `fill-opacity`. Only the first
4035
+ * `solid` layer is representable in flat SVG; `image` / `glyph` / `svg` fills
4036
+ * are skipped (→ `fill: none`), documented as a raster-only feature.
4037
+ */
4038
+ declare function fillPaint(fill: ShapeFill | undefined): Record<string, string | number | undefined>;
4039
+ /** Resolve a {@link ShapeStroke} to SVG stroke attributes. `widthScale` mirrors LOD scaling. */
4040
+ declare function strokePaint(stroke: ShapeStroke | undefined, widthScale?: number): Record<string, string | number | undefined>;
4041
+ /** Extract plain-text `LabelContent` from a label decoration style, if any. */
4042
+ declare function textContent(style: unknown): (LabelContent & {
4043
+ kind: 'text';
4044
+ }) | undefined;
4045
+
4046
+ /** Reference-equality default; selector slices are compared with this. */
4047
+ declare function defaultEqual<U>(a: U, b: U): boolean;
4048
+ /** Shallow-equal for objects/arrays — a common selector equality for derived slices. */
4049
+ declare function shallowEqual<U>(a: U, b: U): boolean;
4050
+ /** A subscribable view of one selected slice — what `useSyncExternalStore` binds to. */
4051
+ interface Selected<U> {
4052
+ get(): U;
4053
+ subscribe(onChange: () => void): () => void;
4054
+ }
4055
+ /**
4056
+ * Project a {@link ReactiveStore} to one slice, re-notifying **only** when that
4057
+ * slice changes (by `isEqual`). Selector + equality semantics live here — in our
4058
+ * code, not the backend — so they survive a backend swap. The React `useStore`
4059
+ * hook (in `@invana/canvas-react`) binds this to `useSyncExternalStore`.
4060
+ */
4061
+ declare function select<T, U>(store: ReactiveStore<T>, selector: (state: T) => U, isEqual?: (a: U, b: U) => boolean): Selected<U>;
4062
+
4063
+ export { type AnnotationRecord, BadgeOptions, BadgePlacement, BaseConnectorSpec, BaseShapeSpec, Behaviour, type BehaviourOptions, BehaviourRegistry, type BehaviourRegistryOptions, CANVAS_SOURCE, Camera, type CameraChangeKind, type CameraInputConfig, type CameraInputModifier, type CameraOptions, type CameraTransform, type CameraTransformValue, type CanvasActions, type CanvasContext, type CanvasEvent, CanvasEventBus, type CanvasGlobalEvents, type CanvasSceneOptions, type CanvasStore, CanvasThemeState, type CanvasView, type ColumnArray, type ColumnSchema, ColumnStore, type ColumnStoreOptions, type ColumnType, type ColumnValue, type CustomElementCtor, DEFAULT_ENDPOINT_BADGE_GAP_PX, DEFAULT_POSITION_TRANSITION_MS, type DataSource, DecorationSpec, type DeepPartial, DefaultGestureArbiter, DirtyBatcher, type DirtySnapshot, EASING_NAMES, type Easing, type EasingName, type EdgeRecord, EffectSpec, ElementEventMap, EventEmitter, EventMap, type EventSource, type EventSourceKind, FlushMode, type FramePhase, type FramePhaseTimings, type FrameStats, type FrameTick, type GestureArbiter, type GestureClaimOptions, type GraphInput, type GroupRecord, HeadlessCameraBinding, HeadlessElementRenderer, HeadlessRenderer, HeadlessSurface, HitResult, IAnchor, type IBehaviour, type ICameraBinding, type IElementRenderer, type ILayer, type IOverlayDevice, IPathStyle, type IRenderer, IRouter, type ISurface, type ISurfaceHost, type IntentLogEntry, type InteractionKind, type KindDelta, LOOP_CURVE_PRESETS, LabelContent, LabelWrap, Layer, LayerData, type LayerFlush, type LayerOptions, LayerRegistry, type LayerRegistryOptions, Layout, type LayoutEndReason, type LayoutEvents, type LayoutOptions, LayoutRegistry, type LayoutRegistryOptions, Listener, type LoopCurvePresetName, type MountedDecoration, NODE_FLAG, type NodeDelta, type NodeRecord, type OverlayFill, type OverlayFillLike, type OverlaySpace, type OverlayStroke, type Patch, Path, type PinchInputOptions, Point, type PosSchema, type PositionTransition, type PositionTransitionOptions, type QueryStatus, type ReactiveStore, type Recipe, Rect, type RenderPreference, type RendererBackend, type RendererCapabilities, type RendererInitOptions, type RendererMountOptions, type ResolvedTheme, type RowOf, type Selected, ShapeFill, ShapeStroke, SourceEmitter, SpecFlush, type SpecProjectionTarget, SpecProjector, type SpecProjectorOptions, SpecStore, type StateCell, type StoreChange, type SurfaceBackdrop, type SurfaceOptions, type SurfaceSpace, type Tap, type TapOptions, type ThemeKind, type ThemeMode, type ThemeState, Tween, type TweenOptions, type Update, Vec2, type WheelInputOptions, animatePositions, attrs, bezierPathStyle, boundaryAnchor, bumpHorizontalPathStyle, bumpRadialPathStyle, bundlePathStyle, centerAnchor, connectorToSvg, createActions, defaultCanvasView, defaultEqual, distanceToPolylineSq, easeInOutCubic, easeInOutSine, easeOutCubic, easeOutQuad, edgePortAnchor, erRouter, esc, fillPaint, hexToCss, linear, loopCurvePathStyle, loopPolylinePathStyle, manhattanRouter, metroRouter, normalPathStyle, oneSideRouter, originToBadgeLocal, orthRouter, pathBounds, pathToSvgD, perpendicularAnchor, pointsAttr, quadraticPathStyle, resolveBadgePosition, resolveConnectorBadgePosition, resolveEasing, roundedPathStyle, samplePath, samplePathAt, select, shallowEqual, shapeSpecToSvg, silhouettePortAnchor, smoothPathStyle, stepRadialPathStyle, straightRouter, strokePaint, n as svgNum, tangentAt, textContent, trimPathEnds };