@invana/canvas-core 0.0.18 → 0.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/contracts/SpecProjector.ts","../src/state/events/EventEmitter.ts","../src/state/events/SourceEmitter.ts","../src/state/data/DirtyBatcher.ts","../src/abstracts/Layer.ts","../src/abstracts/Behaviour.ts","../src/abstracts/Layout.ts","../src/abstracts/GestureArbiter.ts","../src/state/port/select.ts","../src/lib/animation/easings.ts","../src/lib/animation/Tween.ts","../src/abstracts/Camera.ts","../src/abstracts/registries/LayerRegistry.ts","../src/abstracts/registries/BehaviourRegistry.ts","../src/abstracts/registries/LayoutRegistry.ts","../src/abstracts/registries/CommandRegistry.ts","../src/specs/geometry.ts","../src/specs/style.ts","../src/specs/shapeGeometry/polygonMath.ts","../src/specs/shapeGeometry/tabbedRect.ts","../src/specs/shapeGeometry/bounds.ts","../src/specs/shapeGeometry/contains.ts","../src/specs/shapeGeometry/index.ts","../src/state/data/flush.ts","../src/specs/SpecStore.ts","../src/headless/HeadlessCameraBinding.ts","../src/headless/HeadlessRenderer.ts","../src/lib/geometry/connectors/anchors/center.ts","../src/lib/geometry/connectors/anchors/boundary.ts","../src/lib/geometry/connectors/anchors/perpendicular.ts","../src/lib/geometry/connectors/anchors/edgePort.ts","../src/lib/geometry/connectors/anchors/silhouettePort.ts","../src/lib/geometry/connectors/routers/straight.ts","../src/lib/geometry/connectors/routers/orth.ts","../src/lib/geometry/connectors/routers/_obstacleGrid.ts","../src/lib/geometry/connectors/routers/_aStar.ts","../src/lib/geometry/connectors/routers/manhattan.ts","../src/lib/geometry/connectors/routers/metro.ts","../src/lib/geometry/connectors/routers/er.ts","../src/lib/geometry/connectors/routers/oneSide.ts","../src/lib/geometry/connectors/pathStyles/normal.ts","../src/lib/geometry/connectors/pathStyles/rounded.ts","../src/lib/geometry/connectors/pathStyles/bezier.ts","../src/lib/geometry/connectors/pathStyles/quadratic.ts","../src/lib/geometry/connectors/pathStyles/bumpRadial.ts","../src/lib/geometry/connectors/pathStyles/bumpHorizontal.ts","../src/lib/geometry/connectors/pathStyles/bumpVertical.ts","../src/lib/geometry/connectors/pathStyles/spline.ts","../src/lib/geometry/connectors/pathStyles/smooth.ts","../src/lib/geometry/connectors/pathStyles/stepRadial.ts","../src/lib/geometry/connectors/pathStyles/bundle.ts","../src/lib/geometry/connectors/pathStyles/loopPolyline.ts","../src/lib/geometry/connectors/pathStyles/loopCurve.ts","../src/lib/geometry/connectors/pathSampling.ts","../src/lib/geometry/badges/placement.ts","../src/lib/geometry/badges/connectorPlacement.ts","../src/lib/geometry/labels/labelScale.ts","../src/lib/animation/animatePositions.ts","../src/lib/svg/markup.ts","../src/lib/svg/pathToSvgD.ts","../src/lib/svg/paint.ts","../src/lib/svg/shapeSpecToSvg.ts","../src/lib/svg/connectorToSvg.ts","../src/state/view/CanvasView.ts","../src/state/view/createActions.ts","../src/state/events/CanvasEvent.ts","../src/state/events/CanvasEventBus.ts","../src/state/theme/CanvasThemeState.ts","../src/state/theme/types.ts","../src/state/data/ColumnStore.ts","../src/state/data/LayerData.ts"],"names":["reversed","n","len","TAU","resolveAutoSide","DEFAULT_INFLATE","DEFAULT_STUB_LENGTH","DEFAULT_TENSION","DEFAULT_SIDE","sx","sy","DEFAULT_BASE_OFFSET","DEFAULT_RADIUS","sideToAngle","a","b","raf"],"mappings":";AA8CO,IAAM,gBAAN,MAAqE;AAAA,EAI1E,WAAA,CACmB,KAAA,EACA,MAAA,EACA,OAAA,GAAgC,EAAC,EAClD;AAHiB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAEjB,IAAA,IAAA,CAAK,GAAA,GAAM,MAAM,OAAA,CAAQ,CAAC,UAAU,IAAA,CAAK,UAAA,CAAW,KAAK,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AAA,GAAA,CAAI,OAAO,EAAE,CAAA;AACb,IAAA,KAAA,CAAM,OAAA,CAAQ,OAAO,EAAE,CAAA;AACvB,IAAA,IAAI,KAAA,CAAM,KAAA,CAAM,MAAA,CAAO,EAAE,GAAG,OAAO,IAAA;AACnC,IAAA,KAAA,CAAM,OAAA,CAAQ,IAAI,EAAE,CAAA;AACpB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EAEQ,WAAA,CACN,GAAA,EACA,KAAA,EACA,IAAA,EACM;AACN,IAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,IAAA,CAAK,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,EAAE,CAAC,CAAA;AAC7C,IAAA,KAAA,MAAW,MAAM,CAAC,GAAG,GAAA,CAAI,IAAA,EAAM,CAAA,EAAG;AAChC,MAAA,IAAI,CAAC,QAAQ,GAAA,CAAI,EAAE,GAAG,IAAA,CAAK,UAAA,CAAW,GAAA,EAAK,KAAA,EAAO,EAAE,CAAA;AAAA,IACtD;AACA,IAAA,KAAA,MAAW,KAAK,IAAA,EAAM,IAAA,CAAK,MAAA,CAAO,GAAA,EAAK,OAAO,CAAC,CAAA;AAAA,EACjD;AACF","file":"index.js","sourcesContent":["/**\n * `SpecProjector` — drives a renderer from a {@link SpecStore}.\n *\n * The store holds the visual description; this turns it into mounted elements.\n * Every drawing layer uses the same projector, which is what makes \"the renderer\n * is a projection of state\" true for the whole engine rather than for one layer.\n *\n * Two entry points, and the difference matters:\n *\n * - {@link project} — synchronous, for a layer publishing its own spec. Anything\n * the layer does *after* publishing (attaching a label, a decoration, a badge)\n * needs the element mounted already, so this path cannot wait for a flush.\n * - the **flush subscription** — for every other writer: a behaviour, a tool, a\n * restored session. Ids already projected synchronously in the same frame are\n * skipped so nothing is drawn twice.\n *\n * Shapes and connectors are told apart by **which registry owns the spec's\n * `kind`**, so no discriminator has to be baked into the spec vocabulary.\n *\n * See `docs/renderer-split-design.md` §2 and §4.2b.\n */\n\nimport type { SpecFlush, SpecStore } from '../specs';\nimport type { BaseConnectorSpec, BaseShapeSpec } from '../specs';\n\n/** The slice of a renderer this projector drives. */\nexport interface SpecProjectionTarget {\n readonly shapeKinds: ReadonlySet<string>;\n getShapeKind(id: string): string | undefined;\n hasConnector(id: string): boolean;\n addShape<TSpec extends BaseShapeSpec>(id: string, spec: TSpec): void;\n updateShape<TSpec extends BaseShapeSpec>(id: string, patch: Partial<TSpec>): void;\n removeShape(id: string): void;\n addConnector<TSpec extends BaseConnectorSpec>(id: string, spec: TSpec): void;\n updateConnector<TSpec extends BaseConnectorSpec>(id: string, patch: Partial<TSpec>): void;\n removeConnector(id: string): void;\n}\n\nexport interface SpecProjectorOptions {\n /**\n * Called before an element is removed and re-added because its `kind` changed.\n * A host may be tracking decoration / badge slots that the removal disposes.\n */\n onKindChange?: (id: string) => void;\n}\n\nexport class SpecProjector<TSpec extends BaseShapeSpec | BaseConnectorSpec> {\n private readonly projectedThisFlush = new Set<string>();\n private readonly off: () => void;\n\n constructor(\n private readonly specs: SpecStore<TSpec>,\n private readonly target: SpecProjectionTarget,\n private readonly options: SpecProjectorOptions = {},\n ) {\n this.off = specs.onFlush((delta) => this.applyFlush(delta));\n }\n\n /**\n * Mount / update `id` from the store **now**, and mark it handled so the next\n * flush skips it.\n */\n project(id: string): void {\n this.projectedThisFlush.add(id);\n this.apply(id);\n }\n\n /** Remove whatever the renderer holds for `id`, whichever kind it is. */\n unproject(id: string): void {\n const t = this.target;\n if (t.getShapeKind(id) !== undefined) t.removeShape(id);\n else if (t.hasConnector(id)) t.removeConnector(id);\n }\n\n /** Drop the flush subscription. */\n destroy(): void {\n this.off();\n this.projectedThisFlush.clear();\n }\n\n private applyFlush(delta: SpecFlush): void {\n for (const id of delta.added) if (!this.projectedThisFlush.has(id)) this.apply(id);\n for (const id of delta.changed) if (!this.projectedThisFlush.has(id)) this.apply(id);\n for (const id of delta.removed) this.unproject(id);\n this.projectedThisFlush.clear();\n }\n\n private apply(id: string): void {\n const spec = this.specs.get(id);\n if (!spec) return;\n const t = this.target;\n\n if (t.shapeKinds.has(spec.kind)) {\n const shapeSpec = spec as BaseShapeSpec;\n const currentKind = t.getShapeKind(id);\n if (currentKind === undefined) {\n t.addShape(id, shapeSpec);\n } else if (currentKind === shapeSpec.kind) {\n // Instance-preserving: keeps gfx scale, decorations, badges, effects.\n t.updateShape<BaseShapeSpec>(id, shapeSpec);\n } else {\n // `IShape` is fixed at construction, so a kind change means remount.\n t.removeShape(id);\n this.options.onKindChange?.(id);\n t.addShape(id, shapeSpec);\n }\n return;\n }\n\n const connectorSpec = spec as BaseConnectorSpec;\n if (t.hasConnector(id)) t.updateConnector(id, connectorSpec);\n else t.addConnector(id, connectorSpec);\n }\n}\n","/** A typed listener for one event payload. */\nexport type Listener<P> = (payload: P) => void;\n\n/**\n * A string-keyed event map (`{ eventType: payload }`) — the conventional generic\n * bound for scoped {@link EventEmitter}s (layer / behaviour / domain-store event\n * channels). `EventEmitter`/`SourceEmitter` accept any `object`; this is the\n * portable shape most maps use.\n */\nexport type EventMap = Record<string, unknown>;\n\n/**\n * A small typed event emitter over an event map `M` (`{ eventType: payload }`).\n * Renderer-free; the base for {@link SourceEmitter} and the building block under\n * {@link CanvasEventBus}.\n */\nexport class EventEmitter<M extends object> {\n private readonly map = new Map<keyof M, Set<Listener<unknown>>>();\n\n /** Subscribe; returns an unsubscribe. */\n on<K extends keyof M>(type: K, listener: Listener<M[K]>): () => void {\n let set = this.map.get(type);\n if (!set) {\n set = new Set();\n this.map.set(type, set);\n }\n set.add(listener as Listener<unknown>);\n return () => this.off(type, listener);\n }\n\n /** Subscribe for a single emission. */\n once<K extends keyof M>(type: K, listener: Listener<M[K]>): () => void {\n const off = this.on(type, (payload) => {\n off();\n listener(payload);\n });\n return off;\n }\n\n /** Unsubscribe a listener. */\n off<K extends keyof M>(type: K, listener: Listener<M[K]>): void {\n this.map.get(type)?.delete(listener as Listener<unknown>);\n }\n\n /** Emit to all listeners of `type` (snapshot, so handlers may unsubscribe). */\n emit<K extends keyof M>(type: K, payload: M[K]): void {\n const set = this.map.get(type);\n if (!set) return;\n for (const l of [...set]) (l as Listener<M[K]>)(payload);\n }\n\n removeAllListeners(): void {\n this.map.clear();\n }\n\n listenerCount<K extends keyof M>(type: K): number {\n return this.map.get(type)?.size ?? 0;\n }\n}\n","import type { CanvasEventBus } from './CanvasEventBus';\nimport type { EventSource } from './CanvasEvent';\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * A scoped {@link EventEmitter} stamped with an {@link EventSource}. When connected\n * to a bus via {@link setBus}, every emit is **also** forwarded to the bus tap as a\n * structured envelope — so a store/layer/behaviour's own events reach the\n * canvas-wide tap (telemetry / collaboration) without each one re-plumbing.\n *\n * Local `on(...)` subscribers still get the raw typed payload as usual.\n */\nexport class SourceEmitter<M extends object> extends EventEmitter<M> {\n private bus: CanvasEventBus | null = null;\n\n constructor(public readonly source: EventSource) {\n super();\n }\n\n /** Connect (or disconnect with `null`/`undefined`) this emitter's stream to a bus tap. */\n setBus(bus: CanvasEventBus | null | undefined): void {\n this.bus = bus ?? null;\n }\n\n override emit<K extends keyof M>(type: K, payload: M[K]): void {\n super.emit(type, payload);\n this.bus?.publish(type as string, payload, this.source);\n }\n}\n","/**\n * `DirtyBatcher<TBucket>` — accumulates \"this id changed\" signals between frames,\n * deduplicates them, and hands a per-frame snapshot to a flush callback.\n *\n * Relocated into `@invana/canvas-store` (decision D1) alongside {@link ColumnStore}\n * — the renderer-free machinery behind the kernel's coalesced data flush. Pure;\n * **no rendering, no pixi, no `requestAnimationFrame` of its own** — the owner\n * (the engine's single rAF loop) calls {@link flush} once per tick.\n *\n * **Performance contract:** `mark` O(1) (Map.get + Set.add, no steady-state\n * alloc); `markAll` O(1) (a flag); `flush` O(1) (Map swap, no copy). Per-frame\n * consumer work is proportional to *changed* ids, never total scene size. Sets are\n * reused across frames (double-buffered) — zero GC pressure in steady state.\n *\n * **Double buffering:** `flush()` returns a snapshot of the previous frame's marks\n * and swaps in the empty buffer, so any `mark()` during the consumer's handler\n * lands in the *next* frame — never corrupts the iteration in flight.\n */\n\n/**\n * The snapshot handed to the flush handler. `buckets` is keyed by bucket name →\n * the Set of dirty ids this frame (untouched buckets are absent). `rebuildAll` is\n * the set of buckets flagged via {@link DirtyBatcher.markAll} — for those, iterate\n * the underlying data, not the per-id Set.\n */\nexport interface DirtySnapshot<TBucket extends string = string> {\n readonly buckets: ReadonlyMap<TBucket, ReadonlySet<string>>;\n readonly rebuildAll: ReadonlySet<TBucket>;\n}\n\n/** One side of the double buffer. Internal. */\ninterface BatcherFrame<TBucket extends string> {\n buckets: Map<TBucket, Set<string>>;\n rebuildAll: Set<TBucket>;\n}\n\nexport class DirtyBatcher<TBucket extends string = string> {\n private active: BatcherFrame<TBucket> = makeFrame<TBucket>();\n private buffer: BatcherFrame<TBucket> = makeFrame<TBucket>();\n private _dirty = false;\n\n /** Mark a single id dirty in a bucket. O(1); bucket Sets are created lazily + reused. */\n mark(bucket: TBucket, id: string): void {\n let set = this.active.buckets.get(bucket);\n if (!set) {\n set = new Set<string>();\n this.active.buckets.set(bucket, set);\n }\n set.add(id);\n this._dirty = true;\n }\n\n /** Flag a whole bucket for rebuild (theme change, LOD swap, wholesale replace). */\n markAll(bucket: TBucket): void {\n this.active.rebuildAll.add(bucket);\n this._dirty = true;\n }\n\n /** Cheap check the tick uses to decide whether to call {@link flush}. */\n hasPending(): boolean {\n return this._dirty;\n }\n\n /**\n * Swap buffers and return the previous frame's snapshot. The returned Sets are\n * still owned by the batcher — **do not retain references past the flush call**;\n * the next `flush()` reuses and clears them.\n */\n flush(): DirtySnapshot<TBucket> {\n const outgoing = this.active;\n this.active = this.buffer;\n this.buffer = outgoing;\n this._dirty = false;\n // Pre-clear the new active frame; `outgoing` is cleared on the FOLLOWING flush.\n for (const set of this.active.buckets.values()) set.clear();\n this.active.rebuildAll.clear();\n return outgoing as unknown as DirtySnapshot<TBucket>;\n }\n\n /** Drop both buffers. Call on unmount; usable again afterwards. */\n reset(): void {\n for (const set of this.active.buckets.values()) set.clear();\n for (const set of this.buffer.buckets.values()) set.clear();\n this.active.rebuildAll.clear();\n this.buffer.rebuildAll.clear();\n this._dirty = false;\n }\n\n /** Number of dirty ids in a bucket (0 if never touched). Debug. */\n bucketSize(bucket: TBucket): number {\n return this.active.buckets.get(bucket)?.size ?? 0;\n }\n\n /** True iff the bucket is flagged for rebuild this frame. Debug. */\n isRebuildAll(bucket: TBucket): boolean {\n return this.active.rebuildAll.has(bucket);\n }\n}\n\nfunction makeFrame<TBucket extends string>(): BatcherFrame<TBucket> {\n return {\n buckets: new Map<TBucket, Set<string>>(),\n rebuildAll: new Set<TBucket>(),\n };\n}\n","/**\n * `Layer` — base class for everything composable onto `canvas.layers`.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * **What every Layer owns:**\n * - `id` — stable identifier; used by registries, events, telemetry envelopes.\n * - `options` — construction-time, mostly-immutable config.\n * - `state` — UI / interaction state (`ReactiveStore<T>` from the kernel; small,\n * observable, and — because it goes through the port — patch-emitting, so\n * history, telemetry and a future CRDT backend all see it.\n * - `events` — typed `SourceEmitter` that auto-forwards to the canvas tap.\n * - `dirty` — `DirtyBatcher` for per-frame batched flush.\n * - `visible` / `hittable` / `zIndex` / `cullable` — composition flags.\n *\n * **Lifecycle:** `mount(ctx)` → … → `unmount()`. `Canvas` calls these via the\n * `LayerRegistry`. `flush()` is called once per Canvas tick when\n * `dirty.hasPending()` is true.\n *\n * **Bulk hot data (`data`)** is NOT on the base class — it lives on subclasses\n * that need it (e.g. `GraphLayer` ships `GraphNodeStore`). See\n * `architecture-proposal.md` §2.1 for the bifurcated state/data model.\n *\n * **What subclasses provide:**\n * - `createState()` — initial UI state.\n * - `applyDirty(snap)` — translate dirty buckets → renderer commands.\n * - `onMount()` / `onUnmount()` — domain-specific setup/teardown\n * (subscribe to feeds, register decorations, etc.).\n * - `WorldLayer` / `ScreenLayer` add `hitTest(coord, coord)`.\n */\n\nimport type { CanvasContext } from './CanvasContext';\nimport type { EventMap } from '../state/events/EventEmitter';\nimport type { ReactiveStore } from '../state/port/types';\nimport { SourceEmitter } from '../state/events/SourceEmitter';\nimport { DirtyBatcher, type DirtySnapshot } from '../state/data/DirtyBatcher';\n\n// ─── Minimal interface that registries see ─────────────────────────────────\n\n/**\n * The subset of `Layer` the `LayerRegistry` and `Canvas.tick` interact with.\n * Lets the registry stay decoupled from the abstract class implementation.\n */\nexport interface ILayer {\n readonly id: string;\n visible: boolean;\n hittable: boolean;\n zIndex: number;\n cullable: boolean;\n /** `true` between `mount(ctx)` and `unmount()`. Lets the registry skip already-mounted layers. */\n readonly mounted: boolean;\n mount(ctx: CanvasContext): void;\n unmount(): void;\n flush(): void;\n hasPending(): boolean;\n redraw(): void;\n setVisible(visible: boolean): void;\n}\n\n// ─── Constructor options ───────────────────────────────────────────────────\n\nexport interface LayerOptions<TOptions = unknown> {\n id: string;\n options: TOptions;\n visible?: boolean;\n hittable?: boolean;\n zIndex?: number;\n /**\n * Off-screen culling participation. Default `true`. Set `false` for\n * full-canvas effect layers (background gradient, overlay) that should\n * always render regardless of camera visibility.\n */\n cullable?: boolean;\n}\n\n// ─── Layer base class ──────────────────────────────────────────────────────\n\nexport abstract class Layer<\n TOptions = unknown,\n TState extends object = object,\n TEvents extends EventMap = EventMap,\n TDirtyBucket extends string = string,\n> implements ILayer\n{\n readonly id: string;\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'background-layer'`,\n * `'minimap-layer'`). Distinct from {@link id} (the per-instance key): all\n * `BackgroundLayer` instances share `kind: 'background-layer'`. Concrete layers\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n readonly options: TOptions;\n readonly events: SourceEmitter<TEvents>;\n readonly dirty: DirtyBatcher<TDirtyBucket>;\n\n /**\n * Backing field for {@link state}. Created on **first mount** via\n * `ctx.createStateStore` (the engine injects the reactive-store factory — this\n * package is dependency-free and cannot construct one), then kept for the\n * layer's lifetime: a remount reuses the same store, preserving state.\n */\n private _state?: ReactiveStore<TState>;\n\n /**\n * UI / interaction state (`ReactiveStore<TState>`). Because it is built\n * through the injected kernel factory, every write emits patches and history /\n * telemetry / a future CRDT backend all observe it.\n *\n * **Available from `mount()` onward** — accessing it before the first mount\n * throws. (`createState()` is also called at first mount, so it may safely\n * read subclass fields initialised in the subclass constructor.)\n */\n get state(): ReactiveStore<TState> {\n if (!this._state) {\n throw new Error(\n `Layer \"${this.id}\": state is unavailable before the first mount() — ` +\n 'it is created via ctx.createStateStore when the layer mounts.',\n );\n }\n return this._state;\n }\n\n /** Backing field for the `visible` accessor. */\n private _visible: boolean = true;\n hittable: boolean;\n zIndex: number;\n cullable: boolean;\n\n /**\n * Whether this layer renders. Setting `false` hides the layer's pixi\n * container (via `onVisibleChange`, overridden by `WorldLayer` /\n * `ScreenLayer`) and the Canvas tick skips its flush.\n */\n get visible(): boolean {\n return this._visible;\n }\n set visible(value: boolean) {\n if (this._visible === value) return;\n this._visible = value;\n this.onVisibleChange(value);\n }\n\n /**\n * Toggle whole-layer visibility, repaint, and announce it. Unlike assigning\n * `visible` (which only hides the pixi container via {@link onVisibleChange}),\n * this also forces a {@link redraw} and emits `scene:layer:visibilitychange`\n * on the canvas bus so dependent layers (minimap) and the render loop react\n * automatically. No-op if the value is unchanged.\n */\n setVisible(visible: boolean): void {\n if (this._visible === visible) return;\n this.visible = visible; // runs onVisibleChange (container.visible sync)\n // Repaint from current state so a re-shown renderer-backed layer restores\n // its content without waiting for the next mutation.\n if (visible) this.redraw();\n this.ctx?.events.emit('scene:layer:visibilitychange', { id: this.id, visible });\n }\n\n /** Set by `mount(ctx)`; cleared by `unmount()`. */\n protected ctx?: CanvasContext;\n\n /** True between `mount` and `unmount`. */\n get mounted(): boolean {\n return this.ctx !== undefined;\n }\n\n constructor(opts: LayerOptions<TOptions>) {\n this.id = opts.id;\n this.options = opts.options;\n this._visible = opts.visible ?? true;\n this.hittable = opts.hittable ?? true;\n this.zIndex = opts.zIndex ?? 0;\n this.cullable = opts.cullable ?? true;\n\n // State is NOT created here — this package cannot construct a reactive\n // store (the factory is immer/zustand-backed and lives in the kernel).\n // `mount(ctx)` builds it via `ctx.createStateStore` on first mount.\n\n // Events emitter without bus initially; `mount()` attaches it to ctx.events.\n this.events = new SourceEmitter<TEvents>({ kind: 'layer', id: this.id });\n\n this.dirty = new DirtyBatcher<TDirtyBucket>();\n }\n\n // ─── Lifecycle ───────────────────────────────────────────────────────────\n\n mount(ctx: CanvasContext): void {\n if (this.ctx !== undefined) {\n throw new Error(`Layer \"${this.id}\" already mounted`);\n }\n this.ctx = ctx;\n // First mount builds the state store through the engine-injected factory\n // (so layer state rides the same patch-emitting port as every other store);\n // later remounts reuse it, preserving state across unmount/mount cycles.\n this._state ??= ctx.createStateStore<TState>(this.createState());\n this.events.setBus(ctx.events);\n this.onMount(ctx);\n }\n\n unmount(): void {\n if (this.ctx === undefined) return;\n const ctx = this.ctx;\n this.onUnmount(ctx);\n this.events.setBus(null);\n this.dirty.reset();\n this.ctx = undefined;\n }\n\n /** Convenience accessor; throws when called pre-mount. */\n protected get context(): CanvasContext {\n if (!this.ctx) {\n throw new Error(`Layer \"${this.id}\" is not mounted`);\n }\n return this.ctx;\n }\n\n // ─── Per-tick flush ──────────────────────────────────────────────────────\n\n /** Whether `flush()` has work to do this frame. */\n hasPending(): boolean {\n return this.dirty.hasPending();\n }\n\n /**\n * Called by Canvas tick when `hasPending()` is true. Swaps the dirty\n * snapshot, hands it to `applyDirty`. Subclasses normally don't override.\n */\n flush(): void {\n if (!this.dirty.hasPending()) return;\n const snap = this.dirty.flush();\n this.applyDirty(snap);\n }\n\n /**\n * Force a full repaint of this layer from its current state, bypassing the\n * per-frame dirty path. Base implementation is a no-op — only layers that\n * mount a renderer override it (e.g. `GraphLayer.redraw` re-renders every\n * node and edge). Driven by {@link Canvas.redraw}; reach for it after an\n * external change that sidestepped the normal mutate-and-flush path (theme\n * swap, palette change) or to recover from a suspected render desync.\n */\n redraw(): void {\n /* default no-op — renderer-backed layers override this */\n }\n\n // ─── Subclass hooks ──────────────────────────────────────────────────────\n\n /** Build the initial UI / interaction state. Called once in the constructor. */\n protected abstract createState(): TState;\n\n /**\n * Translate a dirty snapshot into renderer / pixi commands.\n * Default: no-op. Override when the layer batches work via `dirty.mark(...)`.\n */\n protected applyDirty(_snap: DirtySnapshot<TDirtyBucket>): void {\n /* default no-op */\n }\n\n /** Domain-specific mount setup (subscribe to peers, attach renderer, etc.). */\n protected onMount(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /** Domain-specific unmount teardown. */\n protected onUnmount(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /**\n * Called whenever `visible` changes (setter only — not on initial\n * construction). Subclasses override to keep their pixi container's\n * `.visible` in sync. Default: no-op.\n */\n protected onVisibleChange(_value: boolean): void {\n /* default no-op */\n }\n}\n","/**\n * `Behaviour` — input subscriber that translates user input into state mutations.\n *\n * Architecture: see `architecture-proposal.md` §2.2.\n *\n * Behaviours own neither rendering output nor source-of-truth data. They\n * subscribe to layer events (`'node:hover'`, `'shape:click'`) or canvas events\n * (`'pointerdown'`) and mutate the appropriate `state` slice.\n *\n * **Default `enabled: false`.** Registration wires the behaviour up; the\n * developer explicitly enables it. Matches the rule that no input behaviour\n * is auto-active (`architecture-proposal.md` §2.2 + repo CLAUDE.md rule 7).\n *\n * **`shortcuts`** is advisory metadata — used by `BehaviourRegistry` to log\n * conflict warnings when two enabled behaviours claim the same gesture\n * (e.g. lasso vs. pan both wanting `'shift+drag'`). The framework warns;\n * it does not enforce — that's the developer's job.\n *\n * **`modes`** ties a behaviour to the canvas's interaction mode\n * (`view.interaction.viewMode` — the modeller \"tool\"). An enabled behaviour with\n * `modes: ['add']` is only *live* while the mode is `'add'`: outside it the base\n * runs {@link Behaviour.onDisable} (cancelling any gesture) and back inside it\n * runs {@link Behaviour.onEnable}. `enabled` stays the developer's flag — a mode\n * switch never changes it, never fires `scene:behaviour:enable`, and never shows\n * up in {@link Behaviour.getOptions}.\n */\n\nimport type { CanvasContext } from './CanvasContext';\nimport type { GestureClaimOptions } from './GestureArbiter';\n\n/** What `BehaviourRegistry` sees. */\nexport interface IBehaviour {\n readonly id: string;\n readonly enabled: boolean;\n /** `true` once `register(ctx)` has run. Lets the registry skip already-wired behaviours. */\n readonly isRegistered: boolean;\n readonly scope: 'layer' | 'canvas';\n readonly targetLayerId?: string;\n readonly shortcuts?: readonly string[];\n register(ctx: CanvasContext): void;\n destroy(): void;\n enable(): void;\n disable(): void;\n /**\n * Merge a serialisable options patch and apply it live. Every behaviour\n * supports this (the base provides a generic implementation) so the engine's\n * `canvas.update({ behaviours })` path can retune any behaviour uniformly.\n */\n setOptions(changes: Record<string, unknown>): void;\n /**\n * Replace the interaction modes this behaviour is live in (`undefined` = all).\n * The engine calls it directly for a `modes` patch, like it routes `enabled`\n * through the registry, because some behaviours override `setOptions`\n * without calling `super`.\n */\n setModes?(modes: readonly string[] | undefined): void;\n}\n\nexport interface BehaviourOptions {\n id: string;\n /**\n * Layer-scoped behaviours target a specific Layer by id. Canvas-scoped\n * behaviours have no `targetLayerId` and `scope: 'canvas'`.\n */\n targetLayerId?: string;\n /** Default `false` — the developer explicitly enables. */\n enabled?: boolean;\n /**\n * Gesture identifiers this behaviour claims. Used by `BehaviourRegistry`\n * for conflict warnings. Format is convention-free (`'shift+drag'`,\n * `'wheel+ctrl'`, `'rclick'`); registries match strings as-is.\n */\n shortcuts?: readonly string[];\n /**\n * Interaction modes (`view.interaction.viewMode` values) this behaviour is live\n * in. Omitted = every mode. An enabled behaviour outside its modes is\n * suspended — its `onDisable` runs, `enabled` is unchanged — and resumes when\n * the mode comes back. E.g. `modes: ['connect']` on an edge-drawing behaviour\n * makes the modeller's Connect tool switch it on and off with no host wiring.\n * A `'!'` entry excludes a mode: `modes: ['!hand']` is live in every mode but\n * `'hand'`. Positive and `'!'` entries combine — listed modes, minus the\n * excluded ones.\n */\n modes?: readonly string[];\n}\n\nexport abstract class Behaviour<TOptions extends BehaviourOptions = BehaviourOptions>\n implements IBehaviour\n{\n readonly id: string;\n readonly targetLayerId?: string;\n readonly shortcuts?: readonly string[];\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'drag-pan'`,\n * `'wheel-zoom'`). Distinct from {@link id} (the per-instance key): all\n * `DragPanBehaviour` instances share `kind: 'drag-pan'`. Concrete behaviours\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n\n /**\n * `'layer'` if `targetLayerId` is set, otherwise `'canvas'`. Set automatically\n * from the constructor — subclasses don't need to re-declare.\n */\n readonly scope: 'layer' | 'canvas';\n\n /**\n * Whether the behaviour is **live**: the developer's flag ({@link enabled})\n * *and* the current interaction mode being one of {@link BehaviourOptions.modes}.\n * Subclasses gate their handlers on this (or {@link isEnabled}); only the base\n * writes it.\n */\n protected _enabled: boolean;\n protected ctx?: CanvasContext;\n\n /** The developer's enable flag — what {@link enabled} reports and snapshots capture. */\n private _wanted: boolean;\n /** `false` while the canvas's mode is outside {@link BehaviourOptions.modes}. */\n private _inMode = true;\n /** Releases the `viewMode` subscription, or `null` when not watching. */\n private _modeUnsub: (() => void) | null = null;\n\n /**\n * The construction options, merged in-place by {@link setOptions}. Named\n * `_options` (not `options`) so subclasses that expose a bespoke\n * `get options()` snapshot don't collide with it. Subclasses read their live\n * config from here (or from fields re-synced in {@link onOptionsChanged}).\n */\n protected _options: TOptions;\n\n /**\n * Release function for this behaviour's live gesture claim, or `null` when it\n * holds none. Held privately (not `protected`) so the only way to end a claim\n * is {@link releaseGesture} — which nulls the field *before* invoking it, so a\n * double release can't happen even under re-entrancy.\n */\n private _gestureRelease: (() => void) | null = null;\n\n constructor(opts: TOptions) {\n this.id = opts.id;\n this.targetLayerId = opts.targetLayerId;\n this.scope = opts.targetLayerId !== undefined ? 'layer' : 'canvas';\n this.shortcuts = opts.shortcuts;\n this._wanted = opts.enabled ?? false;\n this._enabled = this._wanted;\n this._options = opts;\n }\n\n /** The developer's enable flag. A behaviour suspended by its `modes` still reports `true`. */\n get enabled(): boolean {\n return this._wanted;\n }\n\n get isRegistered(): boolean {\n return this.ctx !== undefined;\n }\n\n /** Called by `BehaviourRegistry.register(behaviour)`. Subscribes to inputs. */\n register(ctx: CanvasContext): void {\n if (this.ctx !== undefined) {\n throw new Error(`Behaviour \"${this.id}\" already registered`);\n }\n this.ctx = ctx;\n this.onRegister(ctx);\n this.watchMode();\n this._enabled = this._wanted && this._inMode;\n if (this._enabled) this.onEnable();\n }\n\n /** Called by `BehaviourRegistry.unregister(id)`. Drops subscriptions. */\n destroy(): void {\n if (this.ctx === undefined) return;\n const ctx = this.ctx;\n this._enabled = false;\n this._wanted = false;\n this.unwatchMode();\n this.onDestroy(ctx);\n // Safety net (see `GestureArbiter`): a claim stranded by an unmount would\n // freeze the camera and every other gesture for the life of the canvas.\n this.releaseGesture();\n this.ctx = undefined;\n }\n\n enable(): void {\n if (this._wanted) return;\n this._wanted = true;\n this.syncLive();\n }\n\n disable(): void {\n if (!this._wanted) return;\n this._wanted = false;\n this.syncLive();\n }\n\n /**\n * Bring {@link _enabled} in line with `_wanted && _inMode`, running the\n * matching hook on a change. The single place a behaviour goes live or idle.\n */\n private syncLive(): void {\n const live = this._wanted && this._inMode;\n if (live === this._enabled) return;\n this._enabled = live;\n if (live) {\n this.onEnable();\n } else {\n this.onDisable();\n // Same safety net as `destroy()` — disabling mid-gesture must not strand\n // the claim, even if the subclass forgot to end its drag.\n this.releaseGesture();\n }\n }\n\n /** Is `mode` one this behaviour is live in? */\n private matchesMode(mode: string): boolean {\n const modes = this._options.modes;\n if (modes === undefined) return true;\n if (modes.includes(`!${mode}`)) return false;\n return !modes.some((m) => !m.startsWith('!')) || modes.includes(mode);\n }\n\n /**\n * Follow `view.interaction.viewMode` while registered and `modes` is set;\n * otherwise stop following and count as in-mode. Idempotent — `setOptions`\n * calls it again when `modes` changes.\n */\n private watchMode(): void {\n const ctx = this.ctx;\n if (ctx === undefined || this._options.modes === undefined) {\n this.unwatchMode();\n this._inMode = true;\n return;\n }\n const view = ctx.store.view;\n this._inMode = this.matchesMode(view.getState().interaction.viewMode);\n if (this._modeUnsub !== null) return;\n this._modeUnsub = view.subscribe((state, prev) => {\n if (state.interaction.viewMode === prev.interaction.viewMode) return;\n this._inMode = this.matchesMode(state.interaction.viewMode);\n this.syncLive();\n });\n }\n\n private unwatchMode(): void {\n this._modeUnsub?.();\n this._modeUnsub = null;\n }\n\n /**\n * Merge a serialisable options patch and apply it live. Reflects an `enabled`\n * change by enabling/disabling, then calls {@link onOptionsChanged} so the\n * subclass can apply the rest (re-sync cached fields, re-arm a viewport\n * plugin, recompute). This is the seam the engine's\n * `canvas.update({ behaviours: { [id]: patch } })` path invokes — so a settings\n * editor can retune any behaviour without remounting it.\n *\n * Subclasses with bespoke apply logic (e.g. clearing selection state on a\n * mode change) override this and should call `super.setOptions(changes)` first\n * to keep `_options` — and thus {@link getOptions} — coherent.\n */\n setOptions(changes: Partial<TOptions>): void {\n this._options = { ...this._options, ...changes };\n if ('modes' in changes) this.setModes(changes.modes);\n if (changes.enabled !== undefined) this.applyEnabled(changes.enabled);\n this.onOptionsChanged(changes);\n }\n\n /**\n * Apply an `enabled` option. While this instance is the one mounted under its\n * id, the toggle goes through the registry so `scene:behaviour:enable` /\n * `disable` and the gesture-conflict warning fire — calling {@link enable}\n * directly would leave the registry's own `setEnabled` (the engine's\n * `canvas.update` path) a silent no-op. Unmounted, or superseded by a newer\n * instance under the same id, it toggles itself directly.\n */\n private applyEnabled(enabled: boolean): void {\n const registry = this.ctx?.behaviours;\n if (registry && registry.get(this.id) === this) {\n registry.setEnabled(this.id, enabled);\n } else if (enabled) {\n this.enable();\n } else {\n this.disable();\n }\n }\n\n /**\n * Replace {@link BehaviourOptions.modes} and re-evaluate liveness against the\n * current interaction mode. `undefined` = live in every mode.\n */\n setModes(modes: readonly string[] | undefined): void {\n this._options = { ...this._options, modes };\n this.watchMode();\n this.syncLive();\n }\n\n /**\n * Merge `changes` into the options {@link getOptions} returns — and nothing\n * else: no enable / disable, no mode re-wiring, no {@link onOptionsChanged}.\n *\n * For subclasses that override {@link setOptions} with their own apply logic\n * and don't call `super`: call this first so `getOptions()` (a settings\n * editor's seed, the engine's undo baseline) stays current. Prefer it to\n * `super.setOptions` there: the engine routes `enabled` / `modes` through\n * the registry itself, and the base's direct `enable()` would pre-empt the\n * registry's `scene:behaviour:enable` event.\n */\n protected recordOptions(changes: Partial<TOptions>): void {\n this._options = { ...this._options, ...changes };\n }\n\n /** Snapshot of the current (merged) options — seeds a settings editor. */\n getOptions(): Readonly<TOptions> {\n return this._options;\n }\n\n /**\n * Contribute this behaviour's serialisable config to a canvas-state snapshot\n * (the engine's `DefinitionSerializable` contract). The base implementation\n * captures the explicit `enabled` flag (rule 7). Subclasses with additional\n * JSON-serialisable options should override and spread `super.serializeDefinition()`.\n */\n serializeDefinition(): Record<string, unknown> | undefined {\n const modes = this._options.modes;\n return modes === undefined ? { enabled: this._wanted } : { enabled: this._wanted, modes: [...modes] };\n }\n\n // ─── Subclass hooks ──────────────────────────────────────────────────────\n\n /** Subscribe to events / setup any handler resources. */\n protected abstract onRegister(ctx: CanvasContext): void;\n\n /** Cleanup on destroy. Default no-op. */\n protected onDestroy(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /** Hook fired when the developer enables the behaviour. */\n protected onEnable(): void {\n /* default no-op */\n }\n\n /** Hook fired on disable. */\n protected onDisable(): void {\n /* default no-op */\n }\n\n /**\n * Hook fired after {@link setOptions} merges a patch (and after any `enabled`\n * toggle is applied). Default no-op. Override to apply an option change live:\n * a behaviour whose effect is wired in {@link onEnable} (a pixi-viewport\n * plugin, a DOM listener) re-arms here; one that caches option values in\n * fields re-syncs them from `this._options` here. `changes` is the raw patch;\n * `this._options` already holds the merged result.\n */\n protected onOptionsChanged(_changes: Partial<TOptions>): void {\n /* default no-op */\n }\n\n /**\n * Convenience `if (!enabled) return;` for use inside event handlers\n * (without rebinding `this` cost). `false` while suspended by `modes`.\n */\n protected get isEnabled(): boolean {\n return this._enabled;\n }\n\n // ─── Gesture arbitration ─────────────────────────────────────────────────\n\n /**\n * Take exclusive ownership of the pointer gesture for the duration of a drag\n * (`ctx.gestures`, see `input/GestureArbiter.ts`). Returns `false` when\n * another behaviour already owns it — the caller must then **not** start its\n * gesture, because two behaviours steering the same pointer is exactly what\n * the arbiter exists to prevent.\n *\n * Claiming also suspends camera panning: `DragPanBehaviour` watches the\n * arbiter and yields while anybody else owns the gesture. That replaces the\n * old `camera.viewport.plugins.pause('drag')` reach-through, which put a\n * `pixi-viewport` internal in the hands of domain behaviours.\n *\n * Pair every successful claim with {@link releaseGesture} on **every** exit\n * path — pointerup, pointercancel, abort. `disable()` and `destroy()` release\n * automatically as a backstop.\n */\n protected claimGesture(opts?: GestureClaimOptions): boolean {\n const gestures = this.ctx?.gestures;\n if (!gestures) return false;\n const release = gestures.claim(this.id, opts);\n if (release === null) return false;\n this._gestureRelease = release;\n return true;\n }\n\n /**\n * End this behaviour's gesture claim. Safe to call any number of times and\n * when no claim is held — the arbiter identifies claims by token, so a stale\n * release can never evict a later owner.\n */\n protected releaseGesture(): void {\n const release = this._gestureRelease;\n this._gestureRelease = null;\n release?.();\n }\n\n /** Does this behaviour currently hold the gesture? */\n protected get hasGestureClaim(): boolean {\n return this._gestureRelease !== null;\n }\n\n /**\n * Re-run {@link onDisable} then {@link onEnable} when the behaviour is live, so\n * an option change wired at enable-time (a pixi-viewport plugin, a listener\n * bound with the old config) picks up `this._options`. No-op when disabled or\n * unregistered (the next {@link onEnable} will read the fresh options anyway).\n * The idiomatic body of an {@link onOptionsChanged} override for such\n * behaviours.\n */\n protected reArm(): void {\n if (this._enabled && this.ctx !== undefined) {\n this.onDisable();\n this.onEnable();\n }\n }\n}\n","/**\n * `Layout` — function from data to positions.\n *\n * Architecture: see `architecture-proposal.md` §2.3.\n *\n * Per the proposal:\n * - A Layout does NOT register with the canvas.\n * - It does NOT render.\n * - It does NOT subscribe to input.\n * - You instantiate it and call it against a layer.\n *\n * const layout = new D3ForceLayout({ charge: -300 });\n * layout.events.on('end', () => canvas.camera.fitContent(...));\n * await layout.apply(graphLayer);\n *\n * Continuous-running cases (e.g. always-relax force simulation) are handled\n * by a thin wrapper Behaviour that calls `apply()` on a tick — keeps the\n * Layout API clean while supporting the rare continuous case.\n *\n * Whether two layouts conflict is a domain concern (don't apply two layouts\n * to the same data) — not enforced here.\n *\n * ## Lifecycle events\n *\n * Every layout owns a typed `events` emitter and fires three lifecycle\n * events around `apply()`:\n *\n * - `start` — emitted once, synchronously, after the layout has set up\n * its internal state and just before it begins producing positions.\n * - `tick` — emitted whenever the layout writes a fresh batch of positions.\n * One-shot layouts (e.g. ELK) fire it once. Iterative layouts (force\n * sims) fire it on every iteration. High-frequency; subscribe sparingly.\n * - `end` — emitted once when the run terminates. `reason` distinguishes\n * a natural settle from an external `stop()` call.\n *\n * Subscribe to these events to drive camera fits, progress UI, etc. —\n * instead of listening to per-tick `data:changed` on the layer, which\n * conflates \"structure changed\" with \"positions updated\".\n */\n\nimport { EventEmitter } from '../state/events/EventEmitter';\nimport type { Layer } from './Layer';\n\n/**\n * Why the run ended.\n *\n * - `completed` — the layout settled / finished on its own.\n * - `stopped` — `stop()` (or a second `apply()`) cancelled it.\n */\nexport type LayoutEndReason = 'completed' | 'stopped';\n\n/**\n * Lifecycle events fired by every `Layout`.\n *\n * Subclass-specific telemetry (e.g. d3-force's `alpha`) belongs on a\n * subclass-specific event map, not here.\n */\nexport type LayoutEvents = {\n /**\n * Run is about to produce positions. Optional run-size / animation metadata\n * lets a `Canvas.runLayout` bridge forward it onto the canvas bus as\n * `layout:run:start` without reaching into layer internals. Every field is\n * optional — a layout that doesn't know (or care) emits `{}`, and the bridge\n * substitutes `0` / `false`.\n *\n * - `nodeCount` / `edgeCount` — size of the run, for progress UIs / telemetry.\n * - `animate` — whether the run animates its settle (iterative force sims)\n * vs. jumps straight to final positions; render policies branch on it.\n */\n start: { nodeCount?: number; edgeCount?: number; animate?: boolean };\n tick: Record<string, never>;\n /**\n * A position **transition** advanced one frame — a one-shot layout gliding\n * nodes from where they were to where the run put them. `progress` is the\n * **eased** fraction of the glide, `0..1`, and reaches exactly `1` on the\n * last frame (before `end`). A run that snaps emits none.\n *\n * Separate from `tick` on purpose: `tick` means \"the layout placed nodes\",\n * and fitters react to it as such; this is per-frame motion, which a\n * {@link LayoutRunOptions.fitCamera} run follows with the camera.\n */\n transition: { progress: number };\n /**\n * An off-screen solve advanced: `done` of `total` iterations are finished.\n * Emitted by iterative layouts that settle before drawing (d3-force with\n * `animate: false`), so a UI can say why the canvas is still empty.\n *\n * Separate from `tick` on purpose: `tick` means \"positions were written\",\n * and the graph layer reveals nodes on it — progress writes nothing.\n */\n progress: { done: number; total: number };\n end: { reason: LayoutEndReason };\n};\n\n/**\n * How one layout run should behave — passed per call to {@link Layout.apply}\n * (and `Canvas.runLayout`), as opposed to {@link LayoutOptions}, which are the\n * layout's standing configuration.\n *\n * Both fields describe a **re-flow** the user did not ask for directly — e.g.\n * `CollapseExpandBehaviour` re-running the active layout after a group frame\n * opens or closes — where the point is to keep the picture steady.\n */\nexport interface LayoutRunOptions {\n /**\n * Keep this node where it is on screen. The run computes positions as usual,\n * then shifts the whole result so this node's box centre stays where it was;\n * everything else re-flows around it. Honoured by layouts that support it\n * (the one-shot layouts and `D3ForceLayout`); ignored by the rest.\n */\n anchorNodeId?: string;\n /**\n * Leave the camera alone for this run. Fitters that normally re-frame the\n * view when a layout ends (the `fitOnLoad` auto-fitter, the React layout\n * wrappers' `fitPadding`) skip a run carrying this flag.\n */\n preserveCamera?: boolean;\n /**\n * Frame the result, moving the camera **together with** the nodes. While\n * the run's position transition plays, `Canvas.runLayout` blends the camera\n * from where it started toward a fit of the content as it is on that frame\n * (by the transition's eased progress), so the picture stays framed the\n * whole way and ends exactly fitted — no glide under a stale camera\n * followed by a snap. A run that snaps (or a layout that reports no\n * `transition`) gets one fit when it ends. A user pan / zoom mid-run takes\n * the camera and stops the follow.\n *\n * `true` fits with the default padding (80 screen px); `{ padding }` sets\n * it, and `{ maxZoom }` stops the fit zooming in past that scale (`1` keeps\n * a small graph at its drawn size). Fitters that would otherwise frame on `end` (the `fitOnLoad`\n * auto-fitter, the React layout wrappers' `fitPadding`) skip such a run —\n * it already owns the camera. Ignored when {@link preserveCamera} is set.\n */\n fitCamera?: boolean | { padding?: number; maxZoom?: number };\n /**\n * Solve from scratch: ignore the nodes' stored positions as starting points\n * (pinned nodes still hold). For an iterative layout that settles from where\n * the nodes are, a settled graph otherwise falls straight back into the same\n * arrangement, and a graph laid out by another layout keeps that layout's\n * crossings. Honoured by `D3ForceLayout`; a one-shot layout computes from\n * scratch anyway.\n */\n reseed?: boolean;\n}\n\n/** How {@link Layout.setOptions} applies a patch. */\nexport interface LayoutSetOptions {\n /**\n * Re-run a layout that has already run, so the change shows. Default `true`.\n * `false` when the same write is about to run the layout anyway — a canvas\n * passes it for the layout an `activeLayout` write names — so a switch is one\n * run, carrying that run's options.\n */\n rerun?: boolean;\n}\n\n/**\n * How an **active** layout re-runs when its target layer's data changes\n * (nodes added / removed / hidden / shown). Read by the facade that wires the\n * active layout (`GraphCanvas`) each time it re-runs, so assigning\n * {@link Layout.onData} takes effect on the next change.\n */\nexport interface LayoutDataRunOptions {\n /**\n * At most one data-triggered run per this many ms: the first change runs at\n * once, later ones inside the window collapse into one run at its end — so\n * a feed writing every tick doesn't restart the layout every tick. Default\n * `0` (every change runs).\n */\n throttleMs?: number;\n /**\n * Leave the camera alone on data-triggered runs\n * ({@link LayoutRunOptions.preserveCamera}) — the view doesn't re-frame each\n * time the data changes. Default `false`.\n */\n preserveCamera?: boolean;\n}\n\n/** Construction options every layout shares (for the `LayoutRegistry`). */\nexport interface LayoutOptions {\n /** Stable id, used to address the layout in a `LayoutRegistry` / config. Default `'layout'`. */\n id?: string;\n /** The layer this layout is meant to run against. Informational — `apply(layer)` still takes one explicitly. */\n targetLayerId?: string;\n /** How data-triggered re-runs behave while this layout is active. See {@link LayoutDataRunOptions}. */\n onData?: LayoutDataRunOptions;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport abstract class Layout<TLayer extends Layer<any, any, any, any> = Layer<any, any, any, any>> {\n /** Stable id (registry / config key). */\n readonly id: string;\n /** The layer this layout targets, if declared at construction. */\n readonly targetLayerId?: string;\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'d3-force-layout'`,\n * `'elk-layout'`). Distinct from {@link id} (the per-instance key): all\n * `D3ForceLayout` instances share `kind: 'd3-force-layout'`. Concrete layouts\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n\n /**\n * Lifecycle event bus. See class docs for the event vocabulary.\n * Subclasses with richer telemetry can declare their own typed\n * emitter on top (`override readonly events = new EventEmitter<MyEvents>()`).\n */\n readonly events: EventEmitter<LayoutEvents> = new EventEmitter<LayoutEvents>();\n\n /**\n * Options of the run in flight, or of the last one once it has ended.\n * Implementations record them at the top of {@link apply}, so an `end`\n * listener can tell what kind of run just finished — e.g. a fitter skipping\n * a {@link LayoutRunOptions.preserveCamera} run.\n */\n runOptions: Readonly<LayoutRunOptions> = {};\n\n /**\n * How data-triggered re-runs behave while this layout is active (throttle,\n * keep the camera). Mutable: the wiring reads it on every data change.\n */\n onData: LayoutDataRunOptions;\n\n constructor(opts: LayoutOptions = {}) {\n this.id = opts.id ?? 'layout';\n this.targetLayerId = opts.targetLayerId;\n this.onData = { ...(opts.onData ?? {}) };\n }\n\n /**\n * Live-reconfigure. Called by `Canvas.update({ layouts: { id: patch } })`.\n * Default no-op; layouts override to merge the patch and, unless\n * `opts.rerun` is `false`, re-run so the change shows.\n */\n setOptions(_patch: unknown, _opts?: LayoutSetOptions): void {\n /* default no-op */\n }\n\n /**\n * Contribute this layout's serialisable config to a canvas-state snapshot (the\n * engine's `DefinitionSerializable` contract). The base captures the wiring\n * `targetLayerId`; iterative layouts holding tunable params (e.g. force\n * strengths) should override and spread `super.serializeDefinition()` with a\n * JSON-safe copy of those params.\n */\n serializeDefinition(): Record<string, unknown> | undefined {\n const out: Record<string, unknown> = {};\n if (this.targetLayerId !== undefined) out.targetLayerId = this.targetLayerId;\n if (Object.keys(this.onData).length > 0) out.onData = { ...this.onData };\n return Object.keys(out).length > 0 ? out : undefined;\n }\n\n /**\n * Run the layout against `layer`. Resolves when the run terminates\n * (either a natural settle or an external `stop()`).\n *\n * Calling `apply()` again on the same instance must cancel any in-flight\n * run first, and must record `run` on {@link runOptions} before emitting\n * `start`.\n *\n * @param run How this particular run should behave; see {@link LayoutRunOptions}.\n */\n abstract apply(layer: TLayer, run?: LayoutRunOptions): Promise<void>;\n}\n","/**\n * `GestureArbiter` — who owns the pointer right now.\n *\n * Architecture: see `docs/renderer-split-design.md` §9 (P5).\n *\n * **Why this exists.** Before P5, a behaviour that needed the camera to stop\n * panning during its own gesture reached for `camera.viewport.plugins.pause('drag')`\n * — sixteen calls across six behaviours, every one of them poking at a\n * `pixi-viewport` internal from domain code. The thing they actually wanted was\n * never a camera API: it was *exclusivity*. A node drag, a lasso, a brush, a\n * resize and an edge draw are all mutually exclusive pointer gestures, and the\n * camera pan is simply the lowest-priority one of them.\n *\n * So the arbiter models the real invariant — **at most one owner at a time** —\n * and the camera becomes a subscriber like anything else: `DragPanBehaviour`\n * yields while {@link GestureArbiter.owner} names somebody else. That inverts\n * the old direction (others suspending the camera) into the camera suspending\n * itself, which is what lets the pixi-viewport handle move into the renderer\n * package in P6 without dragging six domain behaviours along with it.\n *\n * **Leak safety is the whole design.** A claim that is never released freezes\n * every gesture *and* the camera, which is worse than the failure it replaces.\n * Three properties defend against that:\n *\n * 1. **Release is token-identified.** The function returned by\n * {@link GestureArbiter.claim} only clears *that* claim. Calling it twice is a\n * no-op, and calling a stale one can never evict a later owner.\n * 2. **A re-claim by the current owner always succeeds.** A behaviour that\n * leaks its own claim can never deadlock *itself* out of its next gesture —\n * the old token is simply invalidated.\n * 3. **`Behaviour` releases on `disable()` and `destroy()`** regardless of what\n * the subclass did (see `Behaviour.claimGesture`), so unmount and mid-gesture\n * teardown can't strand a claim.\n */\n\n/** Options for a single {@link GestureArbiter.claim}. */\nexport interface GestureClaimOptions {\n /**\n * Higher wins. A claim is refused when another owner holds the gesture at an\n * equal or higher priority; a strictly higher priority **pre-empts** the\n * current owner (whose {@link GestureClaimOptions.onRevoke} fires and whose\n * release function goes inert). Default `0` — every built-in behaviour claims\n * at the default, so no pre-emption happens unless a consumer asks for it.\n */\n priority?: number;\n\n /**\n * Called when this claim is pre-empted by a higher-priority owner. The seam\n * a long-running gesture uses to abort cleanly instead of continuing to move\n * things while somebody else drives the pointer. Not called on a normal\n * release, nor when the same owner re-claims.\n */\n onRevoke?: () => void;\n}\n\n/**\n * Arbitrates exclusive ownership of the pointer gesture. Reached as\n * `ctx.gestures`; provided per-`Canvas`.\n */\nexport interface GestureArbiter {\n /**\n * Try to take the gesture for `owner` (by convention the behaviour's `id`).\n * Returns a **release** function on success, or `null` when another owner\n * already holds it at an equal-or-higher priority — in which case the caller\n * should not start its gesture.\n *\n * Release is idempotent and identity-checked: calling it after the claim has\n * already ended (or been pre-empted) does nothing, so it can never clear\n * somebody else's claim.\n */\n claim(owner: string, opts?: GestureClaimOptions): (() => void) | null;\n\n /** The current owner id, or `null` when the gesture is free. */\n readonly owner: string | null;\n\n /**\n * Subscribe to ownership changes — the hook `DragPanBehaviour` uses to\n * suspend and restore camera panning. Fires with the new owner (`null` when\n * released). Returns an unsubscribe function.\n */\n onOwnerChange(listener: (owner: string | null) => void): () => void;\n}\n\n/** The live claim, plus the token that authorises releasing it. */\ninterface ActiveClaim {\n readonly owner: string;\n readonly priority: number;\n /** Identity of this specific claim — what makes release non-transferable. */\n readonly token: symbol;\n readonly onRevoke?: () => void;\n}\n\n/**\n * The default in-memory {@link GestureArbiter}. Renderer-free and DOM-free: it\n * knows nothing about pointers, only about who asked first.\n */\nexport class DefaultGestureArbiter implements GestureArbiter {\n private active: ActiveClaim | null = null;\n private readonly listeners = new Set<(owner: string | null) => void>();\n\n get owner(): string | null {\n return this.active?.owner ?? null;\n }\n\n claim(owner: string, opts?: GestureClaimOptions): (() => void) | null {\n const priority = opts?.priority ?? 0;\n const current = this.active;\n const sameOwner = current?.owner === owner;\n\n // Refuse only a *different* owner that isn't out-prioritised. Letting the\n // current owner re-claim keeps a behaviour that leaked its own release from\n // locking itself out forever (property 2 in the file docblock).\n if (current && !sameOwner && priority <= current.priority) return null;\n\n const token = Symbol(owner);\n this.active = { owner, priority, token, onRevoke: opts?.onRevoke };\n\n // Notify the loser *after* `active` is swapped, so an `onRevoke` that calls\n // its own (now stale) release sees the mismatch and no-ops.\n if (current && !sameOwner) current.onRevoke?.();\n if (!sameOwner) this.emit();\n\n return () => this.release(token);\n }\n\n onOwnerChange(listener: (owner: string | null) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Drop the claim identified by `token`. A stale token — from a released or\n * pre-empted claim — is ignored, which is what makes double-release safe.\n */\n private release(token: symbol): void {\n if (this.active?.token !== token) return;\n this.active = null;\n this.emit();\n }\n\n /** Snapshot before iterating: a listener may unsubscribe from inside itself. */\n private emit(): void {\n const owner = this.owner;\n for (const listener of [...this.listeners]) listener(owner);\n }\n}\n","import type { ReactiveStore } from './types';\n\n/** Reference-equality default; selector slices are compared with this. */\nexport function defaultEqual<U>(a: U, b: U): boolean {\n return Object.is(a, b);\n}\n\n/** Shallow-equal for objects/arrays — a common selector equality for derived slices. */\nexport function shallowEqual<U>(a: U, b: U): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;\n const ak = Object.keys(a as Record<string, unknown>);\n const bk = Object.keys(b as Record<string, unknown>);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/** A subscribable view of one selected slice — what `useSyncExternalStore` binds to. */\nexport interface Selected<U> {\n get(): U;\n subscribe(onChange: () => void): () => void;\n}\n\n/**\n * Project a {@link ReactiveStore} to one slice, re-notifying **only** when that\n * slice changes (by `isEqual`). Selector + equality semantics live here — in our\n * code, not the backend — so they survive a backend swap. The React `useStore`\n * hook (in `@invana/canvas-react`) binds this to `useSyncExternalStore`.\n */\nexport function select<T, U>(\n store: ReactiveStore<T>,\n selector: (state: T) => U,\n isEqual: (a: U, b: U) => boolean = defaultEqual,\n): Selected<U> {\n return {\n get: () => selector(store.getState()),\n subscribe: (onChange) => {\n let current = selector(store.getState());\n return store.subscribe((state) => {\n const next = selector(state);\n if (!isEqual(current, next)) {\n current = next;\n onChange();\n }\n });\n },\n };\n}\n","/**\n * Easing functions consumed by `Tween`. Each is a pure `(t: number) => number`\n * where `t ∈ [0, 1]` is normalised progress and the return value is the eased\n * progress (also typically in `[0, 1]`, though overshoot easings may exceed).\n *\n * Naming follows the standard easing taxonomy (Penner et al). Add new entries\n * here rather than inline-defining easings in effect / decoration code so the\n * set stays consistent across animated primitives.\n */\n\nexport type Easing = (t: number) => number;\n\nexport const linear: Easing = (t) => t;\n\nexport const easeInOutSine: Easing = (t) => -(Math.cos(Math.PI * t) - 1) / 2;\n\nexport const easeOutCubic: Easing = (t) => 1 - Math.pow(1 - t, 3);\n\nexport const easeInOutCubic: Easing = (t) =>\n t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n\nexport const easeOutQuad: Easing = (t) => 1 - (1 - t) * (1 - t);\n\n/**\n * Stable string keys for the built-in easings.\n *\n * Serializable easing handle — use this (not an `Easing` function) anywhere an\n * easing must live in JSON config or bind to a `<select>` / lil-gui dropdown\n * (e.g. a layout's `transitionEase`). Resolve to the function with\n * {@link resolveEasing}.\n */\nexport type EasingName = 'linear' | 'easeInOutSine' | 'easeOutCubic' | 'easeInOutCubic' | 'easeOutQuad';\n\n/** Registry backing {@link resolveEasing}. Keep in sync with {@link EasingName}. */\nconst EASINGS: Record<EasingName, Easing> = {\n linear,\n easeInOutSine,\n easeOutCubic,\n easeInOutCubic,\n easeOutQuad,\n};\n\n/** All built-in easing names — handy for populating a picker. */\nexport const EASING_NAMES = Object.keys(EASINGS) as EasingName[];\n\n/**\n * Resolve an {@link EasingName} (or `undefined`) to its `Easing` function,\n * falling back to `fallback` (default {@link easeOutCubic}) for an unknown or\n * missing name. Lets config carry a serializable easing key while runtime code\n * gets the function.\n */\nexport function resolveEasing(name: EasingName | undefined, fallback: Easing = easeOutCubic): Easing {\n return (name && EASINGS[name]) || fallback;\n}\n","import { linear, type Easing } from './easings';\n\n/**\n * Options for constructing a `Tween`. `from` / `to` / `duration` are required;\n * everything else is optional and falls back to a sensible default.\n *\n * - `easing` defaults to `linear`.\n * - `repeat` is either an integer count (number of additional cycles after the\n * first) or `'forever'`. Defaults to `0` (play once).\n * - `yoyo` reverses direction on each repeat. Only meaningful when `repeat`\n * is non-zero. Defaults to `false`.\n * - `onUpdate(value)` fires every `tick` with the current eased value.\n * - `onComplete()` fires once when the tween retires (final cycle ends).\n * Never fires for `repeat: 'forever'`.\n */\nexport interface TweenOptions {\n readonly from: number;\n readonly to: number;\n readonly duration: number;\n readonly easing?: Easing;\n readonly repeat?: number | 'forever';\n readonly yoyo?: boolean;\n readonly onUpdate?: (value: number) => void;\n readonly onComplete?: () => void;\n}\n\n/**\n * Time-based interpolation primitive. Authors call `tick(deltaMs)` once per\n * frame; the tween advances internal time, applies easing, fires `onUpdate`,\n * and returns `false` when finished so the caller can retire it.\n *\n * The tween itself does no scheduling — it's a pure state machine. Effects\n * and decorations hold a `Tween` and drive it from their own `tick(dt)`.\n *\n * Reusable: call `reset()` to play again from `from`.\n */\nexport class Tween {\n private readonly opts: TweenOptions;\n private readonly easing: Easing;\n private readonly maxRepeat: number;\n private elapsed = 0;\n private cycle = 0;\n private _value: number;\n private _done = false;\n\n constructor(opts: TweenOptions) {\n this.opts = opts;\n this.easing = opts.easing ?? linear;\n this.maxRepeat =\n opts.repeat === 'forever'\n ? Number.POSITIVE_INFINITY\n : (opts.repeat ?? 0);\n this._value = opts.from;\n }\n\n get value(): number {\n return this._value;\n }\n\n get done(): boolean {\n return this._done;\n }\n\n /**\n * Advance by `dt` milliseconds. Returns `false` when the tween has finished\n * its final cycle; callers should remove finished tweens from their tick\n * set. Returns `true` while still running (including indefinitely for\n * `repeat: 'forever'`).\n */\n tick(dt: number): boolean {\n if (this._done) return false;\n\n this.elapsed += dt;\n const { duration, from, to, onUpdate, onComplete } = this.opts;\n const yoyo = this.opts.yoyo ?? false;\n\n // Walk cycles in case `dt` is larger than one cycle (e.g. tab regained focus).\n while (this.elapsed >= duration && this.cycle < this.maxRepeat) {\n this.elapsed -= duration;\n this.cycle += 1;\n }\n\n if (this.cycle >= this.maxRepeat && this.elapsed >= duration) {\n // Final cycle complete — snap to end value and retire.\n const reversed = yoyo && this.maxRepeat % 2 === 1;\n this._value = reversed ? from : to;\n this._done = true;\n onUpdate?.(this._value);\n onComplete?.();\n return false;\n }\n\n const t = this.elapsed / duration;\n const eased = this.easing(t);\n const reversed = yoyo && this.cycle % 2 === 1;\n this._value = reversed ? to + (from - to) * eased : from + (to - from) * eased;\n onUpdate?.(this._value);\n return true;\n }\n\n /** Restart from `from`. Clears `done`. */\n reset(): void {\n this.elapsed = 0;\n this.cycle = 0;\n this._done = false;\n this._value = this.opts.from;\n }\n}\n","/**\n * `Camera` — the engine's pan/zoom/projection facade.\n *\n * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.camera) and\n * §2.6 (camera input is a Behaviour, not a hard-coded gesture).\n *\n * **Design notes**\n *\n * - **No backend type crosses this class.** The concrete viewport lives behind\n * {@link ICameraBinding} — `PixiViewportBinding` today, an orthographic\n * three.js camera later. Camera owns the *semantics* (clamping, anchored zoom,\n * fit-to-rect, bus events, store sync); the binding owns the realisation\n * (`docs/renderer-split-design.md` §9, P5/P6).\n * - The Camera owns no input gestures — those live in opt-in camera-input\n * `Behaviour`s (proposal §2.6). They configure inputs through\n * {@link Camera.configureInput} / {@link Camera.setDragSuspended} /\n * {@link Camera.onDragStart}, described semantically (`percent`, `modifier`),\n * so a behaviour never names a plugin.\n * - The **binding is the single source of truth** for the transform: Camera\n * reads it back rather than caching, so a gesture driven inside the backend\n * and a programmatic `pan()` can't drift apart.\n * - Coordinate model (uniform scale, no rotation):\n *\n * screen.x = world.x * scale + tx\n * screen.y = world.y * scale + ty\n * world.x = (screen.x - tx) / scale\n * world.y = (screen.y - ty) / scale\n *\n * We deliberately keep `scale.x === scale.y` (no anisotropic zoom) and no\n * rotation. Both are enforceable as needed.\n *\n * - Events are emitted on the canvas-wide `CanvasEventBus`:\n * `camera:zoom`, `camera:pan`. They flow through the tap channel so\n * telemetry sees every camera change.\n */\n\nimport { select } from '../state/port/select';\nimport type { CanvasEventBus } from '../state/events/CanvasEventBus';\nimport type { CanvasStore } from '../state/CanvasStore';\nimport { Tween } from '../lib/animation/Tween';\nimport { resolveEasing, type EasingName } from '../lib/animation/easings';\nimport type { Point, Rect } from '../specs/geom';\nimport type {\n CameraInputConfig,\n CameraTransformValue,\n ICameraBinding,\n} from '../contracts/ICameraBinding';\n\nexport type { Point, Rect };\nexport type {\n CameraInputConfig,\n CameraInputModifier,\n DragInputOptions,\n PinchInputOptions,\n WheelInputOptions,\n} from '../contracts/ICameraBinding';\n\n/** An absolute camera transform — world (0,0) at `(x, y)` screen px, uniform `zoom`. */\nexport type CameraTransform = CameraTransformValue;\n\nexport interface CameraOptions {\n /**\n * The renderer's viewport, behind the pixi-free {@link ICameraBinding} seam.\n * Created by the renderer (`Canvas` wires `PixiViewportBinding` today).\n */\n binding: ICameraBinding;\n /** Initial viewport size in CSS pixels. Mirrors the binding's own screen size for projection math. */\n screenWidth: number;\n screenHeight: number;\n /** Optional bus for `input:camera:zoom` / `input:camera:pan` events. */\n bus?: CanvasEventBus;\n /**\n * Optional kernel store. When present, the camera keeps\n * `store.view.interaction.camera` (the abstract `{x,y,zoom}` transform) in sync\n * with the binding **both ways** — gestures/mutators push into the store,\n * and external `actions.camera.*` writes apply to the binding.\n */\n store?: CanvasStore;\n /** Initial uniform scale. Default 1. */\n initialScale?: number;\n /** Initial world-container offset (= where world (0,0) lives in screen pixels). Default (0,0). */\n initialX?: number;\n initialY?: number;\n /** Min / max zoom clamp. Defaults: 0.01 .. 100. */\n minScale?: number;\n maxScale?: number;\n}\n\nexport class Camera {\n /**\n * The renderer's viewport, behind the pixi-free binding seam. **Private** —\n * nothing outside this class reaches the backend, which is what lets P6 move\n * the realisation into `@invana/renderer-pixijs` without a public break.\n */\n private readonly binding: ICameraBinding;\n\n private readonly bus?: CanvasEventBus;\n\n private _screenWidth: number;\n private _screenHeight: number;\n private readonly _minScale: number;\n private readonly _maxScale: number;\n\n /** Kernel store (optional) — the home of the abstract `interaction.camera` transform. */\n private readonly store?: CanvasStore;\n /** Re-entrancy guard so binding↔store sync never ping-pongs. */\n private _syncing = false;\n /** Unsubscribe for the `interaction.camera` slice subscription. */\n private _offStoreCam?: () => void;\n /** Unsubscribe for the binding's backend-driven transform reports. */\n private _offBindingChange?: () => void;\n /** Whether drag-panning is currently yielded to another gesture owner. */\n private _dragSuspended = false;\n /**\n * In-flight {@link animateTo} tween, or `null`. Holds the endpoints and the\n * eased progress; {@link tick} advances it and writes the interpolated\n * transform through {@link binding} directly, bypassing the public mutators\n * so it cannot cancel itself.\n */\n private _fitTween: {\n readonly from: CameraTransform;\n readonly to: CameraTransform;\n readonly tween: Tween;\n readonly onDone?: () => void;\n } | null = null;\n\n constructor(opts: CameraOptions) {\n this.binding = opts.binding;\n this.bus = opts.bus;\n this.store = opts.store;\n this._screenWidth = opts.screenWidth;\n this._screenHeight = opts.screenHeight;\n this._minScale = opts.minScale ?? 0.01;\n this._maxScale = opts.maxScale ?? 100;\n\n this.binding.setTransform({\n x: opts.initialX ?? 0,\n y: opts.initialY ?? 0,\n zoom: this.clampScale(opts.initialScale ?? 1),\n });\n\n // Bridge backend-driven transform changes to the canvas bus. Without this,\n // interactive pan/zoom (drag, wheel, pinch, momentum — all driven inside the\n // backend) never reaches `camera:pan` / `camera:zoom` listeners, because\n // those mutations bypass Camera's typed mutators. Changes Camera itself\n // makes are not reported back, so there's no double-emit.\n this._offBindingChange = this.binding.onTransformChange((kind) => {\n // A user gesture owns the camera from its first frame — drop any glide.\n // Without this an `animateTo` keeps overwriting the gesture until it\n // lands, and drag-pan momentum then inherits the glide's velocity.\n this.cancelAnimation();\n const t = this.binding.getTransform();\n if (kind === 'zoom') {\n this.bus?.emit('input:camera:zoom', {\n scale: t.zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n }\n this.bus?.emit('input:camera:pan', { x: t.x, y: t.y });\n this.pushToStore();\n });\n\n // Bidirectional bind to `store.view.interaction.camera`: seed it from the\n // initial transform, then apply any external `actions.camera.*` write back\n // onto the binding (the `_syncing` guard breaks the feedback loop).\n if (this.store) {\n this.pushToStore();\n const cameraSlice = select(this.store.view, (s) => s.interaction.camera);\n this._offStoreCam = cameraSlice.subscribe(() => this.applyFromStore());\n }\n }\n\n /**\n * Push the current transform into `store.view.interaction.camera`. Called from\n * every camera mutation (gesture + programmatic). No-op when the store already\n * matches or a store→binding apply is in flight.\n */\n private pushToStore(): void {\n if (!this.store || this._syncing) return;\n const { x, y, zoom } = this.binding.getTransform();\n const cur = this.store.view.getState().interaction.camera;\n if (cur.x === x && cur.y === y && cur.zoom === zoom) return;\n this._syncing = true;\n try {\n this.store.actions.camera.set({ x, y, zoom });\n } finally {\n this._syncing = false;\n }\n }\n\n /**\n * Apply `store.view.interaction.camera` onto the binding — realises an external\n * `actions.camera.*` write. No-op when the binding already matches or a\n * binding→store push is in flight.\n */\n private applyFromStore(): void {\n if (!this.store || this._syncing) return;\n const c = this.store.view.getState().interaction.camera;\n const cur = this.binding.getTransform();\n if (cur.x === c.x && cur.y === c.y && cur.zoom === c.zoom) return;\n this._syncing = true;\n try {\n this.binding.setTransform({ x: c.x, y: c.y, zoom: this.clampScale(c.zoom) });\n } finally {\n this._syncing = false;\n }\n }\n\n // ─── Read accessors ──────────────────────────────────────────────────────\n\n /** Current uniform scale. */\n get scale(): number {\n return this.binding.getTransform().zoom;\n }\n\n /** Current world-container x in screen pixels. (Where world (0,0) sits.) */\n get x(): number {\n return this.binding.getTransform().x;\n }\n\n get y(): number {\n return this.binding.getTransform().y;\n }\n\n get screenWidth(): number {\n return this._screenWidth;\n }\n\n get screenHeight(): number {\n return this._screenHeight;\n }\n\n // ─── Mutators ────────────────────────────────────────────────────────────\n\n /**\n * Set absolute world-container offset. `(x, y)` is where world (0,0) lives\n * in screen pixels. Most consumers want `pan(dx, dy)` instead.\n */\n setPosition(x: number, y: number): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const cur = this.binding.getTransform();\n if (x === cur.x && y === cur.y) return;\n this.binding.setTransform({ x, y, zoom: cur.zoom });\n this.bus?.emit('input:camera:pan', { x, y });\n this.pushToStore();\n }\n\n /** Pan by `(dx, dy)` screen pixels. */\n pan(dx: number, dy: number): void {\n if (dx === 0 && dy === 0) return;\n this.setPosition(this.x + dx, this.y + dy);\n }\n\n /**\n * Write an absolute `{ x, y, zoom }` transform in one step — the seam for a\n * layer mirroring an **external** camera authority (a MapLibre basemap, a\n * remote collaborator's viewport, a replayed session).\n *\n * Unlike `setZoom` + `setPosition`, this re-anchors nothing: the transform\n * lands exactly as given, because the external authority has already solved\n * for it and any re-anchoring here would desync the two views. `zoom` is\n * emitted only when it actually changed — most mirrored gestures are pan-only\n * and the `input:camera:zoom` listeners are O(N) over their tracked elements.\n *\n * @param t The transform to apply.\n * @param opts.clamp Apply the camera's min/max zoom clamp. Default `true`.\n * Pass `false` when mirroring an authority with its own scale range — a web\n * mercator basemap runs to `2 ** 22`, far past the camera's default ceiling\n * of 100, and clamping would silently peg the canvas away from the map.\n */\n setTransform(t: CameraTransform, opts?: { clamp?: boolean }): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const zoom = opts?.clamp === false ? t.zoom : this.clampScale(t.zoom);\n const cur = this.binding.getTransform();\n const zoomChanged = zoom !== cur.zoom;\n if (!zoomChanged && t.x === cur.x && t.y === cur.y) return;\n\n this.binding.setTransform({ x: t.x, y: t.y, zoom });\n\n if (zoomChanged) {\n this.bus?.emit('input:camera:zoom', {\n scale: zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n }\n this.bus?.emit('input:camera:pan', { x: t.x, y: t.y });\n this.pushToStore();\n }\n\n /**\n * Set absolute scale, anchored at the viewport centre. The world point at\n * the centre stays put. For zoom-around-an-arbitrary-point semantics use\n * `zoomAt`.\n */\n setZoom(scale: number): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const next = this.clampScale(scale);\n if (next === this.scale) return;\n this.binding.zoomToCentre(next);\n this.bus?.emit('input:camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x: this.x, y: this.y });\n this.pushToStore();\n }\n\n /**\n * Multiply scale by `factor`, holding the world point under the screen\n * cursor `(centerX, centerY)` in place. Default centre = viewport centre.\n *\n * Bindings offer only centre-anchored zoom, so the arbitrary-anchor math is\n * done here: project the anchor to world, change scale, then translate so the\n * same world point lands at the same screen point.\n */\n zoomAt(\n factor: number,\n centerX: number = this._screenWidth / 2,\n centerY: number = this._screenHeight / 2,\n ): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const before = this.toWorld(centerX, centerY);\n const nextScale = this.clampScale(this.scale * factor);\n if (nextScale === this.scale) return;\n this.binding.setTransform({\n x: centerX - before.x * nextScale,\n y: centerY - before.y * nextScale,\n zoom: nextScale,\n });\n this.bus?.emit('input:camera:zoom', { scale: nextScale, centerX, centerY });\n this.bus?.emit('input:camera:pan', { x: this.x, y: this.y });\n this.pushToStore();\n }\n\n /**\n * Fit a world-space rectangle into the viewport. Scales so the whole rect\n * is visible (limited by the smaller axis), centres it. `padding` is in\n * screen pixels around the rect.\n */\n fitContent(worldRect: Rect | null | undefined, padding = 24): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n // `null` means \"nothing to measure\" — an empty graph, or a layer whose\n // renderer hasn't mounted. Fitting to a zero rect would produce a nonsense\n // camera, so the honest response is to leave the view alone. Accepting it\n // here keeps the null-check out of every call site\n // (`docs/renderer-split-design.md` D3).\n if (!worldRect) return;\n const availW = Math.max(1, this._screenWidth - padding * 2);\n const availH = Math.max(1, this._screenHeight - padding * 2);\n const scaleX = availW / Math.max(1, worldRect.width);\n const scaleY = availH / Math.max(1, worldRect.height);\n const next = this.clampScale(Math.min(scaleX, scaleY));\n\n const cx = worldRect.x + worldRect.width / 2;\n const cy = worldRect.y + worldRect.height / 2;\n const tx = this._screenWidth / 2 - cx * next;\n const ty = this._screenHeight / 2 - cy * next;\n\n this.binding.setTransform({ x: tx, y: ty, zoom: next });\n\n this.bus?.emit('input:camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x: tx, y: ty });\n this.pushToStore();\n }\n\n /**\n * Centre the viewport on a world-space point — pan so `(worldX, worldY)`\n * maps to the screen centre, keeping the current zoom. The pan-only\n * counterpart to {@link fitContent}: use it for \"focus\" / \"go to\" actions\n * that should locate a target without rescaling the view.\n *\n * By default the pan is applied at once. Pass a positive `durationMs` to\n * glide there instead — the move then runs through {@link animateTo}, so it\n * follows the same rules: eased, and cancelled by any other camera write.\n *\n * @param durationMs Length of the glide. Absent or `<= 0` pans immediately.\n * @param easing Named curve for the glide; defaults to `'easeOutCubic'`.\n * @param onDone Called once the camera is on target (immediately when\n * not gliding; never when a glide is cancelled).\n */\n centerOn(\n worldX: number,\n worldY: number,\n { durationMs = 0, easing, onDone }:\n { durationMs?: number; easing?: EasingName; onDone?: () => void } = {},\n ): void {\n const scale = this.scale;\n const tx = this._screenWidth / 2 - worldX * scale;\n const ty = this._screenHeight / 2 - worldY * scale;\n if (durationMs > 0) {\n this.animateTo(\n { x: tx, y: ty, zoom: scale },\n { durationMs, ...(easing ? { easing } : {}), ...(onDone ? { onDone } : {}) },\n );\n return;\n }\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n this.binding.setTransform({ x: tx, y: ty, zoom: scale });\n this.bus?.emit('input:camera:pan', { x: tx, y: ty });\n this.pushToStore();\n onDone?.();\n }\n\n /** Update on viewport resize. Forwarded so the binding's own math stays correct. */\n resize(screenWidth: number, screenHeight: number): void {\n this._screenWidth = screenWidth;\n this._screenHeight = screenHeight;\n this.binding.resize(screenWidth, screenHeight);\n }\n\n // ─── Projection ──────────────────────────────────────────────────────────\n\n /** Screen → world. */\n toWorld(screenX: number, screenY: number): Point {\n return this.binding.toWorld(screenX, screenY);\n }\n\n /** World → screen. */\n toScreen(worldX: number, worldY: number): Point {\n return this.binding.toScreen(worldX, worldY);\n }\n\n /**\n * The world-space rectangle currently visible. Used by viewport culling\n * (per `decorations-plan.md` §11.6) and minimap layers.\n */\n getVisibleBounds(): Rect {\n return this.binding.getVisibleBounds();\n }\n\n // ─── Input configuration ─────────────────────────────────────────────────\n\n /**\n * Configure the camera's own pan / zoom inputs. This is the seam camera-input\n * behaviours use instead of naming a backend plugin: the options are described\n * semantically (`percent`, `modifier`) and the realisation lives in the\n * binding, so `DragPanBehaviour` / `WheelZoomBehaviour` / `PinchZoomBehaviour`\n * survive the renderer swap unchanged.\n *\n * Patch semantics — an omitted key is left alone, `null` removes that input:\n *\n * ```ts\n * camera.configureInput({ wheel: { percent: 0.2, modifier: 'control' } });\n * camera.configureInput({ wheel: null }); // wheel zoom off, pinch untouched\n * ```\n *\n * Re-configuring an already-installed input replaces it, because the\n * underlying inputs read their config only at install time.\n */\n configureInput(config: CameraInputConfig): void {\n if (config.drag !== undefined) this._dragSuspended = false;\n this.binding.configureInput(config);\n }\n\n /**\n * Suspend / restore drag-panning without tearing the input down. This is how\n * gesture arbitration yields the camera: while another behaviour owns the\n * pointer (a node drag, a lasso, a resize) panning is suspended, and it\n * resumes when that gesture releases.\n *\n * Momentum is deliberately left running, so an in-flight glide finishes as it\n * always has. Edge-triggered — restoring resets the underlying input, so a\n * repeated call in the same state is a no-op.\n */\n setDragSuspended(suspended: boolean): void {\n if (suspended === this._dragSuspended) return;\n this._dragSuspended = suspended;\n this.binding.setDragSuspended(suspended);\n }\n\n /**\n * Subscribe to the start of a drag-pan gesture — fired once the pointer has\n * actually moved enough to pan. `DragPanBehaviour` uses it as the cursor\n * fallback for the `space` modifier, which can't be read off a pointer event.\n *\n * @returns an unsubscribe function.\n */\n onDragStart(fn: () => void): () => void {\n return this.binding.onDragStart(fn);\n }\n\n // ─── Internal ────────────────────────────────────────────────────────────\n\n /**\n * Ease the camera to an absolute transform over `durationMs`, instead of\n * snapping to it.\n *\n * The animated counterpart of {@link setTransform}, and the mechanism behind\n * `CanvasConfig.fitAnimation`: the first auto-fit of a canvas can glide into\n * frame rather than cutting. `x`, `y` and `zoom` are interpolated together on\n * one eased curve, so the move reads as a single gesture.\n *\n * **Any other camera write cancels it.** A user who pans or zooms mid-glide\n * owns the camera from that moment — an animation that fought back would be\n * the `fitOnResize` mistake in a different costume (`D7`). The tween is also\n * dropped, not finished, so `onDone` does not fire.\n *\n * Requires {@link tick} to be called each frame, which `Canvas.tickOnce` does.\n *\n * @param to Target transform. `zoom` is clamped like any other write.\n * @param durationMs Length of the glide. `<= 0` applies `to` immediately.\n * @param easing Named curve; defaults to `'easeOutCubic'`.\n * @param onDone Called once the glide completes naturally.\n */\n animateTo(\n to: CameraTransform,\n { durationMs = 400, easing, onDone }:\n { durationMs?: number; easing?: EasingName; onDone?: () => void } = {},\n ): void {\n const target: CameraTransform = { x: to.x, y: to.y, zoom: this.clampScale(to.zoom) };\n if (durationMs <= 0) {\n this.setTransform(target);\n onDone?.();\n return;\n }\n // Cancel any glide already running before reading `from`, so a second call\n // starts from where the camera actually is rather than compounding.\n this._fitTween = null;\n const from = this.binding.getTransform();\n this._fitTween = {\n from: { x: from.x, y: from.y, zoom: from.zoom },\n to: target,\n tween: new Tween({ from: 0, to: 1, duration: durationMs, easing: resolveEasing(easing) }),\n ...(onDone ? { onDone } : {}),\n };\n }\n\n /**\n * Drop an in-flight {@link animateTo} without finishing it. Called by every\n * public transform mutator, so whoever writes last owns the camera.\n */\n cancelAnimation(): void {\n this._fitTween = null;\n }\n\n /** Whether an {@link animateTo} glide is currently running. */\n get isAnimating(): boolean {\n return this._fitTween !== null;\n }\n\n /**\n * Advance time-based input animation (momentum, snap). Called by\n * `Canvas.tickOnce()` every frame — the engine owns the only clock (G3).\n * No-op until a camera-input behaviour enables an input that animates.\n */\n tick(dt: number): void {\n this.binding.tick(dt);\n this.advanceAnimation(dt);\n }\n\n /**\n * Step an {@link animateTo} glide. Writes through {@link binding} rather than\n * the public mutators — those cancel the tween, which would end the glide on\n * its own first frame.\n */\n private advanceAnimation(dt: number): void {\n const anim = this._fitTween;\n if (!anim) return;\n const running = anim.tween.tick(dt);\n const t = anim.tween.value;\n const x = anim.from.x + (anim.to.x - anim.from.x) * t;\n const y = anim.from.y + (anim.to.y - anim.from.y) * t;\n const zoom = anim.from.zoom + (anim.to.zoom - anim.from.zoom) * t;\n this.binding.setTransform({ x, y, zoom });\n this.bus?.emit('input:camera:zoom', {\n scale: zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x, y });\n this.pushToStore();\n if (running) return;\n // Land exactly on the target — an eased curve can finish a hair short.\n this._fitTween = null;\n this.setTransform(anim.to);\n anim.onDone?.();\n }\n\n /** Tear down subscriptions. Called by `Canvas.destroy`. */\n dispose(): void {\n this._offStoreCam?.();\n this._offStoreCam = undefined;\n this._offBindingChange?.();\n this._offBindingChange = undefined;\n }\n\n private clampScale(scale: number): number {\n if (scale < this._minScale) return this._minScale;\n if (scale > this._maxScale) return this._maxScale;\n return scale;\n }\n}\n","/**\n * `LayerRegistry` — stores the Layers added to a Canvas.\n *\n * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.layers).\n *\n * **Responsibilities**\n * - Add / remove (with mount / unmount lifecycle).\n * - Typed `get<T>(id)`.\n * - `byZOrder()` iteration — used by the Canvas tick.\n * - Fires `'scene:layer:add'` / `'scene:layer:remove'` on the bus.\n *\n * **Lifecycle wiring**\n *\n * The registry doesn't itself construct the `CanvasContext` — it would be\n * circular (the registry is a field of the context). Instead the Canvas\n * passes a `getContext()` thunk; `add(layer)` resolves it at the moment of\n * mount. This keeps the registry decoupled from the context's full shape.\n */\n\nimport type { CanvasContext } from '../CanvasContext';\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { ILayer } from '../Layer';\n\nexport interface LayerRegistryOptions {\n /**\n * Resolves the `CanvasContext` at the moment of mount, or `undefined` before\n * the Canvas is initialised. Layers added pre-init are stored and mounted\n * later by `mountAll()`.\n */\n getContext: () => CanvasContext | undefined;\n /** Bus for `layer:added` / `layer:removed` events. */\n bus: CanvasEventBus;\n}\n\nexport class LayerRegistry {\n private readonly layers: Map<string, ILayer> = new Map();\n private readonly getContext: () => CanvasContext | undefined;\n private readonly bus: CanvasEventBus;\n\n /** Cached z-sorted view; invalidated on add/remove/setZIndex. */\n private zOrderCache: ILayer[] | null = null;\n\n constructor(opts: LayerRegistryOptions) {\n this.getContext = opts.getContext;\n this.bus = opts.bus;\n }\n\n /** Number of registered layers. */\n get size(): number {\n return this.layers.size;\n }\n\n /**\n * Add a Layer to the canvas. Mounts immediately if the Canvas is initialised;\n * otherwise the layer waits for `mountAll()` (called by `Canvas.init`). Fires\n * `layer:added`. Throws if `id` is already registered.\n */\n add(layer: ILayer): void {\n if (this.layers.has(layer.id)) {\n throw new Error(`LayerRegistry: layer \"${layer.id}\" already registered`);\n }\n this.layers.set(layer.id, layer);\n this.zOrderCache = null;\n const ctx = this.getContext();\n if (ctx) layer.mount(ctx);\n this.bus.emit('scene:layer:add', { id: layer.id });\n }\n\n /** Mount every not-yet-mounted layer. Called by `Canvas.init` once the context exists. */\n mountAll(): void {\n const ctx = this.getContext();\n if (!ctx) return;\n for (const layer of this.layers.values()) {\n if (!layer.mounted) layer.mount(ctx);\n }\n }\n\n /**\n * Remove a Layer. Calls `layer.unmount()` and fires `layer:removed`.\n * No-op if `id` isn't registered.\n */\n remove(id: string): void {\n const layer = this.layers.get(id);\n if (!layer) return;\n this.layers.delete(id);\n this.zOrderCache = null;\n layer.unmount();\n this.bus.emit('scene:layer:remove', { id });\n }\n\n /** Typed get by id. Returns `undefined` if not found. */\n get<T extends ILayer = ILayer>(id: string): T | undefined {\n return this.layers.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.layers.has(id);\n }\n\n /** Snapshot of all layers in insertion order. */\n list(): readonly ILayer[] {\n return Array.from(this.layers.values());\n }\n\n /**\n * Iterate layers in z-order (low → high). The Canvas tick walks layers in\n * z-order to flush dirty work; rendering order is then determined by\n * pixi's child order (handled by `SurfaceManager.setWorldLayerZ`).\n *\n * The result is cached and reused until `add` / `remove` / `setZIndex` invalidates.\n */\n byZOrder(): readonly ILayer[] {\n if (this.zOrderCache !== null) return this.zOrderCache;\n const arr = Array.from(this.layers.values());\n arr.sort((a, b) => a.zIndex - b.zIndex);\n this.zOrderCache = arr;\n return arr;\n }\n\n /**\n * Update a layer's `zIndex` and propagate to surfaces. Invalidates the\n * z-order cache. No-op if the layer isn't registered.\n */\n setZIndex(id: string, zIndex: number): void {\n const layer = this.layers.get(id);\n if (!layer) return;\n layer.zIndex = zIndex;\n this.zOrderCache = null;\n // Surface z-order is handled by the layer's mount path (it knows whether\n // it's a WorldLayer or ScreenLayer). For now we just update the field;\n // visual reordering happens on the next render pass by the layer's hook.\n }\n\n /**\n * Tear down every registered layer. Called on Canvas destroy.\n * Iteration is over a snapshot so unmount-triggered side effects don't\n * corrupt the loop.\n */\n clear(): void {\n for (const id of [...this.layers.keys()]) this.remove(id);\n }\n}\n","/**\n * `BehaviourRegistry` — stores Behaviours and toggles their enabled state.\n *\n * Architecture: see `architecture-proposal.md` §2.2.\n *\n * **Responsibilities**\n * - `register` / `unregister` (with register / destroy lifecycle; fires\n * `'scene:behaviour:register'` / `'scene:behaviour:unregister'`).\n * - `setEnabled(id, enabled)` — toggles + fires `'scene:behaviour:enable'` /\n * `'scene:behaviour:disable'`.\n * - Typed `get<T>(id)`.\n * - **Gesture-conflict warning**: when two enabled behaviours claim the same\n * `shortcut`, log a `console.warn`. Doesn't enforce — the developer\n * decides whether two behaviours can coexist on the same gesture.\n */\n\nimport type { CanvasContext } from '../CanvasContext';\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { IBehaviour } from '../Behaviour';\n\nexport interface BehaviourRegistryOptions {\n getContext: () => CanvasContext | undefined;\n bus: CanvasEventBus;\n}\n\nexport class BehaviourRegistry {\n private readonly behaviours: Map<string, IBehaviour> = new Map();\n private readonly getContext: () => CanvasContext | undefined;\n private readonly bus: CanvasEventBus;\n\n constructor(opts: BehaviourRegistryOptions) {\n this.getContext = opts.getContext;\n this.bus = opts.bus;\n }\n\n get size(): number {\n return this.behaviours.size;\n }\n\n /**\n * Register a Behaviour. Wires it (`behaviour.register(ctx)` + events) now if\n * the Canvas is initialised; otherwise it's stored and wired later by\n * `registerAll()` (called by `Canvas.init`). Throws on duplicate id.\n *\n * When wiring throws (the behaviour rejects its context — a missing target\n * layer, a second instance of a one-per-layer kind), the entry is removed\n * before the error propagates, so a rejected behaviour never shows up in\n * {@link list} and its id stays free.\n */\n register(behaviour: IBehaviour): void {\n if (this.behaviours.has(behaviour.id)) {\n throw new Error(`BehaviourRegistry: behaviour \"${behaviour.id}\" already registered`);\n }\n this.behaviours.set(behaviour.id, behaviour);\n const ctx = this.getContext();\n if (!ctx) return;\n try {\n this.wire(behaviour, ctx);\n } catch (err) {\n this.behaviours.delete(behaviour.id);\n throw err;\n }\n }\n\n /** Wire every not-yet-registered behaviour. Called by `Canvas.init` (after layers mount). */\n registerAll(): void {\n const ctx = this.getContext();\n if (!ctx) return;\n for (const behaviour of [...this.behaviours.values()]) {\n if (behaviour.isRegistered) continue;\n try {\n this.wire(behaviour, ctx);\n } catch (err) {\n // Same rollback as `register`: a rejected behaviour leaves no entry.\n this.behaviours.delete(behaviour.id);\n throw err;\n }\n }\n }\n\n /** `behaviour.register(ctx)` + the registered/enabled events. */\n private wire(behaviour: IBehaviour, ctx: CanvasContext): void {\n behaviour.register(ctx);\n this.bus.emit('scene:behaviour:register', { id: behaviour.id });\n if (behaviour.enabled) {\n this.bus.emit('scene:behaviour:enable', { id: behaviour.id });\n this.warnOnShortcutConflict(behaviour);\n }\n }\n\n /**\n * Remove a behaviour. Calls `destroy()`, then fires\n * `'scene:behaviour:unregister'` (after `'scene:behaviour:disable'` when it\n * was enabled). No-op if not registered.\n */\n unregister(id: string): void {\n const b = this.behaviours.get(id);\n if (!b) return;\n if (b.enabled) {\n b.disable();\n this.bus.emit('scene:behaviour:disable', { id });\n }\n this.behaviours.delete(id);\n b.destroy();\n this.bus.emit('scene:behaviour:unregister', { id });\n }\n\n /** Enable / disable a behaviour. Fires the corresponding bus event. */\n setEnabled(id: string, enabled: boolean): void {\n const b = this.behaviours.get(id);\n if (!b) return;\n if (b.enabled === enabled) return;\n if (enabled) {\n b.enable();\n this.bus.emit('scene:behaviour:enable', { id });\n this.warnOnShortcutConflict(b);\n } else {\n b.disable();\n this.bus.emit('scene:behaviour:disable', { id });\n }\n }\n\n get<T extends IBehaviour = IBehaviour>(id: string): T | undefined {\n return this.behaviours.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.behaviours.has(id);\n }\n\n list(): readonly IBehaviour[] {\n return Array.from(this.behaviours.values());\n }\n\n /** Tear down all behaviours. Called on Canvas destroy. */\n clear(): void {\n for (const id of [...this.behaviours.keys()]) this.unregister(id);\n }\n\n // ─── Conflict detection ──────────────────────────────────────────────────\n\n private warnOnShortcutConflict(b: IBehaviour): void {\n if (!b.shortcuts || b.shortcuts.length === 0) return;\n for (const peer of this.behaviours.values()) {\n if (peer === b) continue;\n if (!peer.enabled || !peer.shortcuts) continue;\n for (const gesture of b.shortcuts) {\n if (peer.shortcuts.includes(gesture)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[canvas] Behaviour \"${b.id}\" claims gesture \"${gesture}\" already used by enabled behaviour \"${peer.id}\". Disable one before enabling the other.`,\n );\n }\n }\n }\n }\n}\n","/**\n * `LayoutRegistry` — stores the Layouts registered on a Canvas, addressed by id.\n *\n * Simpler than `LayerRegistry` / `BehaviourRegistry`: layouts aren't mounted,\n * z-ordered, or wired to input — they're held so `Canvas.update()` can push\n * config to them by id and consumers can fetch + `apply()` them. A graph runs\n * one layout at a time, but several may be registered (e.g. a layout picker).\n */\n\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { Layout } from '../Layout';\n\nexport interface LayoutRegistryOptions {\n bus: CanvasEventBus;\n}\n\nexport class LayoutRegistry {\n private readonly layouts: Map<string, Layout> = new Map();\n private readonly bus: CanvasEventBus;\n\n constructor(opts: LayoutRegistryOptions) {\n this.bus = opts.bus;\n }\n\n get size(): number {\n return this.layouts.size;\n }\n\n /** Register a layout. Fires `layout:added`. Throws on duplicate id. */\n add(layout: Layout): void {\n if (this.layouts.has(layout.id)) {\n throw new Error(`LayoutRegistry: layout \"${layout.id}\" already registered`);\n }\n this.layouts.set(layout.id, layout);\n this.bus.emit('scene:layout:add', { id: layout.id });\n }\n\n /** Remove a layout, stopping it first if it exposes `stop()`. Fires `layout:removed`. */\n remove(id: string): void {\n const layout = this.layouts.get(id);\n if (!layout) return;\n (layout as { stop?: () => void }).stop?.();\n this.layouts.delete(id);\n this.bus.emit('scene:layout:remove', { id });\n }\n\n get<T extends Layout = Layout>(id: string): T | undefined {\n return this.layouts.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.layouts.has(id);\n }\n\n list(): readonly Layout[] {\n return Array.from(this.layouts.values());\n }\n\n /** Stop + drop every layout. Called on Canvas destroy. */\n clear(): void {\n for (const layout of this.layouts.values()) (layout as { stop?: () => void }).stop?.();\n this.layouts.clear();\n }\n}\n","/**\n * `CommandRegistry` — named, serialisable-by-reference actions.\n *\n * Serialisable UI (control panels today; shortcuts and menus later) can't hold\n * closures, so it names what it does — `'camera.fit'`, `'view.lock'` — and this\n * registry resolves the name to behaviour at run time. Names are\n * `namespace.verb`; the engine registers its built-ins, a domain package or an\n * app adds its own.\n *\n * Generic over the context `C` a command runs against (the engine binds it to\n * its `Canvas`), so the kernel stays free of any engine type.\n */\n\n/** One option of a pick-one command (see {@link CanvasCommand.options}). */\nexport interface CommandOption {\n /** The value passed back to `run` as `args.value` when picked. */\n value: string;\n /** Human label. */\n label: string;\n /** Icon name, resolved by the UI kit's icon registry. */\n icon?: string;\n /** Offered but not pickable now. A control shows it dimmed, with {@link description} as the reason. */\n disabled?: boolean;\n /** One line under the label — for a disabled option, why it is off. */\n description?: string;\n}\n\n/**\n * The value kinds a {@link CommandArgSpec} can describe. The first five are\n * plain JSON values; `layer` / `behaviour` / `layout` are the **id** of a\n * registered instance (an editor offers the live registry as choices); `json`\n * is any JSON value the editor can only take as text (maps, number lists).\n */\nexport type CommandArgKind =\n | 'string'\n | 'number'\n | 'boolean'\n | 'enum'\n | 'strings'\n | 'layer'\n | 'behaviour'\n | 'layout'\n | 'json';\n\n/**\n * Describes one key of a command's `args` bag — plain data, so the kernel stays\n * UI-free; the UI kit maps it to a form field. Optional on every command: an\n * undescribed command (or key) is still editable as raw JSON.\n */\nexport interface CommandArgSpec {\n /** The value's kind. */\n kind: CommandArgKind;\n /** Field label. Default: the key. */\n label?: string;\n /** One-line help shown under the field. */\n description?: string;\n /** The value the command uses when the key is absent — shown as a hint, never written. */\n default?: unknown;\n /** The allowed values, for `kind: 'enum'`. */\n options?: readonly CommandOption[];\n /**\n * The key a **pick-one** control supplies itself (`value` — see\n * {@link CanvasCommand.value}). An editor hides it on a `choice` item, where\n * picking sets it, and shows it on a button / toggle, where it's fixed.\n */\n pick?: boolean;\n /**\n * The command can't run without this key (`behaviour.toggle`'s `id`). A\n * surface that runs commands bare — the palette — leaves such commands out.\n * Default `false`: an absent key falls back to {@link default} or the\n * command's own behaviour.\n */\n required?: boolean;\n}\n\n/**\n * A **command map**: command name → the type of its `args` bag. A package\n * exports its commands' map as a type (`EngineCommandMap` in `@invana/canvas`,\n * `GraphCommandMap` in `@invana/graph`) and a registry typed with it\n * (`CommandRegistry<C, M>`) checks the args of those names at compile time —\n * types only, nothing at runtime. Any other name still takes `unknown` args, so\n * app-registered commands keep working. Merge maps with `&`.\n */\nexport type CommandMap = object;\n\n/** A command name: one of `M`'s (offered for completion), or any other string. */\nexport type CommandName<M extends CommandMap> = (keyof M & string) | (string & {});\n\n/**\n * The `args` type of command `K` in map `M` — `unknown` for a name `M` doesn't\n * list. An indexed access, not a conditional type, so a registry stays\n * covariant in its map: a `CommandRegistry<C, Wider>` is a\n * `CommandRegistry<C, Narrower>` (a subclass can widen `commands`' map).\n */\nexport type CommandArgsOf<M extends CommandMap, K extends string> = (M & Record<string, unknown>)[K];\n\n/**\n * A named command, run against a context `C`. `args` is whatever the caller's\n * spec carried (JSON); `A` narrows it for a command whose map entry is known.\n *\n * Its `isEnabled` / `isActive` / `value` / `options` may read anything; a bound\n * control re-reads them on view-store writes and on the registry's\n * {@link CommandRegistry.subscribe} signal. State outside the store needs an\n * owner-side {@link CommandRegistry.invalidate} bridge — see there.\n */\nexport interface CanvasCommand<C, A = unknown> {\n /** Human label — a default tooltip when a spec doesn't give one. */\n label?: string;\n /**\n * Group a command palette / menu lists it under (`'Camera'`, `'Edit'`,\n * `'Layout'`, …). Data only — the kernel never reads it.\n */\n category?: string;\n /** Extra search terms a command palette matches besides the label and name. Data only. */\n keywords?: readonly string[];\n /**\n * The keys `args` may carry, described for editors (the Studio's control-panel\n * editor draws a field per key). In dev builds {@link CommandRegistry.run}\n * checks a described key's value against its `kind` and warns (never throws)\n * on a mismatch — see {@link CommandRegistryOptions.validateArgs}. Keys it\n * doesn't name still pass through unchecked.\n */\n args?: Readonly<Record<string, CommandArgSpec>>;\n /**\n * Perform the command. A command whose work finishes later (a layout run)\n * returns its promise, so {@link CommandRegistry.runAsync} can wait for it;\n * {@link CommandRegistry.run} ignores it.\n */\n run(ctx: C, args?: A): void | Promise<void>;\n /** Toggle state for toggle-style controls. Absent ⇒ never active. */\n isActive?(ctx: C, args?: A): boolean;\n /** Whether the command can run now. Absent ⇒ always enabled. */\n isEnabled?(ctx: C, args?: A): boolean;\n /**\n * Current value, for a **pick-one** command (select mode, edge type, active\n * layout). Picking an option runs the command with `{ ...args, value }`.\n * `null` when nothing is picked.\n */\n value?(ctx: C, args?: A): string | null;\n /** The options a pick-one command offers. A spec's own `options` take precedence. */\n options?(ctx: C, args?: A): CommandOption[];\n}\n\n/** Options for {@link CommandRegistry}. */\nexport interface CommandRegistryOptions<C> {\n /** The context every command runs against (resolved lazily, per call). */\n getContext: () => C;\n /**\n * Check `args` against each command's {@link CanvasCommand.args} descriptors\n * in {@link CommandRegistry.run}, warning once per (command, key, problem) on\n * a mismatch. Never throws, never blocks the run. Default: on in dev builds\n * (`process.env.NODE_ENV !== 'production'`), off in production bundles.\n */\n validateArgs?: boolean;\n}\n\n/**\n * Whether this is a dev build. Written as the literal `process.env.NODE_ENV`\n * so consumer bundlers substitute it (and drop the validator in production);\n * where `process` doesn't exist at all (an unbundled browser) it's `false`.\n */\nfunction isDevBuild(): boolean {\n try {\n // `process` isn't declared in this dependency-free package.\n return (process as { env: { NODE_ENV?: string } }).env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n\ndeclare const process: unknown;\n\n/** Why `value` doesn't fit `spec`, or `null` when it does. */\nfunction argProblem(spec: CommandArgSpec, value: unknown): string | null {\n switch (spec.kind) {\n case 'string':\n case 'layer':\n case 'behaviour':\n case 'layout':\n return typeof value === 'string' ? null : `expected a string (${spec.kind}), got ${describe(value)}`;\n case 'number': {\n if (typeof value === 'number' && Number.isFinite(value)) return null;\n // A picker hands its pick back as a string (`camera.zoomTo`'s `value`).\n if (spec.pick && typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return null;\n return `expected a finite number, got ${describe(value)}`;\n }\n case 'boolean':\n return typeof value === 'boolean' ? null : `expected a boolean, got ${describe(value)}`;\n case 'enum': {\n const allowed = (spec.options ?? []).map((o) => o.value);\n return typeof value === 'string' && allowed.includes(value)\n ? null\n : `expected one of ${allowed.map((v) => JSON.stringify(v)).join(', ')}, got ${describe(value)}`;\n }\n case 'strings':\n return Array.isArray(value) && value.every((v) => typeof v === 'string')\n ? null\n : `expected an array of strings, got ${describe(value)}`;\n case 'json':\n return null;\n }\n}\n\nfunction describe(value: unknown): string {\n if (Array.isArray(value)) return 'an array';\n if (value === null) return 'null';\n return typeof value === 'string' ? JSON.stringify(value) : typeof value;\n}\n\n/**\n * Holds {@link CanvasCommand}s by name and runs them against a bound context.\n *\n * `M` ({@link CommandMap}) types the args of the names it lists — `register`\n * (the handler's `args`), `run`, `isEnabled`, `isActive`, `value`, `options` —\n * while every other name takes `unknown` args. Unset, nothing is typed, and a\n * typed registry still passes where a `CommandRegistry<C>` is expected. Types\n * only: the registry behaves the same for any `M`.\n *\n * Registrations **stack** per name: registering a name that already exists\n * overrides it (a provider upgrading `graph.clear` to its undoable form, an app\n * replacing a built-in), and disposing an override restores whatever is\n * underneath — in any disposal order. {@link subscribe} listeners hear every\n * register / unregister and every {@link invalidate}, so a UI can re-read\n * command state.\n */\nexport class CommandRegistry<C, M extends CommandMap = Record<never, never>> {\n /** Per name, the registrations oldest → newest; the last one is live. */\n private readonly stacks = new Map<string, Array<{ command: CanvasCommand<C> }>>();\n private readonly listeners = new Set<() => void>();\n /** Bumped on every {@link subscribe} signal — see {@link version}. */\n private _version = 0;\n private readonly getContext: () => C;\n private readonly validateArgs: boolean;\n /** `command|key|problem` already warned about, so a bound button doesn't flood the console. */\n private readonly warned = new Set<string>();\n\n constructor(opts: CommandRegistryOptions<C>) {\n this.getContext = opts.getContext;\n this.validateArgs = opts.validateArgs ?? isDevBuild();\n }\n\n /**\n * Register `name`, overriding any existing registration. Returns a disposer\n * that removes **this** registration only: if it is live, the one underneath\n * becomes live again; if it was already overridden, the override stays.\n */\n register<K extends CommandName<M>>(name: K, command: CanvasCommand<C, CommandArgsOf<M, K>>): () => void {\n // A fresh wrapper per call, so registering the same command twice still\n // yields two independently disposable entries.\n const entry = { command };\n const stack = this.stacks.get(name) ?? [];\n stack.push(entry);\n this.stacks.set(name, stack);\n this.notify();\n return () => {\n const current = this.stacks.get(name);\n const i = current?.indexOf(entry) ?? -1;\n if (!current || i < 0) return;\n current.splice(i, 1);\n if (current.length === 0) this.stacks.delete(name);\n this.notify();\n };\n }\n\n /** Remove every registration of `name`. No-op when absent. */\n unregister(name: string): void {\n if (this.stacks.delete(name)) this.notify();\n }\n\n has(name: string): boolean {\n return this.stacks.has(name);\n }\n\n /** The live (most recent) registration of `name`. */\n get(name: string): CanvasCommand<C> | undefined {\n const stack = this.stacks.get(name);\n return stack?.[stack.length - 1]?.command;\n }\n\n /** Registered command names, in first-registration order. */\n list(): string[] {\n return [...this.stacks.keys()];\n }\n\n /**\n * Run `name` with `args`. Returns `false` (and does nothing) when the command\n * is missing or disabled. With `validateArgs` on, first warns about any\n * described key whose value doesn't fit its descriptor — the run proceeds\n * regardless.\n */\n run<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n if (!cmd) return false;\n if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);\n const ctx = this.getContext();\n if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;\n void cmd.run(ctx, args);\n return true;\n }\n\n /**\n * {@link run}, awaiting the command's work: resolves once the promise a\n * command's `run` returned settles (`layout.run` resolves when the layout\n * run ends). Resolves `false` — without running anything — when the command\n * is missing or disabled; a synchronous command resolves `true` at once. A\n * playbook step's `do` verbs go through here, so each finishes before the\n * next starts.\n */\n async runAsync<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): Promise<boolean> {\n const cmd = this.get(name);\n if (!cmd) return false;\n if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);\n const ctx = this.getContext();\n if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;\n await cmd.run(ctx, args);\n return true;\n }\n\n /** `isActive` of `name`; `false` when missing or not a toggle. */\n isActive<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n return cmd?.isActive ? cmd.isActive(this.getContext(), args) : false;\n }\n\n /** `isEnabled` of `name`; `false` when missing, `true` when it declares no check. */\n isEnabled<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n if (!cmd) return false;\n return cmd.isEnabled ? cmd.isEnabled(this.getContext(), args) : true;\n }\n\n /** `value` of a pick-one command; `null` when missing or not a picker. */\n value<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): string | null {\n const cmd = this.get(name);\n return cmd?.value ? cmd.value(this.getContext(), args) : null;\n }\n\n /** `options` of a pick-one command; `[]` when missing or it declares none. */\n options<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): CommandOption[] {\n const cmd = this.get(name);\n return cmd?.options ? cmd.options(this.getContext(), args) : [];\n }\n\n /**\n * Tell subscribers that command state changed **outside** the view store (a\n * history stack, a clipboard buffer, a layer's edge defaults, a registry), so\n * a bound control re-reads `isEnabled` / `isActive` / `value` / `options`.\n *\n * Call it from the state's **owner** — a bridge from the owner's own change\n * signal, set up once (the engine bridges the registries, layer visibility and\n * `canvas.history`; `GraphCanvas` its layers' edge templates; a provider its\n * own history / clipboard) — never from the write sites, where another\n * writer would forget it. A command whose state lives in the view store\n * needs none.\n */\n invalidate(): void {\n this.notify();\n }\n\n /**\n * A counter bumped on every {@link subscribe} signal (register, unregister,\n * dispose, {@link invalidate}, {@link clear}) — and only then. Use it as a\n * `useSyncExternalStore` snapshot when a UI must re-read *everything* on a\n * signal: a snapshot derived from `list()` stays equal when only a command's\n * `options` / state changed, and React would skip the re-render.\n */\n get version(): number {\n return this._version;\n }\n\n /** Hear every register / unregister / {@link invalidate}. Returns an unsubscribe. */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** Drop every command and listener. */\n clear(): void {\n this.stacks.clear();\n this.notify();\n this.listeners.clear();\n }\n\n /** Warn (once each) about `args` values that don't fit `specs`. */\n private checkArgs(name: string, specs: Readonly<Record<string, CommandArgSpec>>, args: unknown): void {\n if (args === undefined || args === null) return;\n if (typeof args !== 'object' || Array.isArray(args)) {\n this.warn(name, '', `args should be an object, got ${describe(args)}`);\n return;\n }\n for (const [key, spec] of Object.entries(specs)) {\n const value = (args as Record<string, unknown>)[key];\n if (value === undefined) continue;\n const problem = argProblem(spec, value);\n if (problem) this.warn(name, key, problem);\n }\n }\n\n private warn(name: string, key: string, problem: string): void {\n const id = `${name}|${key}|${problem}`;\n if (this.warned.has(id)) return;\n this.warned.add(id);\n console.warn(`[canvas] command \"${name}\"${key ? ` arg \"${key}\"` : ''}: ${problem}`);\n }\n\n private notify(): void {\n this._version++;\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * Pure geometry — points, rectangles, polylines, paths, and the router / pathStyle\n * function contracts that operate on them. No drawing library appears here.\n *\n * Part of the pixi-free spec vocabulary — see `docs/renderer-split-design.md`.\n */\n\n// ─── Geometry primitives ───────────────────────────────────────────────────\n\n// Defined once, in the kernel's geometry vocabulary, and re-exported here so the\n// spec surface stays self-describing. Do not redeclare them — `../geom` is\n// the single home (see the RFC that merged the two definitions:\n// `docs/rfcs/fix/2026-08-10-zustand-imported-outside-canvas-store.md` §4.4).\nexport type { Point, Vec2, Rect, Size } from './geom';\n\nimport type { Point, Vec2, Rect } from './geom';\n\n/** Endpoint anchor a router consumes — point + optional outgoing tangent. */\n\nexport interface Endpoint {\n readonly x: number;\n readonly y: number;\n readonly tangent?: Vec2;\n}\n\n// ─── Polyline (router output, pathStyle input) ─────────────────────────────\n\n/**\n * Flat ordered list of points. Output of a `Router`; input to a `PathStyle`.\n * Also used as the densified form of a `Path` for hit-testing\n * (`samplePath(path)`).\n */\n\nexport type Polyline = ReadonlyArray<Point>;\n\n// ─── Path (pathStyle output, connector input) ──────────────────────────────\n\n/**\n * One step of a `Path`. Mirrors SVG path commands one-for-one:\n * - `M` move to absolute (x, y) — must be the first command of any Path.\n * - `L` line to (x, y) from the current point.\n * - `Q` quadratic Bézier with one control point.\n * - `C` cubic Bézier with two control points.\n *\n * No relative variants, no arcs, no shorthand — pathStyles emit one of these\n * four. Connector renders by walking the path and dispatching to Pixi's\n * `moveTo` / `lineTo` / `quadraticCurveTo` / `bezierCurveTo`.\n */\n\nexport type PathCommand =\n | { readonly kind: 'M'; readonly x: number; readonly y: number }\n | { readonly kind: 'L'; readonly x: number; readonly y: number }\n | { readonly kind: 'Q'; readonly cx: number; readonly cy: number; readonly x: number; readonly y: number }\n | { readonly kind: 'C'; readonly c1x: number; readonly c1y: number; readonly c2x: number; readonly c2y: number; readonly x: number; readonly y: number };\n\nexport type Path = ReadonlyArray<PathCommand>;\n\n/**\n * Read-only scene context handed to routers that need awareness of other\n * shapes — primarily for obstacle-avoidance routing (`manhattan` and\n * friends). Simple geometric routers (`straight`, `orth`) ignore it.\n *\n * `obstacles` are world-space `Rect`s the router should not cross. Each\n * obstacle may also expose `containsInflated` for pixel-accurate silhouette\n * testing (e.g. circles route around their tangent, not their AABB).\n * The renderer auto-collects these from `shapeInstances` (excluding the\n * source/target shapes); callers can override or opt out via\n * `routerOpts.obstacles`.\n */\n\nexport interface RouterCtx {\n readonly obstacles: ReadonlyArray<Obstacle>;\n}\n\n/**\n * Obstacle handed to obstacle-aware routers. `Obstacle extends Rect` so any\n * `Rect[]` is assignable; the optional `containsInflated` callback unlocks\n * silhouette-tight routing for non-rect shapes (circles, polygons, paths).\n */\n\nexport interface Obstacle extends Rect {\n /**\n * Optional silhouette obstacle-test in world coordinates. Returns `true`\n * when `(worldX, worldY)` lies inside the obstacle's silhouette OR within\n * `inflate` world units of it.\n *\n * Routers use this for pixel-accurate marking — when present, the grid\n * blocks only cells that pass this test (in addition to the cheap AABB\n * pre-filter). When absent, the inflated AABB is the source of truth.\n *\n * Shapes opt in by overriding `IShape.obstacleTest`.\n */\n readonly containsInflated?: (worldX: number, worldY: number, inflate: number) => boolean;\n}\n\n/**\n * Router: a pure function `(source, target, waypoints?, opts?, ctx?) → Polyline`.\n *\n * Routers decide path **topology** — where bends sit. They emit a flat\n * polyline (Point[]); the visual style of segments between bend points is\n * decided by the downstream `PathStyle`. Routers never touch pixi.\n *\n * `waypoints` are intermediate user-supplied points the router should respect.\n * Built-in `straight` passes them through verbatim; topological routers\n * (orth, manhattan, …) anchor stair / corner segments to them.\n *\n * `ctx` is optional — only obstacle-aware routers consume it. The renderer\n * always passes a `RouterCtx`; routers that ignore it lose nothing.\n */\n\nexport type IRouter = (\n source: Endpoint,\n target: Endpoint,\n waypoints?: ReadonlyArray<Point>,\n opts?: Record<string, unknown>,\n ctx?: RouterCtx,\n) => Polyline;\n\n/**\n * Anchor-resolved endpoints handed to a pathStyle alongside the polyline.\n *\n * Tangent-aware pathStyles (`bump-horizontal`, …) read `source.tangent` /\n * `target.tangent` to place their Bézier handles along each shape's outward\n * surface normal, so the curve leaves and arrives flush with the silhouette\n * instead of in a hard-coded direction. Tangent-agnostic pathStyles (`normal`,\n * `rounded`, …) simply ignore the argument — it's optional and additive.\n */\n\nexport interface PathStyleEndpoints {\n readonly source: Endpoint;\n readonly target: Endpoint;\n}\n\n/**\n * PathStyle: a pure function `(polyline, opts?, endpoints?) → Path`.\n *\n * PathStyles decide visual **style** — how segments between polyline points\n * are drawn (sharp, rounded fillets, bezier-smoothed, single bezier A→B).\n * They never see the connector spec or shape context; pure geometric\n * transform.\n *\n * `endpoints` carries the anchor-resolved source/target (with `tangent`) so\n * tangent-aware styles can align Bézier handles with each shape's outward\n * normal. Optional — styles that don't need it ignore the argument and a\n * direct unit-test invocation (`bumpHorizontal(polyline)`) keeps working.\n *\n * Built-ins: `normal` (sharp), `rounded` (quadratic fillets at corners),\n * `smooth` (Catmull-Rom → cubic), `bezier` (single cubic with auto controls).\n */\n\nexport type IPathStyle = (\n polyline: Polyline,\n opts?: Record<string, unknown>,\n endpoints?: PathStyleEndpoints,\n) => Path;\n\n// ─── Fill ──────────────────────────────────────────────────────────────────\n\n/**\n * Anchor positions for inset content layers (`glyph`, `svg`, `svg-url`).\n * Defaults to `'center'`. Use `'top-right'` etc. for corner-badge\n * composition.\n */\n\n/**\n * Stable key of a connector spec with paint removed — geometry only.\n *\n * Two specs with the same key route to the same path, so a caller can skip a\n * re-route when only `stroke` changed. Pure: it reads the spec and nothing\n * else, which is why it lives here rather than on a renderer.\n */\nexport function connectorGeometryKey(spec: object): string {\n const { stroke: _stroke, ...geometry } = spec as { stroke?: unknown };\n return JSON.stringify(geometry);\n}\n","/**\n * Fill, stroke and paint-override vocabulary. Values are plain numbers and enums —\n * a colour is `0xRRGGBB`, never a backend colour object.\n *\n * Part of the pixi-free spec vocabulary — see `docs/renderer-split-design.md`.\n */\n\nexport type InsetAnchor =\n | 'center'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\n/**\n * One layer of a shape's fill. Layers split by role:\n *\n * - **Silhouette fillers** (`solid`, `image`) — paint into the silhouette\n * via Pixi's `g.fill()`. Multiple silhouette layers stack via alpha;\n * each is re-traced before painting. Image fills always render the\n * texture cover-fitted to the silhouette (uniform scale, may crop) —\n * the engine intentionally does not expose CSS-style `background-size`\n * / `background-repeat` knobs on raster fills.\n * - **Inset content** (`glyph`, `svg`, `svg-url`) — mounted as Container\n * children of the shape's `gfx`. Sized by `sizeRatio` (fraction of the\n * smaller bounds dimension) and positioned by `anchor` (default\n * `'center'`).\n *\n * The engine has no dedicated \"icon\" kind — icon-library specifics (Font\n * Awesome glyphs, Lucide SVGs, Fluent icons, …) are produced by developer\n * code and dropped into a `glyph` or `svg` layer directly.\n */\n\nexport type ShapeFillLayer =\n | { readonly kind: 'solid'; readonly color: number; readonly alpha?: number }\n | {\n /**\n * Raster image painted into the host silhouette.\n *\n * Two orthogonal knobs control sizing:\n *\n * - `fit` (default `'cover'`) — how the texture's aspect maps to\n * the silhouette's AABB. `'cover'` scales by `max(...)`, fully\n * covers, may crop on the cross-axis. `'contain'` scales by\n * `min(...)`, fully fits, leaves the cross-axis margin\n * transparent (the underlying fill layer reads through; the\n * engine pins the texture sampler to `clamp-to-edge` so the\n * margin doesn't tile).\n *\n * - `padding` (default `0`) — pixel inset on the silhouette\n * *before* fit math runs. The silhouette itself is re-traced at\n * that inset for this layer only, so the gap between the\n * full-size silhouette and the inset silhouette is painted by\n * layers underneath (typically a `solid` `bgFill`). Use this\n * when the host silhouette is more restrictive than its AABB\n * (circle, polygon, star, arc) and the texture corners would\n * otherwise clip against the curve.\n *\n * Tile patterns, repeat modes, and inset-Sprite badge placement\n * aren't on the engine surface — stack a `glyph` / `svg` /\n * `svg-url` layer for icon-shaped content.\n */\n readonly kind: 'image';\n readonly url: string;\n readonly alpha?: number;\n readonly fit?: 'cover' | 'contain';\n readonly padding?: number;\n }\n | {\n /** Font-rendered character (icon-font codepoint, Unicode symbol, emoji). */\n readonly kind: 'glyph';\n readonly char: string;\n /** Required for icon-font glyphs; optional for system-font Unicode. */\n readonly fontFamily?: string;\n /**\n * Font weight (CSS value, e.g. `400`, `900`, `'bold'`). Required for\n * icon fonts that pack different glyph sets per weight.\n */\n readonly fontWeight?: number | string;\n readonly fontStyle?: 'normal' | 'italic';\n /** Glyph color. Default `0xffffff`. */\n readonly color?: number;\n readonly alpha?: number;\n /** Size as fraction of the shape's smaller bounds dimension. Default `0.6`. */\n readonly sizeRatio?: number;\n /** Anchor relative to the shape's bounds. Default `'center'`. */\n readonly anchor?: InsetAnchor;\n }\n | {\n /** SVG path-d. Multiple subpaths (`M...M...`) are supported. */\n readonly kind: 'svg';\n readonly pathD: string;\n /** Viewport the path was authored in. Default `{ width: 24, height: 24 }`. */\n readonly viewBox?: { readonly width: number; readonly height: number };\n /** Stroke width when rendering. Default `2`. */\n readonly strokeWidth?: number;\n readonly color?: number;\n readonly alpha?: number;\n readonly sizeRatio?: number;\n readonly anchor?: InsetAnchor;\n }\n | {\n /**\n * Vector SVG icon fetched from a URL. The engine fetches the SVG,\n * extracts every drawing primitive (`path` / `ellipse` / `circle` /\n * `rect` / `line` / `polyline` / `polygon`) into a single concatenated\n * `pathD`, and renders it as a Pixi Graphics path. Fetched lazily on\n * first use; the resulting `pathD` is cached globally per URL.\n *\n * Use this when a consumer wants to point at their own remote SVG\n * (logo, custom diagram, sample artwork). For curated icon-library\n * usage, prefer an icon-font glyph via `kind: 'glyph'` — the\n * library is icon-vendor-agnostic and intentionally has no\n * vendor-specific fetch glue.\n */\n readonly kind: 'svg-url';\n readonly url: string;\n readonly viewBox?: { readonly width: number; readonly height: number };\n readonly strokeWidth?: number;\n readonly color?: number;\n readonly alpha?: number;\n readonly sizeRatio?: number;\n readonly anchor?: InsetAnchor;\n };\n\n/**\n * A shape's fill. Either a single layer, an array of layers (painted\n * bottom-up — first array entry sits underneath), or the `number` shorthand\n * for a solid color.\n */\n\nexport type ShapeFill =\n | number\n | ShapeFillLayer\n | ReadonlyArray<ShapeFillLayer>;\n\n/**\n * The **inset-content** half of {@link ShapeFillLayer} — the layer kinds a\n * backend mounts *inside* the silhouette as a child rather than painting\n * *into* it. Named here (not only where it is mounted) because it is part of\n * the vocabulary: a `CompositePart` of kind `'icon'` carries one, so the spec\n * types must be able to reference it without reaching into a renderer.\n */\nexport type InsetFillLayer = Extract<\n ShapeFillLayer,\n { kind: 'glyph' | 'svg' | 'svg-url' }\n>;\n\n/**\n * Does this fill paint the **silhouette** — i.e. would a backend emit a fill\n * for it? True for the `number` shorthand and for any `solid` / `image` layer;\n * false for `undefined` and for a fill made only of inset content\n * ({@link InsetFillLayer}), which mounts a child instead of filling.\n *\n * Load-bearing for hit-testing: a shape with no silhouette fill is **hollow**\n * — only its stroke band answers a containment test, exactly as pixi's\n * `Graphics.containsPoint` behaves (it consults a `fill` instruction that was\n * never emitted). See `containsSpec` in `specs/shapeGeometry/`.\n */\nexport function hasSilhouetteFill(fill: ShapeFill | undefined): boolean {\n if (fill === undefined) return false;\n if (typeof fill === 'number') return true;\n const layers = Array.isArray(fill) ? fill : [fill as ShapeFillLayer];\n return layers.some((l) => l.kind === 'solid' || l.kind === 'image');\n}\n\n// ─── Stroke (border) ───────────────────────────────────────────────────────\n\nexport interface ShapeStroke {\n readonly color: number;\n readonly alpha?: number;\n readonly width?: number;\n /** Default `'center'`. */\n readonly alignment?: 'inside' | 'center' | 'outside';\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n}\n\n// ─── Paint styles (decoration → primitive override) ────────────────────────\n\n/**\n * Decoration entry-point override on `IShape.paintInto`. When supplied, the\n * shape ignores `spec.fill` / `spec.stroke` and paints with these values\n * instead. Decorations like glow widen `strokeWidth` and reduce `alpha` to\n * paint a halo; decorations like marching-ants supply `dashArray` /\n * `dashOffset` to render a dashed silhouette; decorations like ring/halo\n * with non-zero `inset` ask the shape to trace a parallel-offset version of\n * its own silhouette.\n */\n\nexport interface ShapePaintStyle {\n readonly color?: number;\n readonly alpha?: number;\n readonly strokeWidth?: number;\n /**\n * Stroke alignment relative to the silhouette. Default `'outside'` —\n * decorations almost always want their geometry painted outside the\n * host body (halo, glow, ring), so the inner band doesn't eat into the\n * fill. Override per-call when a decoration genuinely wants to bleed\n * inward (e.g. an \"inset border\" effect).\n */\n readonly alignment?: 'inside' | 'center' | 'outside';\n /** Default `false` — decorations almost always stroke without filling. */\n readonly fill?: boolean;\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n /** Positive = inside the silhouette, negative = outside. Default `0`. */\n readonly inset?: number;\n}\n\n/** Mirror of `ShapePaintStyle` for connectors. No `inset` (connectors are 1D). */\n\nexport interface ConnectorPaintStyle {\n readonly color?: number;\n readonly alpha?: number;\n readonly strokeWidth?: number;\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n /**\n * When `true`, markers paint with `color` / `alpha` instead of their own\n * spec colors. Glow / halo decorations use this so the decoration covers\n * path + markers as a unified silhouette; marching-ants leaves it\n * undefined so markers stay normal-colored over the dashed line.\n */\n readonly tintMarkers?: boolean;\n /**\n * When `true`, `paintInto` paints only the body (no source / target\n * markers). Useful for decorations that handle markers separately or\n * want to leave them untouched. `markerHalo` is preferred for glow /\n * halo coverage; reach for `skipMarkers` only when even outlined\n * markers would be wrong.\n */\n readonly skipMarkers?: boolean;\n /**\n * When `true`, markers paint as **outlines** at `style.strokeWidth`\n * (using `style.color` / `style.alpha`) instead of as filled silhouettes.\n * Marker geometry continues to size off the host connector's spec\n * stroke width — the halo width affects only the outline stroke, never\n * the marker's tip-to-base / wing-spread dimensions. Combined with the\n * widening-stroke / decreasing-alpha pattern of a glow decoration,\n * this produces a halo around the marker that matches the body halo.\n */\n readonly markerHalo?: boolean;\n}\n\n// ─── Spec types ────────────────────────────────────────────────────────────\n\n/**\n * Ordered paint stripe. Earlier entries paint **below** later ones, and a stripe\n * always wins over `zIndex`: `plane` picks the stripe, `zIndex` orders *within*\n * it. Independent of the scene graph — a shape keeps its logical parent (and so\n * its transform); only its render order moves.\n *\n * `'backdrop'` is the only stripe below the connectors, which is what makes a\n * group frame able to sit under the edges between its own members — see\n * `docs/rfcs/fix/2026-08-05-group-frame-occludes-edges.md`.\n *\n * @remarks\n * The design of record (`docs/render-planes-and-emphasis-plan.md` §4.1) defines\n * five stripes — `backdrop` · `background` · `content` · `foreground` ·\n * `overlay`. Two are implemented: `'backdrop'` and the default `'content'`. The\n * remaining three are served today by the renderer's built-in connector / shape\n * / overlay ordering; widening this union later is additive.\n */\n","/**\n * Polygon maths shared by every spec kind whose silhouette is (or densifies\n * to) a closed vertex ring — `polygon`, `regular-polygon`, `star`,\n * `tabbed-rect`, `path`, and the sampled `arc` fallback.\n *\n * Pure functions over plain `{x, y}` arrays in shape-local space. No drawing\n * library, and nothing from `primitives/` — this file is what lets picking and\n * bounds be answered with no GPU (see `docs/renderer-split-design.md` §4.5,\n * \"what stays engine-side\").\n *\n * Convention: all vertex arrays here are **centre-relative** — the silhouette\n * is traced around the origin so that `boundaryIntersect` (which receives\n * centre-relative input) works without an extra translation step. The one\n * exception is `tabbed-rect`, whose outline is AABB-origin-relative; it says so\n * at its own call sites.\n */\n\nimport type { Point, Rect } from '../geometry';\n\n/** Tight axis-aligned bounding box around the vertex list. */\nexport function polygonBounds(vertices: ReadonlyArray<Point>): Rect {\n if (vertices.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n let minX = vertices[0]!.x;\n let maxX = minX;\n let minY = vertices[0]!.y;\n let maxY = minY;\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i]!;\n if (v.x < minX) minX = v.x;\n else if (v.x > maxX) maxX = v.x;\n if (v.y < minY) minY = v.y;\n else if (v.y > maxY) maxY = v.y;\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/**\n * Even-odd ray-cast point-in-polygon test. Handles convex and concave\n * silhouettes. Treats the polygon as closed (last vertex implicitly\n * connects to first).\n */\nexport function pointInPolygon(\n localX: number,\n localY: number,\n vertices: ReadonlyArray<Point>,\n): boolean {\n const n = vertices.length;\n if (n < 3) return false;\n let inside = false;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const vi = vertices[i]!;\n const vj = vertices[j]!;\n const intersects =\n vi.y > localY !== vj.y > localY &&\n localX < ((vj.x - vi.x) * (localY - vi.y)) / (vj.y - vi.y) + vi.x;\n if (intersects) inside = !inside;\n }\n return inside;\n}\n\n/** Squared distance from `(px, py)` to the segment `(x1, y1) → (x2, y2)`. */\nexport function distanceToSegmentSq(\n px: number,\n py: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n): number {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const lenSq = dx * dx + dy * dy;\n // Degenerate segment (both endpoints coincide) — fall back to point distance.\n let t = lenSq === 0 ? 0 : ((px - x1) * dx + (py - y1) * dy) / lenSq;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n const ex = x1 + t * dx - px;\n const ey = y1 + t * dy - py;\n return ex * ex + ey * ey;\n}\n\n/**\n * Squared distance from `(x, y)` to the nearest **edge** of a vertex ring.\n * `closed` includes the wrap-around edge (last → first); an open run omits it,\n * which is what a `path` spec with `closed: false` draws.\n */\nexport function distanceToOutlineSq(\n x: number,\n y: number,\n vertices: ReadonlyArray<Point>,\n closed = true,\n): number {\n const n = vertices.length;\n if (n === 0) return Infinity;\n if (n === 1) {\n const v = vertices[0]!;\n return (x - v.x) * (x - v.x) + (y - v.y) * (y - v.y);\n }\n const edges = closed ? n : n - 1;\n let best = Infinity;\n for (let i = 0; i < edges; i++) {\n const a = vertices[i]!;\n const b = vertices[(i + 1) % n]!;\n const d = distanceToSegmentSq(x, y, a.x, a.y, b.x, b.y);\n if (d < best) best = d;\n }\n return best;\n}\n\n/**\n * Containment against a vertex ring **grown (or shrunk) by `pad`**.\n *\n * - `pad > 0` — inside the ring *or* within `pad` of its outline. This is the\n * region a centred stroke of half-width `pad` covers, and it is exactly the\n * union pixi's `Graphics.containsPoint` reports for a filled + stroked\n * polygon (`Polygon.contains` ∪ `Polygon.strokeContains`).\n * - `pad < 0` — inside the ring *and* further than `|pad|` from its outline:\n * the silhouette eroded inward, used to punch the hole out of a\n * fill-less shape so only its stroke band answers `true`.\n *\n * The offset is a true distance offset (round joins at convex corners), not a\n * miter offset, so a spike's tip grows by `pad` rather than by `pad / sin(θ/2)`\n * — the same approximation pixi makes.\n */\nexport function polygonContainsInflated(\n x: number,\n y: number,\n vertices: ReadonlyArray<Point>,\n pad = 0,\n closed = true,\n): boolean {\n const inside = closed && pointInPolygon(x, y, vertices);\n if (pad === 0) return inside;\n const nearOutline = distanceToOutlineSq(x, y, vertices, closed) <= pad * pad;\n return pad > 0 ? inside || nearOutline : inside && !nearOutline;\n}\n\n/**\n * Parallel-offset a closed polygon by `distance` along each edge's inward\n * normal. Positive `distance` shrinks (inset); negative grows (outset).\n *\n * Each vertex is moved along the **bisector** of its two adjacent edge\n * normals, scaled so the perpendicular offset along the edges equals\n * `distance`. Sufficient for convex and mildly concave silhouettes — the\n * regular-polygon and star convenience kinds always produce well-behaved\n * shapes, free-form polygon insets are best-effort and may self-intersect at\n * extreme concavities.\n */\nexport function offsetPolygon(\n vertices: ReadonlyArray<Point>,\n distance: number,\n): Point[] {\n const n = vertices.length;\n if (n < 3 || distance === 0) return vertices.map((v) => ({ x: v.x, y: v.y }));\n\n // Inward normal of edge (a → b) for a clockwise polygon is (dy, -dx)/len;\n // for counter-clockwise it's (-dy, dx)/len. We don't know orientation up\n // front, so compute the signed area and flip accordingly.\n const ccw = signedArea(vertices) > 0;\n\n const out: Point[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const prev = vertices[(i + n - 1) % n]!;\n const curr = vertices[i]!;\n const next = vertices[(i + 1) % n]!;\n\n const e1 = unitNormal(prev, curr, ccw);\n const e2 = unitNormal(curr, next, ccw);\n\n // Bisector = sum of the two edge normals. Scale to preserve perpendicular\n // distance: divide by (1 + n1·n2) / |n1+n2|² … which simplifies to\n // distance / (1 + n1·n2) when |n1| = |n2| = 1 (both unit normals).\n const bx = e1.x + e2.x;\n const by = e1.y + e2.y;\n const dot = e1.x * e2.x + e1.y * e2.y;\n const denom = 1 + dot;\n // `denom` collapses to ~0 at a 180° spike — fall back to the edge normal\n // to avoid blowing up the offset vertex.\n if (Math.abs(denom) < 1e-6) {\n out[i] = { x: curr.x + e1.x * distance, y: curr.y + e1.y * distance };\n } else {\n const k = distance / denom;\n out[i] = { x: curr.x + bx * k, y: curr.y + by * k };\n }\n }\n return out;\n}\n\n/**\n * Vertices of a regular polygon with `sides` sides and circum-radius\n * `radius`, centred at the origin. `rotationRad` is added to the base angle.\n *\n * Base placement: first vertex at angle `-π/2 + rotationRad` (straight up).\n * So with `rotation = 0`: triangle (sides=3) points up, pentagon points up,\n * hexagon has a vertex at the top (pointy-top). For a flat-top hexagon, pass\n * `rotation = Math.PI / 6`.\n */\nexport function regularPolygonVertices(\n sides: number,\n radius: number,\n rotationRad: number,\n): Point[] {\n const n = Math.max(3, Math.floor(sides));\n const out: Point[] = new Array(n);\n const base = -Math.PI / 2 + rotationRad;\n const step = (Math.PI * 2) / n;\n for (let i = 0; i < n; i++) {\n const a = base + i * step;\n out[i] = { x: Math.cos(a) * radius, y: Math.sin(a) * radius };\n }\n return out;\n}\n\n/**\n * Vertices of a star with `points` outer points, alternating outer\n * (`outerRadius`) and inner (`innerRadius`) vertices around the origin.\n * `rotationRad` is added to the base angle.\n *\n * Base placement: first outer vertex at angle `-π/2 + rotationRad` (up).\n */\nexport function starVertices(\n points: number,\n innerRadius: number,\n outerRadius: number,\n rotationRad: number,\n): Point[] {\n const p = Math.max(3, Math.floor(points));\n const total = p * 2;\n const out: Point[] = new Array(total);\n const base = -Math.PI / 2 + rotationRad;\n const step = Math.PI / p; // half of full angular step\n for (let i = 0; i < total; i++) {\n const r = i % 2 === 0 ? outerRadius : innerRadius;\n const a = base + i * step;\n out[i] = { x: Math.cos(a) * r, y: Math.sin(a) * r };\n }\n return out;\n}\n\n/**\n * Ray from the origin toward `localFromCenter`, intersected with the polygon\n * silhouette. Returns the farthest hit (i.e. where the ray exits the\n * polygon) as a centre-relative point, or `null` if the ray doesn't cross\n * any edge.\n *\n * Used by `boundaryIntersect` to snap connector anchors to the exact\n * perimeter of polygonal shapes.\n */\nexport function rayPolygonIntersection(\n localFromCenter: Point,\n vertices: ReadonlyArray<Point>,\n): Point | null {\n const n = vertices.length;\n if (n < 2) return null;\n const dx = localFromCenter.x;\n const dy = localFromCenter.y;\n if (dx === 0 && dy === 0) return null;\n\n let bestT = -Infinity;\n let hit: Point | null = null;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const a = vertices[j]!;\n const b = vertices[i]!;\n const ex = b.x - a.x;\n const ey = b.y - a.y;\n // Solve [dx -ex] [t] = [a.x]\n // [dy -ey] [u] [a.y]\n const denom = dx * -ey - dy * -ex;\n if (denom === 0) continue;\n const t = (a.x * -ey - a.y * -ex) / denom;\n const u = (dx * a.y - dy * a.x) / denom;\n if (t >= 0 && u >= 0 && u <= 1 && t > bestT) {\n bestT = t;\n hit = { x: dx * t, y: dy * t };\n }\n }\n return hit;\n}\n\n/**\n * One vertex of a {@link roundedPolygonOutline} input ring: a corner point\n * plus the fillet radius to apply there. `r <= 0` keeps the corner sharp.\n */\nexport interface RoundedCorner extends Point {\n readonly r: number;\n}\n\n/**\n * Densify a closed corner ring into a polyline, replacing each corner that\n * carries `r > 0` with a tangent circular fillet.\n *\n * Works for **convex and concave** corners alike — the fillet centre is\n * placed along the corner's interior bisector, which flips side with the\n * corner's turn direction automatically. That's what lets a silhouette with\n * re-entrant corners (a folder's tab shoulder, a callout's notch) round its\n * outer corners while leaving the re-entrant ones sharp.\n *\n * The requested radius is clamped so a fillet can never consume more than\n * half of either adjacent edge, so authored radii larger than the geometry\n * degrade gracefully instead of self-intersecting. Arcs are sampled at\n * roughly one vertex per 2 px of arc length (min 2 segments), matching the\n * density the rounded-rect outline sampler uses.\n *\n * Output winds in the same direction as the input ring, starting at the\n * first corner (or the start of its fillet when it has one).\n */\nexport function roundedPolygonOutline(\n corners: ReadonlyArray<RoundedCorner>,\n): Point[] {\n const n = corners.length;\n if (n < 3) return corners.map((c) => ({ x: c.x, y: c.y }));\n\n const out: Point[] = [];\n for (let i = 0; i < n; i++) {\n const p = corners[i]!;\n const prev = corners[(i + n - 1) % n]!;\n const next = corners[(i + 1) % n]!;\n\n // Unit vectors from the corner toward each neighbour.\n const v1x = prev.x - p.x;\n const v1y = prev.y - p.y;\n const v2x = next.x - p.x;\n const v2y = next.y - p.y;\n const l1 = Math.hypot(v1x, v1y);\n const l2 = Math.hypot(v2x, v2y);\n if (p.r <= 0 || l1 < 1e-9 || l2 < 1e-9) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n const u1x = v1x / l1;\n const u1y = v1y / l1;\n const u2x = v2x / l2;\n const u2y = v2y / l2;\n\n // Interior half-angle at the corner. Collinear neighbours (θ ≈ π, a\n // straight run) and 180° spikes (θ ≈ 0) have no well-defined fillet.\n const cosT = Math.max(-1, Math.min(1, u1x * u2x + u1y * u2y));\n const theta = Math.acos(cosT);\n if (theta < 1e-6 || Math.PI - theta < 1e-6) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n const half = theta / 2;\n\n // Tangent distance from the corner, clamped to half of each adjacent\n // edge so neighbouring fillets can't overlap. The effective radius is\n // recovered from the clamped distance.\n const tangent = Math.min(p.r / Math.tan(half), l1 / 2, l2 / 2);\n const radius = tangent * Math.tan(half);\n if (radius < 1e-6) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n\n // Fillet centre sits along the bisector at `radius / sin(half)`.\n let bx = u1x + u2x;\n let by = u1y + u2y;\n const bl = Math.hypot(bx, by);\n if (bl < 1e-9) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n bx /= bl;\n by /= bl;\n const cx = p.x + bx * (radius / Math.sin(half));\n const cy = p.y + by * (radius / Math.sin(half));\n\n const a1 = Math.atan2(p.y + u1y * tangent - cy, p.x + u1x * tangent - cx);\n const a2 = Math.atan2(p.y + u2y * tangent - cy, p.x + u2x * tangent - cx);\n // Take the minor arc — the fillet never sweeps more than π.\n let delta = a2 - a1;\n while (delta > Math.PI) delta -= 2 * Math.PI;\n while (delta < -Math.PI) delta += 2 * Math.PI;\n\n const steps = Math.max(2, Math.ceil((Math.abs(delta) * radius) / 2));\n for (let s = 0; s <= steps; s++) {\n const a = a1 + delta * (s / steps);\n out.push({ x: cx + Math.cos(a) * radius, y: cy + Math.sin(a) * radius });\n }\n }\n return out;\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\nfunction signedArea(vertices: ReadonlyArray<Point>): number {\n let sum = 0;\n const n = vertices.length;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const a = vertices[j]!;\n const b = vertices[i]!;\n sum += (b.x - a.x) * (b.y + a.y);\n }\n // Shoelace's signed area is half this sum, with sign flipped for screen\n // coordinates (y grows down). Positive return = counter-clockwise in\n // screen space.\n return -sum * 0.5;\n}\n\nfunction unitNormal(a: Point, b: Point, ccw: boolean): Point {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy) || 1;\n // Inward-facing perpendicular: rotate the edge vector by ±90°.\n // CCW polygon (screen space): inward = rotate edge left → (-dy, dx).\n // CW polygon: inward = rotate edge right → (dy, -dx).\n return ccw ? { x: -dy / len, y: dx / len } : { x: dy / len, y: -dx / len };\n}\n","/**\n * The `tabbed-rect` (manila folder) silhouette, as pure maths.\n *\n * Every edge coordinate the outline, fold line, label box, bounds and hit test\n * are built from is resolved here, from the spec alone. It lives in `specs/`\n * rather than beside the renderer because the folder's footprint is a genuine\n * property of the *description* — a layout asking how big a container frame is,\n * an SVG export tracing it, and a headless hit-test all need the same answer\n * without a GPU (`docs/renderer-split-design.md` §4.5).\n *\n * Coordinates are **AABB-origin-relative**: `(0, 0)` is the top-left of the\n * full silhouette, which is the tab band's top-left when the tab is flush left.\n */\n\nimport type { Point, Rect } from '../geometry';\nimport type { TabbedRectSpec } from '../shape';\nimport { roundedPolygonOutline, type RoundedCorner } from './polygonMath';\n\n/** A tabbed-rect spec with its world position removed — geometry only. */\nexport type TabbedRectGeometrySpec = Omit<TabbedRectSpec, 'x' | 'y'>;\n\n/**\n * Every edge coordinate the silhouette, fold line and label box are built\n * from, resolved once against `inset`. `null` when the inset has collapsed the\n * geometry to nothing.\n *\n * The inset is applied analytically per edge rather than via a polygon offset:\n * the re-entrant shoulder corners make a bisector offset unstable, and all but\n * the slanted edges are axis-aligned, so the exact answer is one addition.\n */\nexport interface TabbedRectGeometry {\n left: number;\n right: number;\n bottom: number;\n /** Top of the tab — the silhouette's topmost edge. */\n tabTop: number;\n /** Where the tab meets the body; the fold line's y. */\n shoulder: number;\n /** Tab extent at its **base**, where it meets the body. */\n tabLeft: number;\n tabRight: number;\n /** Tab extent at its **top**, narrowed by the slant on whichever side leans. */\n tabTopLeft: number;\n tabTopRight: number;\n flushLeft: boolean;\n flushRight: boolean;\n /**\n * `true` when `spec.height <= 0` and the silhouette is the tab alone — the\n * closed folder. `left` / `right` / `bottom` describe the tab, and there is\n * no fold line. See {@link bodylessGeometryOf}.\n */\n bodyless: boolean;\n}\n\n/**\n * Resolved tab width: the declared {@link TabbedRectSpec.tabWidth}, falling\n * back to the body's width when it's left unset (a full-width tab).\n *\n * Clamped to the body while there is one — a tab can't outgrow the rectangle\n * it sits on. A bodyless folder's tab *is* the silhouette, so it sizes freely.\n */\nexport function tabbedRectTabWidth(spec: TabbedRectGeometrySpec): number {\n const declared = spec.tabWidth ?? spec.width;\n return spec.height <= 0 ? declared : Math.min(declared, spec.width);\n}\n\n/**\n * AABB of the folder.\n *\n * Bodyless (`height <= 0`): the tab *is* the silhouette, so it's also the\n * footprint — the declared body width describes a rectangle that isn't being\n * drawn. Everything positioned against the AABB (the label box, decorations,\n * edge anchors) therefore lands on the tab.\n */\nexport function tabbedRectBounds(spec: TabbedRectGeometrySpec): Rect {\n if (spec.height <= 0) {\n return { x: 0, y: 0, width: tabbedRectTabWidth(spec), height: spec.tabHeight };\n }\n return { x: 0, y: 0, width: spec.width, height: spec.tabHeight + spec.height };\n}\n\n/**\n * The folder, closed: body gone, tab kept. `width` is deliberately left alone —\n * {@link tabbedRectBounds} already reports the tab as the footprint once the\n * body is gone, so rewriting it would double-apply.\n */\nexport function collapsedTabbedRect(\n _spec: TabbedRectGeometrySpec,\n): Partial<TabbedRectSpec> {\n return { height: 0 };\n}\n\n/**\n * Size the tab to the content it carries — the title.\n *\n * The taper eats into the tab's top edge, so the slant's run is added on top of\n * the text budget; otherwise leaning the tab would push the title into the\n * taper. A centred tab leans on both sides.\n *\n * The clamp to `width` applies **only while there's a body**: a tab can't\n * outgrow the rectangle it sits on, but a closed folder is nothing *but* its\n * tab, so it sizes to the whole title rather than ellipsising it. Returns\n * nothing when {@link TabbedRectSpec.tabWidth} is pinned.\n */\nexport function fitTabbedRectToContent(\n spec: TabbedRectGeometrySpec,\n content: { readonly width: number; readonly height: number },\n): Partial<TabbedRectSpec> {\n if (spec.tabWidth !== undefined) return {};\n const pad = spec.tabPadding ?? 10;\n const slantSides = (spec.tabAlign ?? 'left') === 'center' ? 2 : 1;\n const fitted = content.width + 2 * pad + (spec.tabSkew ?? 0) * slantSides;\n return { tabWidth: spec.height <= 0 ? fitted : Math.min(spec.width, fitted) };\n}\n\n/** Uniform scale of every length the folder carries. */\nexport function scaleTabbedRect(\n spec: TabbedRectGeometrySpec,\n factor: number,\n): Partial<TabbedRectSpec> {\n return {\n width: spec.width * factor,\n height: spec.height * factor,\n tabHeight: spec.tabHeight * factor,\n ...(spec.tabWidth !== undefined ? { tabWidth: spec.tabWidth * factor } : {}),\n ...(spec.tabPadding !== undefined ? { tabPadding: spec.tabPadding * factor } : {}),\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius * factor } : {}),\n ...(spec.tabCornerRadius !== undefined\n ? { tabCornerRadius: spec.tabCornerRadius * factor }\n : {}),\n ...(spec.tabOffset !== undefined ? { tabOffset: spec.tabOffset * factor } : {}),\n ...(spec.tabSkew !== undefined ? { tabSkew: spec.tabSkew * factor } : {}),\n };\n}\n\n/**\n * Trace the folder silhouette into a polyline, inset by `inset` on every side.\n * Winds clockwise from the tab's top-left corner.\n *\n * The two re-entrant shoulders stay sharp; the convex corners take a fillet.\n * Rounding a shoulder reads as a dent rather than a fold.\n */\nexport function tabbedRectOutline(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): Point[] {\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo) return [];\n const { left, right, bottom, tabTop, shoulder, tabLeft, tabRight } = geo;\n\n const r = Math.max(0, (spec.cornerRadius ?? 0) - inset);\n const tr = Math.max(0, (spec.tabCornerRadius ?? spec.cornerRadius ?? 0) - inset);\n\n const corners: RoundedCorner[] = [];\n corners.push({ x: geo.tabTopLeft, y: tabTop, r: tr });\n corners.push({ x: geo.tabTopRight, y: tabTop, r: tr });\n // Closed folder — the tab's base closes the outline, so there are no\n // shoulders to turn and the body's fillet applies to its two bottom corners.\n if (geo.bodyless) {\n corners.push({ x: tabRight, y: bottom, r });\n corners.push({ x: tabLeft, y: bottom, r });\n return roundedPolygonOutline(corners);\n }\n if (geo.flushRight) {\n // Tab reaches the body's right edge — the tab's leaning (or vertical)\n // side runs straight into the body's side, one convex bend.\n corners.push({ x: right, y: shoulder, r });\n } else {\n corners.push({ x: tabRight, y: shoulder, r: 0 });\n corners.push({ x: right, y: shoulder, r });\n }\n corners.push({ x: right, y: bottom, r });\n corners.push({ x: left, y: bottom, r });\n if (!geo.flushLeft) {\n corners.push({ x: left, y: shoulder, r });\n corners.push({ x: tabLeft, y: shoulder, r: 0 });\n }\n return roundedPolygonOutline(corners);\n}\n\n/**\n * The tab's bottom border — the fold where the tab meets the body — as a\n * two-point segment, or `undefined` when `tabDivider` is off or the geometry\n * has collapsed. Spans the tab's **base**, so with a flush tab it starts on the\n * body's own edge and the two borders meet cleanly.\n */\nexport function tabbedRectFoldLine(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): [Point, Point] | undefined {\n if (spec.tabDivider === false) return undefined;\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo || geo.bodyless) return undefined;\n return [\n { x: geo.tabLeft, y: geo.shoulder },\n { x: geo.tabRight, y: geo.shoulder },\n ];\n}\n\n/**\n * The tab's **upright** box — its full-height portion, with the slant excluded\n * on whichever side is angled. This is where the folder's own label belongs:\n * the body interior belongs to whatever the frame contains, so a title centred\n * against this box stays put no matter how large the body grows.\n */\nexport function tabbedRectTabBox(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): Rect | undefined {\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo) return undefined;\n return {\n x: geo.tabTopLeft,\n y: geo.tabTop,\n width: Math.max(0, geo.tabTopRight - geo.tabTopLeft),\n height: geo.shoulder - geo.tabTop,\n };\n}\n\n/** Resolve every edge coordinate of the folder against `inset`. */\nexport function tabbedRectGeometry(\n spec: TabbedRectGeometrySpec,\n inset: number,\n): TabbedRectGeometry | null {\n if (spec.height <= 0) return bodylessGeometryOf(spec, inset);\n const totalH = spec.tabHeight + spec.height;\n const left = inset;\n const right = spec.width - inset;\n const bottom = totalH - inset;\n const tabTop = inset;\n const shoulder = spec.tabHeight + inset;\n if (right <= left || bottom <= shoulder) return null;\n\n const x0 = tabXOf(spec);\n const tabLeft = Math.max(left, x0 + inset);\n const tabRight = Math.min(right, x0 + tabbedRectTabWidth(spec) - inset);\n if (tabRight <= tabLeft) return null;\n\n // The tab leans away from the side it hugs, so the angled edge is always\n // the one facing the rest of the frame. A centred tab leans both ways.\n const align = spec.tabAlign ?? 'left';\n const flushLeft = tabLeft - left < 1e-6;\n const flushRight = right - tabRight < 1e-6;\n // A side flush with the body's edge merges into it and can't lean.\n const slantLeft = (align === 'right' || align === 'center') && !flushLeft;\n const slantRight = (align === 'left' || align === 'center') && !flushRight;\n\n const sides = (slantLeft ? 1 : 0) + (slantRight ? 1 : 0);\n // Clamp so the slants can never eat more than half the tab — an over-large\n // skew degrades to a triangle-ish tab instead of inverting the top edge.\n const skew =\n sides === 0\n ? 0\n : Math.max(0, Math.min(spec.tabSkew ?? 0, (tabRight - tabLeft) / (2 * sides)));\n\n return {\n left,\n right,\n bottom,\n tabTop,\n shoulder,\n tabLeft,\n tabRight,\n tabTopLeft: tabLeft + (slantLeft ? skew : 0),\n tabTopRight: tabRight - (slantRight ? skew : 0),\n flushLeft,\n flushRight,\n bodyless: false,\n };\n}\n\n/**\n * Geometry for a **bodyless** spec (`height <= 0`) — the closed folder: the\n * silhouette is the tab and nothing else.\n *\n * Two things flip relative to {@link tabbedRectGeometry}'s main path, both\n * because the tab's base stops being an interior fold and becomes the outline's\n * bottom edge:\n *\n * - The inset pulls that edge **up** (`tabHeight − inset`) instead of pushing\n * the body's top edge down, so a decoration borrowing this silhouette insets\n * uniformly rather than growing downward.\n * - The tab may **lean on either side regardless of flushness**. In the main\n * path a side flush with the body's edge can't slant (it merges into it);\n * with no body there's nothing to merge with, so a tab spanning the full\n * declared width still gets its taper — which is what keeps a collapsed\n * frame reading as a folder rather than a plain rounded rect.\n */\nfunction bodylessGeometryOf(\n spec: TabbedRectGeometrySpec,\n inset: number,\n): TabbedRectGeometry | null {\n const tabTop = inset;\n const base = spec.tabHeight - inset;\n const tabLeft = inset;\n const tabRight = tabbedRectTabWidth(spec) - inset;\n if (base <= tabTop || tabRight <= tabLeft) return null;\n\n const align = spec.tabAlign ?? 'left';\n const slantLeft = align === 'right' || align === 'center';\n const slantRight = align === 'left' || align === 'center';\n const sides = (slantLeft ? 1 : 0) + (slantRight ? 1 : 0);\n const skew =\n sides === 0\n ? 0\n : Math.max(0, Math.min(spec.tabSkew ?? 0, (tabRight - tabLeft) / (2 * sides)));\n\n return {\n left: tabLeft,\n right: tabRight,\n bottom: base,\n tabTop,\n // No fold to sit on: the shoulder *is* the outline's bottom edge, which\n // keeps the label box (tabTop → shoulder) spanning the whole tab.\n shoulder: base,\n tabLeft,\n tabRight,\n tabTopLeft: tabLeft + (slantLeft ? skew : 0),\n tabTopRight: tabRight - (slantRight ? skew : 0),\n flushLeft: true,\n flushRight: true,\n bodyless: true,\n };\n}\n\n/** Left edge of the tab's base in shape-local space, resolved from `tabAlign`. */\nfunction tabXOf(spec: TabbedRectGeometrySpec): number {\n // Bodyless: the tab is the whole footprint, so it starts at the origin —\n // there's no body left for it to be aligned against or offset from.\n if (spec.height <= 0) return 0;\n const tabW = tabbedRectTabWidth(spec);\n const offset = spec.tabOffset ?? 0;\n switch (spec.tabAlign ?? 'left') {\n case 'center':\n return (spec.width - tabW) / 2;\n case 'right':\n return Math.max(0, spec.width - tabW - offset);\n default:\n return Math.min(offset, Math.max(0, spec.width - tabW));\n }\n}\n","/**\n * Per-kind spec measurement: **bounds**, **uniform scale**, **collapse** and\n * **fit-to-content**, as pure functions of the spec.\n *\n * These four used to live as `static` methods on the renderer-side shape\n * classes. They are not drawing — they are properties of the description, and\n * a layout, an exporter or a headless test needs them with no GPU in the\n * process. The shape classes now delegate here, so there is one implementation\n * per kind (`docs/renderer-split-design.md` §9, P4).\n *\n * Every function takes the spec **without** `x` / `y`: bounds are local, so the\n * world position is the caller's business.\n */\n\nimport type { Point, Rect } from '../geometry';\nimport type {\n ArcSpec,\n CircleSpec,\n CompositeRootSpec,\n CompositeSpec,\n EllipseSpec,\n PathSpec,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n StarSpec,\n} from '../shape';\nimport {\n polygonBounds,\n regularPolygonVertices,\n starVertices,\n} from './polygonMath';\n\n/** A spec of kind `K` with its world position removed — geometry only. */\nexport type LocalSpec<T> = Omit<T, 'x' | 'y'>;\n\nconst TAU = Math.PI * 2;\n\n// ─── circle ────────────────────────────────────────────────────────────────\n\nexport function boundsOfCircle(spec: LocalSpec<CircleSpec>): Rect {\n const r = spec.radius;\n return { x: -r, y: -r, width: r * 2, height: r * 2 };\n}\n\nexport function scaleCircle(\n spec: LocalSpec<CircleSpec>,\n factor: number,\n): Partial<CircleSpec> {\n return { radius: spec.radius * factor };\n}\n\n// ─── ellipse ───────────────────────────────────────────────────────────────\n\nexport function boundsOfEllipse(spec: LocalSpec<EllipseSpec>): Rect {\n return {\n x: -spec.radiusX,\n y: -spec.radiusY,\n width: spec.radiusX * 2,\n height: spec.radiusY * 2,\n };\n}\n\nexport function scaleEllipse(\n spec: LocalSpec<EllipseSpec>,\n factor: number,\n): Partial<EllipseSpec> {\n return { radiusX: spec.radiusX * factor, radiusY: spec.radiusY * factor };\n}\n\n// ─── rect ──────────────────────────────────────────────────────────────────\n\n/** Anchored top-left, so the local box starts at the origin. */\nexport function boundsOfRect(spec: LocalSpec<RectSpec>): Rect {\n return { x: 0, y: 0, width: spec.width, height: spec.height };\n}\n\nexport function scaleRect(\n spec: LocalSpec<RectSpec>,\n factor: number,\n): Partial<RectSpec> {\n return {\n width: spec.width * factor,\n height: spec.height * factor,\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius * factor } : {}),\n };\n}\n\n// ─── polygon ───────────────────────────────────────────────────────────────\n\nexport function boundsOfPolygon(spec: LocalSpec<PolygonSpec>): Rect {\n return polygonBounds(spec.vertices);\n}\n\nexport function scalePolygon(\n spec: LocalSpec<PolygonSpec>,\n factor: number,\n): Partial<PolygonSpec> {\n return { vertices: spec.vertices.map((v) => ({ x: v.x * factor, y: v.y * factor })) };\n}\n\n// ─── regular-polygon ───────────────────────────────────────────────────────\n\n/** The n-gon's vertices at its authored size, centred on the origin. */\nexport function verticesOfRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n): Point[] {\n return regularPolygonVertices(spec.sides, spec.radius, spec.rotation ?? 0);\n}\n\nexport function boundsOfRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n): Rect {\n return polygonBounds(verticesOfRegularPolygon(spec));\n}\n\nexport function scaleRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n factor: number,\n): Partial<RegularPolygonSpec> {\n return { radius: spec.radius * factor };\n}\n\n// ─── star ──────────────────────────────────────────────────────────────────\n\n/** The star's alternating outer / inner vertices, centred on the origin. */\nexport function verticesOfStar(spec: LocalSpec<StarSpec>): Point[] {\n return starVertices(spec.points, spec.innerRadius, spec.outerRadius, spec.rotation ?? 0);\n}\n\nexport function boundsOfStar(spec: LocalSpec<StarSpec>): Rect {\n return polygonBounds(verticesOfStar(spec));\n}\n\nexport function scaleStar(\n spec: LocalSpec<StarSpec>,\n factor: number,\n): Partial<StarSpec> {\n return {\n innerRadius: spec.innerRadius * factor,\n outerRadius: spec.outerRadius * factor,\n };\n}\n\n// ─── arc ───────────────────────────────────────────────────────────────────\n\n/**\n * Axis-aligned bounding box for an annular sector. The extreme points are\n * either on the four sector corners (a0/inner, a0/outer, a1/inner, a1/outer)\n * or at the cardinal angles (0, π/2, π, 3π/2) on the outer radius if those\n * angles fall inside the sweep — those produce the (±outerR, 0) / (0, ±outerR)\n * extents.\n */\nexport function boundsOfArc(spec: LocalSpec<ArcSpec>): Rect {\n const { innerR, outerR, startAngle: a0, endAngle: a1 } = spec;\n if (a1 <= a0 || outerR <= 0) return { x: 0, y: 0, width: 0, height: 0 };\n\n // Corners always contribute.\n const corners: Point[] = [\n { x: Math.cos(a0) * innerR, y: Math.sin(a0) * innerR },\n { x: Math.cos(a0) * outerR, y: Math.sin(a0) * outerR },\n { x: Math.cos(a1) * innerR, y: Math.sin(a1) * innerR },\n { x: Math.cos(a1) * outerR, y: Math.sin(a1) * outerR },\n ];\n\n // Add the cardinal-angle extents on the outer radius if the sweep crosses\n // them. Normalise everything into a single circle's worth of revolutions so\n // sweeps that wrap past 2π still pick up all four cardinals.\n const sweep = a1 - a0;\n for (const k of [0, 1, 2, 3]) {\n const cardinal = (k * Math.PI) / 2;\n // First multiple of 2π that lands `cardinal` at or after a0.\n let n = Math.ceil((a0 - cardinal) / TAU);\n if (cardinal + n * TAU < a0) n++;\n const angle = cardinal + n * TAU;\n if (angle <= a1 || sweep >= TAU) {\n corners.push({ x: Math.cos(angle) * outerR, y: Math.sin(angle) * outerR });\n }\n }\n\n return polygonBounds(corners);\n}\n\nexport function scaleArc(\n spec: LocalSpec<ArcSpec>,\n factor: number,\n): Partial<ArcSpec> {\n return { innerR: spec.innerR * factor, outerR: spec.outerR * factor };\n}\n\n// ─── path ──────────────────────────────────────────────────────────────────\n\nexport function boundsOfPath(spec: LocalSpec<PathSpec>): Rect {\n return polygonBounds(spec.points);\n}\n\nexport function scalePath(\n spec: LocalSpec<PathSpec>,\n factor: number,\n): Partial<PathSpec> {\n return { points: spec.points.map((p) => ({ x: p.x * factor, y: p.y * factor })) };\n}\n\n// ─── composite ─────────────────────────────────────────────────────────────\n\n/**\n * The composite's silhouette fills its declared box (like a rect), whatever\n * root shape it borrows — the root is centred and sized to that box. Layouts\n * (ELK et al.) read node dimensions through this; without it every card falls\n * back to the layout's default size and they overlap.\n */\nexport function boundsOfComposite(\n spec: Pick<CompositeSpec, 'width' | 'height'>,\n): Rect {\n return { x: 0, y: 0, width: spec.width, height: spec.height };\n}\n\n/**\n * The composite's effective root spec: the explicit\n * {@link CompositeSpec.root}, or the default rounded rect built from\n * `cornerRadius` + the inherited `fill` / `stroke`.\n */\nexport function resolveCompositeRoot(spec: CompositeSpec): CompositeRootSpec {\n if (spec.root) return spec.root;\n return {\n kind: 'rect',\n x: 0,\n y: 0,\n width: spec.width,\n height: spec.height,\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius } : {}),\n ...(spec.fill !== undefined ? { fill: spec.fill } : {}),\n ...(spec.stroke !== undefined ? { stroke: spec.stroke } : {}),\n };\n}\n\n/** Local bounds of whichever shape a composite borrows for its silhouette. */\nexport function boundsOfCompositeRoot(root: CompositeRootSpec): Rect {\n switch (root.kind) {\n case 'circle':\n return boundsOfCircle(root);\n case 'ellipse':\n return boundsOfEllipse(root);\n case 'polygon':\n return boundsOfPolygon(root);\n case 'regular-polygon':\n return boundsOfRegularPolygon(root);\n case 'star':\n return boundsOfStar(root);\n case 'arc':\n return boundsOfArc(root);\n default:\n return boundsOfRect(root);\n }\n}\n\n/**\n * Translation from the composite's top-left origin to the borrowed root's own\n * local origin — the offset that centres the root in the `width × height` box.\n *\n * Origin-agnostic by construction: it works off the root's *bounding-box*\n * centre, so a rect (top-left origin) and a circle (centred origin) both land\n * in the middle of the card. The renderer applies exactly this before tracing\n * the root, which is why hit-testing has to apply it too.\n */\nexport function compositeRootOffset(spec: CompositeSpec): Point {\n const b = boundsOfCompositeRoot(resolveCompositeRoot(spec));\n return {\n x: spec.width / 2 - (b.x + b.width / 2),\n y: spec.height / 2 - (b.y + b.height / 2),\n };\n}\n","/**\n * Pure geometric containment, per spec kind — the engine's hit-test narrow\n * phase with no GPU in it.\n *\n * ## Why this exists\n *\n * Picking used to ask the backend: `bodyGfx.containsPoint(...)`, i.e. pixi\n * walked the instructions it had recorded while painting. That made the answer\n * depend on a display object existing, so picking could not be tested headlessly\n * and would have left the engine with the renderer under the P6 extraction\n * (`docs/renderer-split-design.md` §5 — \"geometry answers must not require the\n * backend\"). Here the answer comes from the spec alone, so every backend agrees\n * by construction.\n *\n * ## Matching pixi\n *\n * `Graphics.containsPoint` is a **union over painted instructions**: a `fill`\n * instruction answers `shape.contains`, a `stroke` instruction answers\n * `shape.strokeContains`. Two consequences are reproduced here deliberately:\n *\n * 1. **A shape with no silhouette fill is hollow.** No fill was painted, so only\n * the stroke band answers `true` — clicking the middle of an outline-only\n * contour misses it, exactly as it does today.\n * 2. **The stroke widens the region by its alignment split**: `'center'`\n * (default) puts half the width outside and half inside, `'outside'` puts all\n * of it outside, `'inside'` all of it inside. That mirrors pixi's\n * `outerWidth = (1 - alignment) * width`.\n *\n * Coordinates are **shape-local** — `(0, 0)` is the shape's own origin (centre\n * for circle / ellipse / polygon / star / arc, top-left for rect / tabbed-rect /\n * composite), i.e. the caller has already subtracted `spec.x` / `spec.y` and\n * divided out any renderer-applied scale.\n */\n\nimport type {\n ArcSpec,\n BaseShapeSpec,\n CircleSpec,\n CompositeRootSpec,\n CompositeSpec,\n EllipseSpec,\n PathSpec,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n StarSpec,\n TabbedRectSpec,\n} from '../shape';\nimport { hasSilhouetteFill, type ShapeStroke } from '../style';\nimport {\n compositeRootOffset,\n resolveCompositeRoot,\n verticesOfRegularPolygon,\n verticesOfStar,\n type LocalSpec,\n} from './bounds';\nimport {\n distanceToSegmentSq,\n polygonContainsInflated,\n} from './polygonMath';\nimport { tabbedRectOutline } from './tabbedRect';\n\nconst TAU = Math.PI * 2;\n\n/**\n * How far a stroke pushes the hit region past the silhouette (`outer`) and how\n * far it reaches back inside it (`inner`).\n *\n * Mirrors pixi's split: `outer = (1 - alignment) * width`, `inner = width -\n * outer`, with the engine's `'inside' | 'center' | 'outside'` mapping to\n * pixi's `1 | 0.5 | 0` alignment. A missing or non-positive width paints\n * nothing, so it widens nothing.\n */\nexport function strokeBandOf(stroke: ShapeStroke | undefined): {\n outer: number;\n inner: number;\n} {\n const width = stroke?.width ?? (stroke ? 1 : 0);\n if (!stroke || width <= 0) return { outer: 0, inner: 0 };\n const alignment = stroke.alignment === 'inside' ? 1 : stroke.alignment === 'outside' ? 0 : 0.5;\n const outer = (1 - alignment) * width;\n return { outer, inner: width - outer };\n}\n\n// ─── Per-kind containment ──────────────────────────────────────────────────\n//\n// Each takes a `pad`: positive grows the silhouette, negative erodes it. That\n// one parameter expresses both halves of the stroke band, so the fill-less\n// \"hollow\" case is `grown && !eroded` rather than a second family of functions.\n\nexport function containsCircle(\n spec: LocalSpec<CircleSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const r = spec.radius + pad;\n if (r <= 0) return false;\n return localX * localX + localY * localY <= r * r;\n}\n\nexport function containsEllipse(\n spec: LocalSpec<EllipseSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n // Padding an ellipse by its radii is not a true parallel offset (the exact\n // offset curve isn't an ellipse), but it is precisely what pixi's\n // `Ellipse.strokeContains` does, so picking stays consistent with what the\n // user sees highlighted.\n const rx = spec.radiusX + pad;\n const ry = spec.radiusY + pad;\n if (rx <= 0 || ry <= 0) return false;\n const nx = localX / rx;\n const ny = localY / ry;\n return nx * nx + ny * ny <= 1;\n}\n\nexport function containsRect(\n spec: LocalSpec<RectSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const w = spec.width + pad * 2;\n const h = spec.height + pad * 2;\n if (w <= 0 || h <= 0) return false;\n const left = -pad;\n const top = -pad;\n if (localX < left || localX > left + w || localY < top || localY > top + h) return false;\n\n const r = Math.min(Math.max(0, (spec.cornerRadius ?? 0) + pad), w / 2, h / 2);\n if (r <= 0) return true;\n // Outside the four corner discs = outside the rounded rect. Clamping the\n // point into the inner \"core\" rectangle finds the nearest corner centre in\n // one step (pixi's `RoundedRectangle.contains` does the same).\n const cx = clamp(localX, left + r, left + w - r);\n const cy = clamp(localY, top + r, top + h - r);\n const dx = localX - cx;\n const dy = localY - cy;\n return dx * dx + dy * dy <= r * r;\n}\n\nexport function containsPolygon(\n spec: LocalSpec<PolygonSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, spec.vertices, pad);\n}\n\nexport function containsRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, verticesOfRegularPolygon(spec), pad);\n}\n\nexport function containsStar(\n spec: LocalSpec<StarSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, verticesOfStar(spec), pad);\n}\n\nexport function containsTabbedRect(\n spec: LocalSpec<TabbedRectSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n // The outline is already densified through its fillets, so the generic\n // polygon test covers the rounded corners and the re-entrant shoulders alike.\n // The fold line is interior geometry and never part of the silhouette.\n return polygonContainsInflated(localX, localY, tabbedRectOutline(spec, 0), pad);\n}\n\n/**\n * An open path is tested against its **run**, not a phantom closed area: only a\n * `closed` (or `smooth`, which implies closed) path has an interior, matching\n * the paint path, which fills only when closed. So an unfilled contour line\n * answers `true` along its stroke and nowhere else.\n *\n * `smooth` paths are approximated by the control polygon rather than the\n * quadratic spline it generates. The spline passes through the segment\n * midpoints and bulges toward each control point, so the two differ by at most\n * half a segment's sagitta — a fraction of a pixel at contour densities.\n */\nexport function containsPath(\n spec: LocalSpec<PathSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const closed = spec.closed === true || spec.smooth === true;\n return polygonContainsInflated(localX, localY, spec.points, pad, closed);\n}\n\n/**\n * Annular sector, tested analytically rather than against a sampled outline:\n * radius inside `[innerR, outerR]` and angle inside the sweep, each relaxed by\n * `pad`. Outside the sweep the nearest point of the sector lies on one of the\n * two straight radial edges, so the padded test falls back to a distance check\n * against those two segments.\n */\nexport function containsArc(\n spec: LocalSpec<ArcSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const { startAngle: a0, endAngle: a1 } = spec;\n const innerR = Math.max(0, spec.innerR - pad);\n const outerR = spec.outerR + pad;\n if (a1 <= a0 || outerR <= 0) return false;\n\n const rSq = localX * localX + localY * localY;\n const inRadial = rSq >= innerR * innerR && rSq <= outerR * outerR;\n const inSweep = a1 - a0 >= TAU || angleWithin(Math.atan2(localY, localX), a0, a1);\n if (inSweep && inRadial) {\n if (pad >= 0) return true;\n // Eroding: also stay clear of the two radial edges, or the band along them\n // would be reported as interior.\n return distanceToRadialEdgesSq(spec, localX, localY) > pad * pad;\n }\n if (pad <= 0 || a1 - a0 >= TAU) return false;\n // Outside the sweep but possibly within `pad` of a radial edge.\n return distanceToRadialEdgesSq(spec, localX, localY) <= pad * pad;\n}\n\n/**\n * A composite is its **root silhouette** (centred in the card box) plus every\n * geometric part painted on top of it. Parts are included because they are\n * painted into the same `Graphics` the backend hit-tests today: a part that\n * pokes outside the root — an accent bar on an unclipped card — is clickable,\n * and stays clickable here.\n *\n * `label` parts are excluded: they are mounted as text children, not painted\n * into the body, so they never contributed a hit region.\n */\nexport function containsComposite(\n spec: CompositeSpec,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const off = compositeRootOffset(spec);\n const root = resolveCompositeRoot(spec);\n if (containsRootSpec(root, localX - off.x, localY - off.y, pad)) return true;\n\n for (const p of spec.parts) {\n if (p.part === 'rect') {\n if (p.fill === undefined && !p.stroke) continue;\n const box: LocalSpec<RectSpec> = {\n kind: 'rect',\n width: p.width,\n height: p.height,\n ...(p.cornerRadius !== undefined ? { cornerRadius: p.cornerRadius } : {}),\n };\n const half = partHalfStroke(p.stroke);\n if (\n withHollowRule(\n (q) => containsRect(box, localX - p.x, localY - p.y, q),\n p.fill !== undefined,\n pad + half,\n half,\n )\n ) {\n return true;\n }\n } else if (p.part === 'circle') {\n if (p.fill === undefined && !p.stroke) continue;\n const disc: LocalSpec<CircleSpec> = { kind: 'circle', radius: p.radius };\n const half = partHalfStroke(p.stroke);\n if (\n withHollowRule(\n (q) => containsCircle(disc, localX - p.x, localY - p.y, q),\n p.fill !== undefined,\n pad + half,\n half,\n )\n ) {\n return true;\n }\n } else if (p.part === 'line') {\n // Stroke-only geometry: a band of half the stroke width around the run.\n const tol = pad + partHalfStroke(p.stroke);\n if (tol > 0 && distanceToSegmentSq(localX, localY, p.x, p.y, p.x2, p.y2) <= tol * tol) {\n return true;\n }\n } else if (p.part === 'icon' && p.background) {\n // The chip behind the glyph is a filled rect; the glyph itself is a child.\n const chip: LocalSpec<RectSpec> = {\n kind: 'rect',\n width: p.size,\n height: p.size,\n ...(p.background.cornerRadius !== undefined\n ? { cornerRadius: p.background.cornerRadius }\n : {}),\n };\n if (containsRect(chip, localX - p.x, localY - p.y, pad)) return true;\n }\n }\n return false;\n}\n\n// ─── Dispatcher ────────────────────────────────────────────────────────────\n\n/**\n * Does `(localX, localY)` fall inside the region this spec paints?\n *\n * `strokeTolerance` overrides the widening the spec's own stroke would imply\n * (both inward and outward). Omit it and the band is derived from\n * `spec.stroke` — width and alignment — which is what the renderer wants: the\n * hit region then tracks whatever the shape actually draws.\n *\n * Returns `undefined` for a kind this module doesn't know. That is not a\n * failure: `registerShape` admits third-party kinds, and the caller falls back\n * to asking the instance (`IShape.getHitArea`). Distinguishing \"not contained\"\n * from \"cannot answer\" is the whole point of the `boolean | undefined` return.\n */\nexport function containsSpec(\n spec: BaseShapeSpec,\n localX: number,\n localY: number,\n strokeTolerance?: number,\n): boolean | undefined {\n const fn = CONTAINS[spec.kind];\n if (!fn) return undefined;\n\n // A composite resolves fill and stroke per borrowed root and per part — its\n // own `stroke` is already folded into the default root — so it owns the\n // hollow rule internally and takes only the caller's extra padding.\n if (spec.kind === 'composite') return fn(spec as never, localX, localY, strokeTolerance ?? 0);\n\n const band =\n strokeTolerance !== undefined\n ? { outer: strokeTolerance, inner: strokeTolerance }\n : strokeBandOf(spec.stroke);\n\n return withHollowRule(\n (pad) => fn(spec as never, localX, localY, pad),\n hasSilhouetteFill(spec.fill),\n band.outer,\n band.inner,\n );\n}\n\n/**\n * Kinds this module can answer for. Keyed by the same string the shape registry\n * uses, so a kind is answerable here exactly when the engine ships geometry for\n * it — third-party kinds are absent by design (see {@link containsSpec}).\n */\nconst CONTAINS: Record<\n string,\n (spec: never, x: number, y: number, pad: number) => boolean\n> = {\n circle: containsCircle as never,\n ellipse: containsEllipse as never,\n rect: containsRect as never,\n 'tabbed-rect': containsTabbedRect as never,\n polygon: containsPolygon as never,\n 'regular-polygon': containsRegularPolygon as never,\n star: containsStar as never,\n arc: containsArc as never,\n path: containsPath as never,\n composite: containsComposite as never,\n};\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\n/** Containment against whichever shape a composite borrows for its silhouette. */\nfunction containsRootSpec(\n root: CompositeRootSpec,\n x: number,\n y: number,\n pad: number,\n): boolean {\n const band = strokeBandOf(root.stroke);\n const test = (p: number): boolean => {\n switch (root.kind) {\n case 'circle':\n return containsCircle(root, x, y, p);\n case 'ellipse':\n return containsEllipse(root, x, y, p);\n case 'polygon':\n return containsPolygon(root, x, y, p);\n case 'regular-polygon':\n return containsRegularPolygon(root, x, y, p);\n case 'star':\n return containsStar(root, x, y, p);\n case 'arc':\n return containsArc(root, x, y, p);\n default:\n return containsRect(root, x, y, p);\n }\n };\n return withHollowRule(test, hasSilhouetteFill(root.fill), pad + band.outer, band.inner);\n}\n\n/**\n * Apply the fill-less **hollow** rule to a padded containment test: filled\n * geometry answers for its whole grown silhouette; unfilled geometry answers\n * only inside the stroke band, i.e. grown-by-`outer` minus eroded-by-`inner`.\n */\nfunction withHollowRule(\n test: (pad: number) => boolean,\n filled: boolean,\n outer: number,\n inner: number,\n): boolean {\n if (filled) return test(outer);\n if (outer <= 0 && inner <= 0) return false;\n return test(outer) && !test(-inner);\n}\n\n/**\n * Half-width of a composite part's stroke — the distance it reaches past the\n * traced path. Parts are stroked with the backend's default centred alignment,\n * so half the width falls outside; an absent stroke reaches nowhere.\n */\nfunction partHalfStroke(stroke: { readonly width?: number } | undefined): number {\n if (!stroke) return 0;\n return Math.max(0, stroke.width ?? 1) / 2;\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v;\n}\n\n/** Is `theta` inside `[a0, a1]`, allowing for sweeps that wrap past 2π? */\nfunction angleWithin(theta: number, a0: number, a1: number): boolean {\n // Bring θ into the same revolution as a0 so the comparison is unambiguous\n // across the 2π wrap (e.g. a sweep from 3π/2 to 5π/2 hitting θ ≈ 0.1).\n let n = Math.ceil((a0 - theta) / TAU);\n if (theta + n * TAU < a0) n++;\n const t = theta + n * TAU;\n return t >= a0 && t <= a1;\n}\n\n/** Squared distance to the sector's two straight radial edges. */\nfunction distanceToRadialEdgesSq(\n spec: LocalSpec<ArcSpec>,\n x: number,\n y: number,\n): number {\n const edge = (a: number): number => {\n const c = Math.cos(a);\n const s = Math.sin(a);\n return distanceToSegmentSq(\n x,\n y,\n c * spec.innerR,\n s * spec.innerR,\n c * spec.outerR,\n s * spec.outerR,\n );\n };\n return Math.min(edge(spec.startAngle), edge(spec.endAngle));\n}\n","/**\n * Spec geometry — bounds, scale, collapse, fit and containment, computed from a\n * spec and nothing else.\n *\n * This is the half of the old shape classes that was never really drawing: the\n * `static boundsOf` / `scaleSpec` / `collapsedOf` / `fitToContent` methods, plus\n * the new `contains`. They live here so a layout can size a node, an exporter\n * can trace a silhouette and a test can pick a shape with no backend mounted —\n * and so they stay in `@invana/canvas` when the pixi renderer is extracted\n * (`docs/renderer-split-design.md` §9, P4).\n *\n * The renderer-side shape classes now delegate to these functions; the maths\n * exists once.\n */\n\nexport * from './polygonMath';\nexport * from './tabbedRect';\nexport * from './bounds';\nexport * from './contains';\n\nimport type { Rect } from '../geometry';\nimport type { BaseShapeSpec } from '../shape';\nimport {\n boundsOfArc,\n boundsOfCircle,\n boundsOfComposite,\n boundsOfEllipse,\n boundsOfPath,\n boundsOfPolygon,\n boundsOfRect,\n boundsOfRegularPolygon,\n boundsOfStar,\n scaleArc,\n scaleCircle,\n scaleEllipse,\n scalePath,\n scalePolygon,\n scaleRect,\n scaleRegularPolygon,\n scaleStar,\n} from './bounds';\nimport {\n collapsedTabbedRect,\n fitTabbedRectToContent,\n scaleTabbedRect,\n tabbedRectBounds,\n} from './tabbedRect';\n\n/**\n * Local bounds of any built-in spec kind, or `undefined` for a kind this module\n * doesn't know.\n *\n * `undefined` is a real answer, not a failure: `registerShape` admits\n * third-party kinds, so callers that must cover those ask the registry (which\n * consults the class's `static boundsOf`) and fall back to a default box.\n */\nexport function boundsOfSpec(spec: BaseShapeSpec): Rect | undefined {\n switch (spec.kind) {\n case 'circle':\n return boundsOfCircle(spec as never);\n case 'ellipse':\n return boundsOfEllipse(spec as never);\n case 'rect':\n return boundsOfRect(spec as never);\n case 'tabbed-rect':\n return tabbedRectBounds(spec as never);\n case 'polygon':\n return boundsOfPolygon(spec as never);\n case 'regular-polygon':\n return boundsOfRegularPolygon(spec as never);\n case 'star':\n return boundsOfStar(spec as never);\n case 'arc':\n return boundsOfArc(spec as never);\n case 'path':\n return boundsOfPath(spec as never);\n case 'composite':\n return boundsOfComposite(spec as never);\n default:\n return undefined;\n }\n}\n\n/**\n * Uniformly scale a spec's geometry by `factor`, as a partial patch to merge\n * onto it. Paint is untouched — only lengths.\n *\n * The contract: `boundsOfSpec(scaleSpec(spec, k)).width === boundsOfSpec(spec).width * k`\n * (likewise height). `undefined` for kinds with no meaningful uniform scale\n * (`composite` sizes off its box and its parts, so scaling it needs the layer's\n * intent, not a geometric rule).\n */\nexport function scaleSpec(\n spec: BaseShapeSpec,\n factor: number,\n): Record<string, unknown> | undefined {\n switch (spec.kind) {\n case 'circle':\n return scaleCircle(spec as never, factor);\n case 'ellipse':\n return scaleEllipse(spec as never, factor);\n case 'rect':\n return scaleRect(spec as never, factor);\n case 'tabbed-rect':\n return scaleTabbedRect(spec as never, factor);\n case 'polygon':\n return scalePolygon(spec as never, factor);\n case 'regular-polygon':\n return scaleRegularPolygon(spec as never, factor);\n case 'star':\n return scaleStar(spec as never, factor);\n case 'arc':\n return scaleArc(spec as never, factor);\n case 'path':\n return scalePath(spec as never, factor);\n default:\n return undefined;\n }\n}\n\n/**\n * The spec \"as small as it goes\" — what a collapsed container renders as.\n * Purely geometric: the kind decides what collapsing means to it. `undefined`\n * when the kind has no collapsed form, and callers then keep the spec as is.\n */\nexport function collapsedSpec(\n spec: BaseShapeSpec,\n): Record<string, unknown> | undefined {\n return spec.kind === 'tabbed-rect' ? collapsedTabbedRect(spec as never) : undefined;\n}\n\n/**\n * Size the spec's geometry to a measured block of content (a title, a label).\n * The caller measures — text metrics belong to the backend — and the kind turns\n * that size into geometry. `undefined` when the kind doesn't size to content.\n */\nexport function fitSpecToContent(\n spec: BaseShapeSpec,\n content: { readonly width: number; readonly height: number },\n): Record<string, unknown> | undefined {\n return spec.kind === 'tabbed-rect'\n ? fitTabbedRectToContent(spec as never, content)\n : undefined;\n}\n","/**\n * Flush scheduling for the **non-reactive** data stores ({@link DataStore} /\n * {@link LayerData}). A write marks a dirty delta and *arms* a deferred flush; the\n * mode decides **when** that flush fires. The store never notifies per write — it\n * coalesces a whole batch into **one** flush (see `docs/canvas-store-data-event-flow.md` §2).\n */\n\n/** When a coalesced data flush fires. */\nexport type FlushMode =\n /** Next animation frame (browser). Falls back to `microtask` where no rAF exists (node/tests). */\n | 'frame'\n /** End of the current JS task — the kernel default (no DOM assumption, deterministic). */\n | 'microtask'\n /** Never auto-fires; the owner (e.g. the engine's single rAF loop) calls `flush()`. */\n | 'manual';\n\n// Feature-detect rAF so the renderer-free kernel makes no hard DOM assumption.\nconst raf: typeof requestAnimationFrame | undefined =\n typeof requestAnimationFrame === 'function' ? requestAnimationFrame : undefined;\nconst caf: typeof cancelAnimationFrame | undefined =\n typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : undefined;\n\n/**\n * Arm a deferred flush per `mode`, returning a **cancel** function (a no-op once the\n * callback has run or for modes that can't be cancelled). `'manual'` arms nothing.\n */\nexport function scheduleFlush(mode: FlushMode, cb: () => void): () => void {\n if (mode === 'manual') return () => {};\n if (mode === 'frame' && raf && caf) {\n const handle = raf(() => cb());\n return () => caf(handle);\n }\n // microtask — and the `frame` fallback when no rAF is present (node / tests)\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) cb();\n });\n return () => {\n cancelled = true;\n };\n}\n","/**\n * `SpecStore` — the durable **visual description** of one layer's elements.\n *\n * A spec says *what to draw* (`{ kind: 'circle', radius, fill, plane }`) and\n * contains no drawing code. Layers resolve style + templates into specs and\n * publish them here; renderers subscribe and project. That inversion is the\n * point: two backends reading one description cannot disagree about intent, and\n * the description is serialisable, diffable and testable without a GPU.\n *\n * **Generic over `T`, though it no longer has to be.** The vocabulary now sits\n * beside this file (`./index`), so this store *could* name its own element types.\n * It stays generic deliberately: nothing needs the narrowing, and a concrete\n * signature would ripple through `SpecProjector` and `GraphLayer` for no new\n * capability. The engine instantiates it as\n * `SpecStore<BaseShapeSpec | BaseConnectorSpec>`.\n *\n * **What does *not* live here:** positions. Those stay in {@link LayerData}'s\n * typed arrays on the machine-rate path — a drag frame moves nodes without\n * touching a single spec. And transient visuals (lasso, brush, drag ghosts) never\n * enter the store at all; they are drawn through the renderer's overlay device,\n * so gesture noise stays out of history, undo and saved files.\n *\n * Writes mark a dirty delta and arm a coalesced flush — the same contract as\n * {@link LayerData}, so both channels settle in the same frame.\n *\n * See `docs/renderer-split-design.md` §2 (specs as state) and §4.2b (the channel).\n */\n\nimport { scheduleFlush, type FlushMode } from '../state/data/flush';\n\n/**\n * One coalesced batch of spec changes. Ids only — the receiver reads the specs\n * it cares about, so a flush stays O(dirty) regardless of collection size.\n */\nexport interface SpecFlush {\n readonly added: readonly string[];\n readonly changed: readonly string[];\n readonly removed: readonly string[];\n /** Monotonic, per store. Lets a consumer detect a missed batch. */\n readonly version: number;\n}\n\nexport class SpecStore<T extends object = object> {\n private readonly specs = new Map<string, T>();\n private readonly added = new Set<string>();\n private readonly changed = new Set<string>();\n private readonly removed = new Set<string>();\n private readonly listeners = new Set<(e: SpecFlush) => void>();\n private version = 0;\n private scheduled = false;\n private flushMode: FlushMode = 'microtask';\n private cancel: (() => void) | undefined;\n\n // ── Reads ──────────────────────────────────────────────────────────────────\n\n get(id: string): T | undefined {\n return this.specs.get(id);\n }\n\n has(id: string): boolean {\n return this.specs.has(id);\n }\n\n get size(): number {\n return this.specs.size;\n }\n\n ids(): IterableIterator<string> {\n return this.specs.keys();\n }\n\n entries(): IterableIterator<[string, T]> {\n return this.specs.entries();\n }\n\n // ── Writes ─────────────────────────────────────────────────────────────────\n\n /** Publish (or replace) the spec for `id`. */\n set(id: string, spec: T): void {\n const existed = this.specs.has(id);\n this.specs.set(id, spec);\n if (existed) {\n this.removed.delete(id);\n // An id added and then re-set before the flush is still just \"added\".\n if (!this.added.has(id)) this.changed.add(id);\n } else {\n this.added.add(id);\n this.removed.delete(id);\n }\n this.schedule();\n }\n\n /**\n * Shallow-merge `partial` over the stored spec. Returns `false` when `id` is\n * unknown, so a caller can fall back to {@link set} with a full spec.\n */\n patch(id: string, partial: Partial<T>): boolean {\n const current = this.specs.get(id);\n if (!current) return false;\n this.specs.set(id, { ...current, ...partial });\n if (!this.added.has(id)) this.changed.add(id);\n this.schedule();\n return true;\n }\n\n delete(id: string): void {\n if (!this.specs.delete(id)) return;\n this.changed.delete(id);\n // Added-then-removed before a flush is a net no-op: the receiver never saw it.\n if (!this.added.delete(id)) this.removed.add(id);\n this.schedule();\n }\n\n /** Drop every spec. Emits one flush listing all ids as removed. */\n clear(): void {\n for (const id of this.specs.keys()) {\n if (!this.added.delete(id)) this.removed.add(id);\n }\n this.specs.clear();\n this.changed.clear();\n this.schedule();\n }\n\n // ── Flush ──────────────────────────────────────────────────────────────────\n\n onFlush(listener: (e: SpecFlush) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Choose **when** a coalesced flush fires. `'manual'` disarms auto-flush so the\n * engine's single rAF drives it — which is how the renderer stays on one clock.\n */\n setFlushMode(mode: FlushMode): void {\n this.flushMode = mode;\n if (mode === 'manual' && this.scheduled) {\n this.cancel?.();\n this.scheduled = false;\n }\n }\n\n /** Emit the pending delta, if any. Safe to call when nothing is dirty. */\n flush(): void {\n this.scheduled = false;\n if (this.added.size === 0 && this.changed.size === 0 && this.removed.size === 0) return;\n const event: SpecFlush = {\n added: [...this.added],\n changed: [...this.changed],\n removed: [...this.removed],\n version: ++this.version,\n };\n this.added.clear();\n this.changed.clear();\n this.removed.clear();\n for (const listener of this.listeners) listener(event);\n }\n\n private schedule(): void {\n if (this.scheduled || this.flushMode === 'manual') return;\n this.scheduled = true;\n this.cancel = scheduleFlush(this.flushMode, () => this.flush());\n }\n}\n","/**\n * `ICameraBinding` with no backend behind it.\n *\n * The projection math mirrors the engine's coordinate model exactly\n * (`screen = world * zoom + offset`), so camera semantics — clamping, anchored\n * zoom, fit, the bus and store sync — are exercisable with no GPU.\n * `emitTransformChange` simulates a backend-driven gesture (a wheel tick, a\n * momentum glide), the one path `Camera` cannot trigger itself.\n *\n * Shipped rather than test-only: §7 keeps a headless backend deliberately, so\n * consumers can test layouts, picking and projection without a renderer.\n */\n\nimport type { Point, Rect } from '../specs/geom';\nimport type {\n CameraChangeKind,\n CameraInputConfig,\n CameraTransformValue,\n ICameraBinding,\n} from '../contracts/ICameraBinding';\n\nexport class HeadlessCameraBinding implements ICameraBinding {\n private t: CameraTransformValue = { x: 0, y: 0, zoom: 1 };\n private screenWidth: number;\n private screenHeight: number;\n private readonly changeListeners = new Set<(kind: CameraChangeKind) => void>();\n private readonly dragStartListeners = new Set<() => void>();\n\n /** Every `configureInput` patch received, in order — for asserting input wiring. */\n readonly inputConfigs: CameraInputConfig[] = [];\n /** Latest `setDragSuspended` value. */\n dragSuspended = false;\n /** Accumulated `tick` time, to prove the engine drives the clock. */\n tickedMs = 0;\n\n constructor(screenWidth = 800, screenHeight = 600) {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n }\n\n getTransform(): CameraTransformValue {\n return { ...this.t };\n }\n\n setTransform(t: CameraTransformValue): void {\n this.t = { ...t };\n }\n\n zoomToCentre(zoom: number): void {\n // Keep the world point at the screen centre fixed, which is what a backend's\n // own centre-anchored zoom does.\n const cx = this.screenWidth / 2;\n const cy = this.screenHeight / 2;\n const world = this.toWorld(cx, cy);\n this.t = { x: cx - world.x * zoom, y: cy - world.y * zoom, zoom };\n }\n\n resize(screenWidth: number, screenHeight: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n }\n\n toWorld(screenX: number, screenY: number): Point {\n return { x: (screenX - this.t.x) / this.t.zoom, y: (screenY - this.t.y) / this.t.zoom };\n }\n\n toScreen(worldX: number, worldY: number): Point {\n return { x: worldX * this.t.zoom + this.t.x, y: worldY * this.t.zoom + this.t.y };\n }\n\n getVisibleBounds(): Rect {\n const tl = this.toWorld(0, 0);\n const br = this.toWorld(this.screenWidth, this.screenHeight);\n return { x: tl.x, y: tl.y, width: br.x - tl.x, height: br.y - tl.y };\n }\n\n configureInput(config: CameraInputConfig): void {\n this.inputConfigs.push(config);\n }\n\n setDragSuspended(suspended: boolean): void {\n this.dragSuspended = suspended;\n }\n\n onTransformChange(fn: (kind: CameraChangeKind) => void): () => void {\n this.changeListeners.add(fn);\n return () => this.changeListeners.delete(fn);\n }\n\n onDragStart(fn: () => void): () => void {\n this.dragStartListeners.add(fn);\n return () => this.dragStartListeners.delete(fn);\n }\n\n tick(dtMs: number): void {\n this.tickedMs += dtMs;\n }\n\n // ─── Test-only drivers ───────────────────────────────────────────────────\n\n /** Simulate a backend-driven transform change (wheel, drag, momentum). */\n emitTransformChange(t: CameraTransformValue, kind: CameraChangeKind): void {\n this.t = { ...t };\n for (const fn of this.changeListeners) fn(kind);\n }\n\n /** Simulate the backend reporting the start of a drag-pan. */\n emitDragStart(): void {\n for (const fn of this.dragStartListeners) fn();\n }\n}\n","/**\n * `HeadlessRenderer` — a complete `IRenderer` that draws nothing.\n *\n * Not a product renderer: a **test double**, kept deliberately (§7) so layouts,\n * picking, bounds, spec projection and the whole layer / behaviour lifecycle can\n * be exercised with no GPU and no DOM. It is why `@invana/canvas` needs a\n * drawing library neither as a dependency nor a devDependency.\n *\n * It doubles as the reference for how small the contract really is: if a new\n * feature means adding a method here that cannot be implemented without pixels,\n * that method belongs on a concrete backend, not on `IRenderer`.\n *\n * ```ts\n * const canvas = new Canvas();\n * canvas.initWithRenderer(new HeadlessRenderer(), 800, 600);\n * ```\n */\n\nimport { EventEmitter } from '../state/events/EventEmitter';\nimport type { Camera } from '../abstracts/Camera';\nimport type { ICameraBinding } from '../contracts/ICameraBinding';\nimport type {\n IElementRenderer,\n LabelSizePolicy,\n LabelSizeTarget,\n ShapeDisplayOverride,\n} from '../contracts/IElementRenderer';\nimport type { IOverlayDevice } from '../contracts/IOverlayDevice';\nimport type {\n IRenderer,\n RendererCapabilities,\n} from '../contracts/IRenderer';\nimport type { ISurface, SurfaceBackdrop, SurfaceSpace } from '../contracts/ISurface';\nimport type { BaseShapeSpec, ElementEventMap } from '../specs';\nimport { boundsOfSpec } from '../specs';\nimport type { Rect } from '../specs/geom';\nimport { HeadlessCameraBinding } from './HeadlessCameraBinding';\n\n/** An `IOverlayDevice` that records nothing and draws nothing. */\nfunction noopOverlay(): IOverlayDevice {\n const self = {\n clear: () => self,\n moveTo: () => self,\n lineTo: () => self,\n quadraticCurveTo: () => self,\n closePath: () => self,\n rect: () => self,\n roundRect: () => self,\n ellipse: () => self,\n poly: () => self,\n fill: () => self,\n stroke: () => self,\n setVisible: () => self,\n setZIndex: () => self,\n setPosition: () => self,\n destroy: () => {},\n } as unknown as IOverlayDevice;\n return self;\n}\n\n/**\n * An `IElementRenderer` that tracks which ids exist and their specs, and\n * answers geometry from the spec alone. Enough for a layer test to assert that\n * elements were mounted, moved and removed.\n */\nexport class HeadlessElementRenderer implements IElementRenderer {\n readonly events = new EventEmitter<ElementEventMap>();\n readonly shapes = new Map<string, { kind: string; x: number; y: number }>();\n readonly connectors = new Set<string>();\n readonly shapeKinds = new Set<string>([\n 'circle', 'ellipse', 'rect', 'tabbed-rect', 'polygon',\n 'regular-polygon', 'star', 'arc', 'path', 'composite',\n ]);\n\n registerShape(kind: string): void {\n this.shapeKinds.add(kind);\n }\n\n getShapeKind(id: string): string | undefined {\n return this.shapes.get(id)?.kind;\n }\n hasShape(id: string): boolean {\n return this.shapes.has(id);\n }\n hasConnector(id: string): boolean {\n return this.connectors.has(id);\n }\n\n addShape(id: string, spec: { kind: string; x?: number; y?: number }): void {\n this.shapes.set(id, { kind: spec.kind, x: spec.x ?? 0, y: spec.y ?? 0 });\n }\n updateShape(id: string, patch: { x?: number; y?: number }): void {\n const cur = this.shapes.get(id);\n if (cur) this.shapes.set(id, { ...cur, ...patch });\n }\n removeShape(id: string): void {\n this.shapes.delete(id);\n }\n addConnector(id: string): void {\n this.connectors.add(id);\n }\n updateConnector(): void {}\n removeConnector(id: string): void {\n this.connectors.delete(id);\n }\n\n moveShape(id: string, x: number, y: number): void {\n const cur = this.shapes.get(id);\n if (cur) this.shapes.set(id, { ...cur, x, y });\n }\n getShapePosition(id: string): { x: number; y: number } | null {\n const s = this.shapes.get(id);\n return s ? { x: s.x, y: s.y } : null;\n }\n\n /**\n * Display overrides by shape id — recorded so a test can assert what a\n * behaviour asked to draw. Nothing is drawn, and positions stay logical.\n */\n readonly displayOverrides = new Map<string, ShapeDisplayOverride>();\n setShapeDisplayOverride(id: string, override: ShapeDisplayOverride | null): void {\n if (!this.shapes.has(id)) return;\n if (override === null) this.displayOverrides.delete(id);\n else this.displayOverrides.set(id, override);\n }\n clearShapeDisplayOverrides(): void {\n this.displayOverrides.clear();\n }\n\n /**\n * Ids whose text the LOD channel has hidden (`setShapeTextVisible` /\n * `setConnectorTextVisible` with `false`) — recorded so a behaviour test can\n * assert what a text LOD asked for.\n */\n readonly textHidden = new Set<string>();\n setShapeTextVisible(id: string, visible: boolean): void {\n if (visible) this.textHidden.delete(id);\n else this.textHidden.add(id);\n }\n setConnectorTextVisible(id: string, visible: boolean): void {\n if (visible) this.textHidden.delete(id);\n else this.textHidden.add(id);\n }\n isTextVisible(id: string): boolean {\n if (!this.shapes.has(id) && !this.connectors.has(id)) return false;\n return !this.textHidden.has(id);\n }\n\n /** The label-size policy last pushed per target — recorded for assertions. */\n readonly labelSizePolicies: Record<LabelSizeTarget, LabelSizePolicy | null> = {\n shape: null,\n connector: null,\n };\n setLabelSizePolicy(target: LabelSizeTarget, policy: LabelSizePolicy | null): void {\n this.labelSizePolicies[target] = policy;\n }\n\n // Everything below is a no-op or a null answer: these are the calls a layer\n // makes for pixels, and there are none here.\n scaleShape(): void {}\n setConnectorStroke(): void {}\n scaleConnectorStroke(): void {}\n setRaised(): void {}\n setShapeIconVisible(): void {}\n setShapeImageVisible(): void {}\n setLabelsResolution(): void {}\n setVisibleSet(): void {}\n cull(): void {}\n uncull(): void {}\n setDecoration(): void {}\n setEffect(): void {}\n getDecoration(): undefined {\n return undefined;\n }\n setDecorationVisible(): void {}\n getDecorationWorldBounds(): null {\n return null;\n }\n setBadge(): void {}\n removeBadge(): void {}\n getShapeWorldBounds(): null {\n return null;\n }\n getShapeCenter(): null {\n return null;\n }\n getConnectorPolyline(): null {\n return null;\n }\n connectorGeometryUnchanged(): boolean {\n return false;\n }\n /**\n * Pure geometry, answered for real: the kernel's spec-geometry covers every\n * built-in kind, so a headless canvas measures node footprints exactly like\n * a drawing backend would (`GraphLayer.boundsOfNode`, minimap estimates,\n * ELK size queries — and `getBounds()`'s store-derived fit box — all work\n * with no GPU). `undefined` only for unregistered third-party kinds.\n */\n boundsOfSpec(spec: { readonly kind: string }): Rect | undefined {\n return boundsOfSpec(spec as BaseShapeSpec);\n }\n scaleShapeSpec(): undefined {\n return undefined;\n }\n collapsedShapeSpec(): undefined {\n return undefined;\n }\n fitShapeSpecToContent(): undefined {\n return undefined;\n }\n measureLabel(): null {\n return null;\n }\n hitTest(): null {\n return null;\n }\n setHitTestEnabled(): void {}\n reindexScaledShapeHits(): void {}\n reanchorAllConnectors(): void {}\n reRouteAllConnectors(): void {}\n tickAnimations(): void {}\n toSVG(): string {\n return '';\n }\n destroy(): void {\n this.shapes.clear();\n this.connectors.clear();\n }\n}\n\nexport class HeadlessSurface implements ISurface {\n readonly primitives = new HeadlessElementRenderer();\n /** Last backdrop pushed — lets a background test assert without pixels. */\n backdrop: SurfaceBackdrop | null = null;\n visible = true;\n /** Last alpha pushed — lets an entrance test assert without pixels. */\n alpha = 1;\n zIndex = 0;\n destroyed = false;\n\n constructor(\n readonly id: string,\n readonly space: SurfaceSpace,\n ) {}\n\n overlay(): IOverlayDevice {\n return noopOverlay();\n }\n setBackdrop(backdrop: SurfaceBackdrop | null): void {\n this.backdrop = backdrop;\n }\n setVisible(visible: boolean): void {\n this.visible = visible;\n }\n setAlpha(alpha: number): void {\n this.alpha = alpha;\n }\n setZIndex(z: number): void {\n this.zIndex = z;\n }\n destroy(): void {\n this.destroyed = true;\n this.primitives.destroy();\n }\n}\n\nexport class HeadlessRenderer implements IRenderer {\n readonly backend = 'canvas' as const;\n readonly canvasElement: HTMLCanvasElement | null = null;\n /** Every surface handed out, by layer id — for asserting layer lifecycle. */\n readonly surfaces = new Map<string, HeadlessSurface>();\n readonly binding = new HeadlessCameraBinding();\n camera?: Camera;\n destroyed = false;\n /** Every `tick(dt)` the engine drove, in order. */\n readonly frames: number[] = [];\n\n get capabilities(): RendererCapabilities {\n return {\n effects: 'none',\n textMode: 'native',\n rasterExport: false,\n depth: false,\n specKinds: [],\n };\n }\n\n mount(): void {}\n\n createSurface(space: SurfaceSpace, id: string): ISurface {\n const s = new HeadlessSurface(id, space);\n this.surfaces.set(id, s);\n return s;\n }\n\n createOverlay(): IOverlayDevice {\n return noopOverlay();\n }\n\n createCameraBinding(): ICameraBinding {\n return this.binding;\n }\n\n attachCamera(camera: Camera): void {\n this.camera = camera;\n }\n\n worldContentBounds(): Rect | null {\n return null;\n }\n\n resize(): void {}\n\n /** Records the frames the engine drove, so a test can assert the clock ran. */\n tick(dtMs: number): void {\n this.frames.push(dtMs);\n }\n\n destroy(): void {\n this.destroyed = true;\n }\n}\n","import type { IAnchor } from '../../../../specs';\n\n/**\n * Default anchor — resolves a shape endpoint to the shape's bounding-box\n * **centre** in world space. Uses `ref.center` (computed by the renderer\n * from `origin + bounds`) rather than the raw `(spec.x, spec.y)` origin so\n * the anchor is uniform regardless of each shape's local-origin convention\n * (`RectShape` is anchored top-left; `CircleShape` is centred).\n *\n * Ignores `fromPoint`; the centre never depends on the other endpoint.\n */\nexport const centerAnchor: IAnchor = (endpoint, _fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`centerAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n return { x: ref.center.x, y: ref.center.y };\n};\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Boundary anchor — snaps the endpoint onto the shape silhouette where the\n * ray from the shape's geometric **centre** toward the *other* endpoint\n * exits.\n *\n * The ray is cast from `ref.center` (the bounding-box centre, computed by\n * the renderer from `origin + bounds`) rather than from `ref.origin` so the\n * behaviour is uniform regardless of each shape's local-origin convention.\n * `RectShape` is anchored top-left, `CircleShape` is centred — `ref.center`\n * normalises the difference.\n *\n * Calls the shape's optional `boundaryIntersect(localFromCenter)` for\n * analytical shapes (`CircleShape` overrides). For shapes that don't\n * override, falls back to a centred-AABB ray-exit (provided by\n * `ShapeBase.boundaryIntersect`). The input is centre-relative; the output\n * is centre-relative; this anchor converts back to world via `ref.center`.\n *\n * Sets an outward-pointing `tangent` on the returned endpoint (unit vector\n * from shape centre to the boundary point) so port-aware routers can use it\n * as an exit-direction hint.\n */\nexport const boundaryAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`boundaryAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n\n const localFromCenter: Point = {\n x: fromPoint.x - ref.center.x,\n y: fromPoint.y - ref.center.y,\n };\n\n const localPoint = ref.boundaryIntersect?.(localFromCenter)\n ?? { x: 0, y: 0 };\n\n const x = ref.center.x + localPoint.x;\n const y = ref.center.y + localPoint.y;\n\n const len = Math.hypot(localPoint.x, localPoint.y);\n const tangent = len === 0\n ? { x: 1, y: 0 }\n : { x: localPoint.x / len, y: localPoint.y / len };\n\n return { x, y, tangent };\n};\n","import type { IAnchor } from '../../../../specs';\n\n/**\n * Perpendicular anchor — exits at the **midpoint of the face** of the\n * shape's bounding box that is closest to the other endpoint. The face is\n * picked by comparing `|dx| / halfWidth` against `|dy| / halfHeight`: the\n * ratio that's larger wins (so a target slightly to the right of a wide,\n * short rect still picks the right side; a tall, narrow rect picks the top\n * or bottom more readily).\n *\n * Best for **orth-style routing** (`orth`, `manhattan`, `metro`, `er`,\n * `oneSide`) where the natural exit is along one cardinal axis. Produces\n * the \"lines start at the middle of a side\" look common in flowcharts and\n * ER diagrams.\n *\n * For circles (square bounds), this lands at the cardinal points\n * (N / S / E / W) on the perimeter — a useful default though `boundary`\n * still gives smoother diagonal exits for non-orthogonal routers.\n *\n * Sets the outward tangent to the face normal: `(±1, 0)` for left/right\n * faces, `(0, ±1)` for top/bottom. Routers like `orth` consume this to\n * pick H-first vs V-first.\n */\nexport const perpendicularAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`perpendicularAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n\n const dx = fromPoint.x - ref.center.x;\n const dy = fromPoint.y - ref.center.y;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Degenerate fallback when the two endpoints coincide.\n if (dx === 0 && dy === 0) {\n return {\n x: ref.center.x + halfW,\n y: ref.center.y,\n tangent: { x: 1, y: 0 },\n };\n }\n\n // Compare the ratio so the face choice scales with each axis's extent.\n const rx = halfW > 0 ? Math.abs(dx) / halfW : Infinity;\n const ry = halfH > 0 ? Math.abs(dy) / halfH : Infinity;\n\n if (rx >= ry) {\n // Left or right face.\n const sx = dx >= 0 ? halfW : -halfW;\n return {\n x: ref.center.x + sx,\n y: ref.center.y,\n tangent: { x: dx >= 0 ? 1 : -1, y: 0 },\n };\n }\n\n // Top or bottom face.\n const sy = dy >= 0 ? halfH : -halfH;\n return {\n x: ref.center.x,\n y: ref.center.y + sy,\n tangent: { x: 0, y: dy >= 0 ? 1 : -1 },\n };\n};\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Edge-port anchor — lands the endpoint on a named face of the host's\n * bounding box, displaced from that face's midpoint along the face axis by\n * `offset` world units.\n *\n * Use this when many connectors share a node but each needs to attach at a\n * specific position along one of its faces — the canonical case is a Sankey\n * diagram, where the ribbons stack vertically on the source's right face and\n * the target's left face. The layout owns the offsets (they map to the\n * cumulative link y-positions); the anchor just resolves them to world points\n * every time the connector re-routes. Generally useful for any port-attached\n * edge model — ER table rows, BPMN sequence flows, switch-statement diagrams.\n *\n * Opts:\n * - `side: 'left' | 'right' | 'top' | 'bottom' | 'auto'` — which face to\n * attach to. `'auto'` picks the face whose outward normal best aligns\n * with the vector from this shape's centre to the *other* endpoint\n * (`fromPoint`) — dominant-axis rule. Default `'auto'`.\n * - `offset: number` — displacement from the face midpoint along the face\n * axis (the axis parallel to the face). For `'left'` / `'right'` this is\n * a vertical offset (+ down); for `'top'` / `'bottom'` a horizontal offset\n * (+ right). Default `0` (face midpoint).\n *\n * The returned `tangent` is the outward face normal — `(±1, 0)` for left /\n * right, `(0, ±1)` for top / bottom — so routers that consume the tangent\n * (orth, er, …) keep working unchanged.\n *\n * Geometric only: no graph / node / port domain concepts in the\n * implementation. The \"port\" word in the registered name describes a generic\n * port-on-an-AABB-face primitive; any domain can compose it.\n */\n\ninterface EdgePortOpts {\n readonly side?: 'left' | 'right' | 'top' | 'bottom' | 'auto';\n readonly offset?: number;\n}\n\nexport const edgePortAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`edgePortAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n const opts = endpoint.opts as EdgePortOpts | undefined;\n const offset = opts?.offset ?? 0;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Default `side` is `'auto'` — pick the face pointing toward the other\n // endpoint. Callers that want a fixed face pass an explicit `side`.\n const requestedSide = opts?.side ?? 'auto';\n const side: 'left' | 'right' | 'top' | 'bottom' =\n requestedSide === 'auto' ? resolveAutoSide(fromPoint, ref.center) : requestedSide;\n\n switch (side) {\n case 'left':\n return {\n x: ref.center.x - halfW,\n y: ref.center.y + offset,\n tangent: { x: -1, y: 0 },\n };\n case 'right':\n return {\n x: ref.center.x + halfW,\n y: ref.center.y + offset,\n tangent: { x: 1, y: 0 },\n };\n case 'top':\n return {\n x: ref.center.x + offset,\n y: ref.center.y - halfH,\n tangent: { x: 0, y: -1 },\n };\n case 'bottom':\n return {\n x: ref.center.x + offset,\n y: ref.center.y + halfH,\n tangent: { x: 0, y: 1 },\n };\n }\n};\n\n/**\n * Pick the AABB face whose outward normal best aligns with the vector from\n * the host centre to `fromPoint` (the other endpoint). Dominant axis wins;\n * ties resolve to the horizontal face (`right` / `left`).\n */\nfunction resolveAutoSide(\n fromPoint: Point,\n center: Point,\n): 'left' | 'right' | 'top' | 'bottom' {\n const dx = fromPoint.x - center.x;\n const dy = fromPoint.y - center.y;\n if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left';\n return dy >= 0 ? 'bottom' : 'top';\n}\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Silhouette-port anchor — silhouette-aware sibling of {@link edgePortAnchor}.\n *\n * Same `{ side, offset }` opts as `edge-port`, but resolves the endpoint by\n * casting a ray from the shape's centre through the AABB's face point\n * `(±halfW, offset)` (or `(offset, ±halfH)` for top / bottom faces) and\n * intersecting it with the shape's actual silhouette via\n * `ref.boundaryIntersect`. The endpoint therefore lands on the rendered\n * outline — not on the AABB face — for every shape that overrides\n * `boundaryIntersect` (circle, polygon, …). Shapes without an override fall\n * through to the AABB face, matching `edge-port` exactly.\n *\n * Use this when fanning many connectors along one face of a non-rect node\n * (parallel graph edges between two circles, ER table → enum, etc.) — every\n * offset stays on the silhouette instead of floating off the AABB tangent\n * point. Large offsets that would exceed the face on a rect auto-wrap around\n * the corner to the top / bottom face instead of falling off the shape.\n *\n * Opts:\n * - `side: 'left' | 'right' | 'top' | 'bottom' | 'auto'` — which AABB face's\n * direction the offset is measured against. `'auto'` picks the face whose\n * outward normal best aligns with the vector from this shape's centre to\n * the *other* endpoint (`fromPoint`) — dominant-axis rule. Default\n * `'auto'`.\n * - `offset: number` — displacement from the face midpoint along the face\n * axis. For `'left'` / `'right'` this is a vertical offset (+ down); for\n * `'top'` / `'bottom'` a horizontal offset (+ right). Default `0`.\n *\n * The returned `tangent` is the outward radial unit vector from shape centre\n * to the silhouette point (matches `boundary`'s convention). For analytic\n * shapes this is the true surface normal; orth / er routers consume the\n * dominant axis component and remain happy.\n *\n * Geometric only: no graph / node / port domain concepts in the\n * implementation. Composable from any domain layer that already speaks the\n * `{ side, offset }` port vocabulary.\n */\n\ninterface SilhouettePortOpts {\n readonly side?: 'left' | 'right' | 'top' | 'bottom' | 'auto';\n readonly offset?: number;\n}\n\nexport const silhouettePortAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`silhouettePortAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n const opts = endpoint.opts as SilhouettePortOpts | undefined;\n const offset = opts?.offset ?? 0;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Default `side` is `'auto'` — pick the face pointing toward the other\n // endpoint. Callers that want a fixed face pass an explicit `side`.\n const requestedSide = opts?.side ?? 'auto';\n const side: 'left' | 'right' | 'top' | 'bottom' =\n requestedSide === 'auto' ? resolveAutoSide(fromPoint, ref.center) : requestedSide;\n\n // Centre-relative target the ray aims at. The ray runs from local origin\n // (= centre) through this point and intersects the silhouette en route.\n let localTarget: Point;\n switch (side) {\n case 'left': localTarget = { x: -halfW, y: offset }; break;\n case 'right': localTarget = { x: halfW, y: offset }; break;\n case 'top': localTarget = { x: offset, y: -halfH }; break;\n case 'bottom': localTarget = { x: offset, y: halfH }; break;\n }\n\n // Analytical shapes (circle / polygon) override `boundaryIntersect` and\n // return the exact silhouette exit. Shapes without an override fall back\n // to the AABB target — same behaviour as `edge-port` for that case.\n const exit = ref.boundaryIntersect?.(localTarget) ?? localTarget;\n\n const x = ref.center.x + exit.x;\n const y = ref.center.y + exit.y;\n const len = Math.hypot(exit.x, exit.y);\n const tangent = len === 0\n ? { x: 1, y: 0 }\n : { x: exit.x / len, y: exit.y / len };\n\n return { x, y, tangent };\n};\n\n/**\n * Pick the AABB face whose outward normal best aligns with the vector from\n * the host centre to `fromPoint` (the other endpoint). Dominant axis wins;\n * ties resolve to the horizontal face (`right` / `left`).\n */\nfunction resolveAutoSide(\n fromPoint: Point,\n center: Point,\n): 'left' | 'right' | 'top' | 'bottom' {\n const dx = fromPoint.x - center.x;\n const dy = fromPoint.y - center.y;\n if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left';\n return dy >= 0 ? 'bottom' : 'top';\n}\n","import type { IRouter } from '../../../../specs';\n\n/**\n * Direct line from source through any waypoints to target.\n * Output: `[source, ...waypoints, target]` — a flat polyline.\n *\n * Routers decide topology (where bends sit). The visual style of segments\n * between these points is owned by the downstream `PathStyle`:\n * - `normal` → straight segments (`M, L, L, …`)\n * - `rounded` → quadratic fillets at corners\n * - `smooth` → Catmull-Rom cubic spline\n * - `bezier` → single cubic A→B (intermediate points ignored)\n */\nexport const straightRouter: IRouter = (source, target, waypoints) => {\n if (!waypoints || waypoints.length === 0) {\n return [\n { x: source.x, y: source.y },\n { x: target.x, y: target.y },\n ];\n }\n return [\n { x: source.x, y: source.y },\n ...waypoints.map((p) => ({ x: p.x, y: p.y })),\n { x: target.x, y: target.y },\n ];\n};\n","import type { Endpoint, IRouter, Point } from '../../../../specs';\n\n/**\n * Orth router — produces a polyline made of horizontal and vertical\n * segments only. Simple, geometric, **no obstacle awareness**: pick this\n * for clean H/V routing in layouts you trust to have no shapes in the way.\n * For obstacle avoidance, use `manhattan` (which is built on top of A*).\n *\n * Naming follows X6 / JointJS / mxGraph: their `Orth` is also the simple\n * H/V router, while their `Manhattan` is the obstacle-aware variant.\n *\n * For each consecutive pair `(P, Q)` of `[source, ...waypoints, target]`,\n * one bend point is inserted (producing an L-shape for that pair). The bend\n * direction (H-first vs V-first) is chosen by:\n *\n * 1. **Source tangent** on the first segment — the line exits along the\n * tangent's dominant axis. The boundary anchor sets this as an outward\n * normal hint.\n * 2. **Target tangent** on the last segment — the line approaches matching\n * the tangent's dominant axis (so the final leg is perpendicular to the\n * target boundary).\n * 3. **Alternation** in between — alternate H ↔ V across consecutive\n * segments to avoid back-tracking.\n * 4. **Dominant axis** as a final fallback when no other signal applies.\n *\n * Aligned consecutive points (same x or same y) emit no bend.\n */\nexport const orthRouter: IRouter = (source, target, waypoints) => {\n const hasWaypoints = waypoints !== undefined && waypoints.length > 0;\n\n // Special case: no waypoints, both endpoints provide tangents that agree\n // on axis. A single L-bend can't satisfy both tangents (one leg would\n // exit along the wrong axis), so emit a Z-bend with two corners. Examples:\n // - both horizontal tangents → out H, V at midX, in H\n // - both vertical tangents → out V, H at midY, in V\n if (!hasWaypoints && source.tangent && target.tangent && source.x !== target.x && source.y !== target.y) {\n const srcH = Math.abs(source.tangent.x) > Math.abs(source.tangent.y);\n const tgtH = Math.abs(target.tangent.x) > Math.abs(target.tangent.y);\n if (srcH && tgtH) {\n const midX = (source.x + target.x) / 2;\n return [\n { x: source.x, y: source.y },\n { x: midX, y: source.y },\n { x: midX, y: target.y },\n { x: target.x, y: target.y },\n ];\n }\n if (!srcH && !tgtH) {\n const midY = (source.y + target.y) / 2;\n return [\n { x: source.x, y: source.y },\n { x: source.x, y: midY },\n { x: target.x, y: midY },\n { x: target.x, y: target.y },\n ];\n }\n // Mismatched axes (one H, one V) — a single L-bend already satisfies both\n // tangents naturally, so fall through to the standard logic below.\n }\n\n const points: ReadonlyArray<Endpoint | Point> = hasWaypoints\n ? [source, ...waypoints, target]\n : [source, target];\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n let prevDir: 'H' | 'V' | null = null;\n\n for (let i = 0; i < points.length - 1; i++) {\n const P = points[i]!;\n const Q = points[i + 1]!;\n const isFirst = i === 0;\n const isLast = i === points.length - 2;\n\n if (P.x === Q.x) {\n out.push({ x: Q.x, y: Q.y });\n prevDir = 'V';\n continue;\n }\n if (P.y === Q.y) {\n out.push({ x: Q.x, y: Q.y });\n prevDir = 'H';\n continue;\n }\n\n const goHFirst = pickHFirst({\n source: isFirst ? source : null,\n target: isLast ? target : null,\n prevDir,\n P, Q,\n });\n\n const bend: Point = goHFirst\n ? { x: Q.x, y: P.y }\n : { x: P.x, y: Q.y };\n\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n prevDir = goHFirst ? 'V' : 'H';\n }\n\n return out;\n};\n\ninterface PickArgs {\n readonly source: Endpoint | null;\n readonly target: Endpoint | null;\n readonly prevDir: 'H' | 'V' | null;\n readonly P: Endpoint | Point;\n readonly Q: Endpoint | Point;\n}\n\nfunction pickHFirst({ source, target, prevDir, P, Q }: PickArgs): boolean {\n if (source?.tangent) {\n return Math.abs(source.tangent.x) >= Math.abs(source.tangent.y);\n }\n if (target?.tangent) {\n // Last leg should align with the target's tangent axis. If target tangent\n // is vertical, last leg is V → first leg of this segment is H.\n return Math.abs(target.tangent.y) >= Math.abs(target.tangent.x);\n }\n if (prevDir === 'H') return false;\n if (prevDir === 'V') return true;\n return Math.abs(Q.x - P.x) >= Math.abs(Q.y - P.y);\n}\n","/**\n * Coarse-grid construction for obstacle-aware routing. Used internally by\n * `manhattan`, `metro`, `er`, and `oneSide` routers when `RouterCtx.obstacles`\n * is non-empty. Pure data structure — no pixi, no router, no scene access.\n */\n\nimport type { Obstacle, Point } from '../../../../specs';\n\nexport interface ObstacleGrid {\n /** Cell count along x. */\n readonly width: number;\n /** Cell count along y. */\n readonly height: number;\n /** World-space x of cell `(0, _)` centre. */\n readonly originX: number;\n /** World-space y of cell `(_, 0)` centre. */\n readonly originY: number;\n /** Edge length of each cell in world units. */\n readonly cellSize: number;\n /** Length = `width * height`; `1` = blocked, `0` = free. */\n readonly cells: Uint8Array;\n}\n\nexport interface BuildGridOpts {\n readonly source: Point;\n readonly target: Point;\n readonly obstacles: ReadonlyArray<Obstacle>;\n /** Cell edge length in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region of source / target / obstacles. Default `64`. */\n readonly margin?: number;\n /** Per-obstacle inflation in world units (so the path doesn't graze edges). Default `4`. */\n readonly inflate?: number;\n /** Hard cap on `width * height`. Default `40_000` (200×200). Returns `null` on overflow. */\n readonly maxCells?: number;\n}\n\nconst DEFAULT_GRID_STEP = 16;\nconst DEFAULT_MARGIN = 64;\nconst DEFAULT_INFLATE = 4;\nconst DEFAULT_MAX_CELLS = 40_000;\n\n/**\n * Build a grid covering the **neighbourhood of this edge** — the bounding box\n * of `source` / `target` (padded by `margin`), expanded to fully contain any\n * obstacle that intersects that box. Obstacles elsewhere in the scene are\n * ignored: a whole-graph grid would need millions of cells for a single edge\n * (blowing `maxCells`), so avoidance would never run on a large diagram. The\n * edge can only route through its own neighbourhood anyway, so bounding the\n * grid there keeps it small without losing the obstacles that actually matter.\n *\n * Each obstacle is inflated by `inflate` and any cell whose centre lies inside\n * an inflated rect is marked blocked. The cell size adapts upward (never below\n * `gridStep`) so the grid always fits `maxCells` — long spans route coarsely\n * but still avoid, rather than bailing to a straight line through nodes.\n *\n * Returns `null` only for a degenerate `gridStep <= 0`.\n */\nexport function buildObstacleGrid(opts: BuildGridOpts): ObstacleGrid | null {\n const requestedStep = opts.gridStep ?? DEFAULT_GRID_STEP;\n const margin = opts.margin ?? DEFAULT_MARGIN;\n const inflate = opts.inflate ?? DEFAULT_INFLATE;\n const maxCells = opts.maxCells ?? DEFAULT_MAX_CELLS;\n\n if (requestedStep <= 0) return null;\n\n // Seed region: just the source / target span + margin.\n const seedMinX = Math.min(opts.source.x, opts.target.x) - margin;\n const seedMaxX = Math.max(opts.source.x, opts.target.x) + margin;\n const seedMinY = Math.min(opts.source.y, opts.target.y) - margin;\n const seedMaxY = Math.max(opts.source.y, opts.target.y) + margin;\n\n // Expand to fully contain obstacles that intersect the seed region, so a\n // node straddling the boundary is marked in full. Test against the *seed*\n // bounds (not the growing region) so the result is order-independent and the\n // region stays the edge's locality rather than chaining out to the whole graph.\n let minX = seedMinX;\n let maxX = seedMaxX;\n let minY = seedMinY;\n let maxY = seedMaxY;\n for (const r of opts.obstacles) {\n const r1x = r.x + r.width;\n const r1y = r.y + r.height;\n if (r.x > seedMaxX || r1x < seedMinX || r.y > seedMaxY || r1y < seedMinY) continue;\n if (r.x < minX) minX = r.x;\n if (r.y < minY) minY = r.y;\n if (r1x > maxX) maxX = r1x;\n if (r1y > maxY) maxY = r1y;\n }\n\n // Adaptive cell size: coarsen so `width * height <= maxCells` instead of\n // returning null (which would fall back to a node-crossing straight line).\n const spanX = maxX - minX;\n const spanY = maxY - minY;\n const fitStep = Math.sqrt((Math.max(spanX, 1) * Math.max(spanY, 1)) / maxCells);\n const gridStep = fitStep > requestedStep ? fitStep : requestedStep;\n\n const width = Math.max(1, Math.ceil(spanX / gridStep));\n const height = Math.max(1, Math.ceil(spanY / gridStep));\n\n const cells = new Uint8Array(width * height);\n\n const originX = minX + gridStep / 2;\n const originY = minY + gridStep / 2;\n\n for (const r of opts.obstacles) {\n const ix0 = r.x - inflate;\n const iy0 = r.y - inflate;\n const ix1 = r.x + r.width + inflate;\n const iy1 = r.y + r.height + inflate;\n const cMinX = Math.max(0, Math.floor((ix0 - originX) / gridStep));\n const cMaxX = Math.min(width - 1, Math.ceil((ix1 - originX) / gridStep));\n const cMinY = Math.max(0, Math.floor((iy0 - originY) / gridStep));\n const cMaxY = Math.min(height - 1, Math.ceil((iy1 - originY) / gridStep));\n const silhouette = r.containsInflated;\n for (let cy = cMinY; cy <= cMaxY; cy++) {\n for (let cx = cMinX; cx <= cMaxX; cx++) {\n const wx = originX + cx * gridStep;\n const wy = originY + cy * gridStep;\n // Cheap AABB pre-filter — skips cells well outside the obstacle's\n // bounding box. Required because the cell range above is rounded\n // up/down by `Math.floor` / `Math.ceil`.\n if (wx < ix0 || wx > ix1 || wy < iy0 || wy > iy1) continue;\n // Silhouette test when provided — tightens the marking from the\n // bounding box to the actual shape (circle disc, polygon outline, …).\n // When absent, the inflated AABB IS the obstacle.\n if (silhouette && !silhouette(wx, wy, inflate)) continue;\n cells[cy * width + cx] = 1;\n }\n }\n }\n\n return { width, height, originX, originY, cellSize: gridStep, cells };\n}\n\n/** Round-to-nearest cell containing the world-space point. */\nexport function worldToCell(grid: ObstacleGrid, p: Point): { cx: number; cy: number } {\n return {\n cx: Math.round((p.x - grid.originX) / grid.cellSize),\n cy: Math.round((p.y - grid.originY) / grid.cellSize),\n };\n}\n\n/** World-space centre of cell `(cx, cy)`. */\nexport function cellToWorld(grid: ObstacleGrid, cx: number, cy: number): Point {\n return {\n x: grid.originX + cx * grid.cellSize,\n y: grid.originY + cy * grid.cellSize,\n };\n}\n\n/** True when `(cx, cy)` is inside the grid and not blocked. */\nexport function isFreeCell(grid: ObstacleGrid, cx: number, cy: number): boolean {\n if (cx < 0 || cy < 0 || cx >= grid.width || cy >= grid.height) return false;\n return grid.cells[cy * grid.width + cx] === 0;\n}\n","/**\n * A* search on an `ObstacleGrid` plus path simplification. Used internally\n * by obstacle-aware routers (`manhattan`, `metro`, `er`, `oneSide`).\n *\n * The search works in cell coordinates; converting back to world points is\n * the caller's job (`cellToWorld` from `_obstacleGrid`).\n */\n\nimport type { ObstacleGrid } from './_obstacleGrid';\nimport { isFreeCell } from './_obstacleGrid';\n\nexport interface Cell {\n readonly cx: number;\n readonly cy: number;\n}\n\nexport type Connectivity = 4 | 8;\n\ninterface AStarOpts {\n readonly connectivity: Connectivity;\n}\n\nconst SQRT2 = Math.SQRT2;\n\nconst DIRS_4: ReadonlyArray<readonly [number, number, number]> = [\n [1, 0, 1],\n [-1, 0, 1],\n [0, 1, 1],\n [0, -1, 1],\n];\n\nconst DIRS_8: ReadonlyArray<readonly [number, number, number]> = [\n [1, 0, 1],\n [-1, 0, 1],\n [0, 1, 1],\n [0, -1, 1],\n [1, 1, SQRT2],\n [1, -1, SQRT2],\n [-1, 1, SQRT2],\n [-1, -1, SQRT2],\n];\n\n/**\n * A* from `start` to `goal` on `grid`. Returns the cell path (inclusive of\n * start and goal) or `null` if unreachable.\n *\n * Connectivity:\n * - `4` — H/V neighbours only. Manhattan-distance heuristic.\n * - `8` — H/V/diagonal neighbours. Octile-distance heuristic. Diagonal cost\n * is `√2`. Diagonal moves through a corner where one of the two flanking\n * cells is blocked are forbidden (\"no corner cutting\").\n *\n * Blocked start/goal cells are snapped to the nearest free cell within an\n * 8-cell radius — useful when the literal endpoint sits inside an inflated\n * obstacle (commonly the source/target shape itself, when the renderer\n * forgot to exclude it). Returns `null` if no free cell is found.\n */\nexport function aStar(\n grid: ObstacleGrid,\n start: Cell,\n goal: Cell,\n opts: AStarOpts,\n): Cell[] | null {\n const startSnapped = snapToFree(grid, start);\n const goalSnapped = snapToFree(grid, goal);\n if (!startSnapped || !goalSnapped) return null;\n\n const w = grid.width;\n const startIdx = startSnapped.cy * w + startSnapped.cx;\n const goalIdx = goalSnapped.cy * w + goalSnapped.cx;\n if (startIdx === goalIdx) return [startSnapped];\n\n const dirs = opts.connectivity === 4 ? DIRS_4 : DIRS_8;\n const heuristic = opts.connectivity === 4 ? manhattanH : octileH;\n\n const gScore = new Map<number, number>();\n const cameFrom = new Map<number, number>();\n const closed = new Set<number>();\n gScore.set(startIdx, 0);\n\n const open = new MinHeap();\n open.push(startIdx, heuristic(startSnapped, goalSnapped));\n\n while (open.size > 0) {\n const cur = open.pop()!;\n if (closed.has(cur)) continue;\n closed.add(cur);\n\n if (cur === goalIdx) return reconstruct(cameFrom, cur, w);\n\n const cx = cur % w;\n const cy = Math.floor(cur / w);\n const curG = gScore.get(cur)!;\n\n for (const [dx, dy, cost] of dirs) {\n const ncx = cx + dx;\n const ncy = cy + dy;\n if (!isFreeCell(grid, ncx, ncy)) continue;\n // No-corner-cutting on diagonal moves.\n if (dx !== 0 && dy !== 0) {\n if (!isFreeCell(grid, cx + dx, cy)) continue;\n if (!isFreeCell(grid, cx, cy + dy)) continue;\n }\n const nIdx = ncy * w + ncx;\n if (closed.has(nIdx)) continue;\n const tentativeG = curG + cost;\n const prevG = gScore.get(nIdx) ?? Infinity;\n if (tentativeG < prevG) {\n gScore.set(nIdx, tentativeG);\n cameFrom.set(nIdx, cur);\n const f = tentativeG + heuristic({ cx: ncx, cy: ncy }, goalSnapped);\n open.push(nIdx, f);\n }\n }\n }\n return null;\n}\n\n/**\n * Drop interior cells whose direction-in equals direction-out — the result\n * is a polyline of bend points only. Works for both 4- and 8-connectivity\n * (the direction signature is `(dx, dy)` so diagonal runs collapse the\n * same way as cardinal ones).\n */\nexport function simplifyCellPath(cells: ReadonlyArray<Cell>): Cell[] {\n if (cells.length <= 2) return cells.slice();\n const out: Cell[] = [cells[0]!];\n for (let i = 1; i < cells.length - 1; i++) {\n const prev = cells[i - 1]!;\n const cur = cells[i]!;\n const next = cells[i + 1]!;\n const dx1 = sign(cur.cx - prev.cx);\n const dy1 = sign(cur.cy - prev.cy);\n const dx2 = sign(next.cx - cur.cx);\n const dy2 = sign(next.cy - cur.cy);\n if (dx1 !== dx2 || dy1 !== dy2) out.push(cur);\n }\n out.push(cells[cells.length - 1]!);\n return out;\n}\n\nfunction sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\nfunction manhattanH(a: Cell, b: Cell): number {\n return Math.abs(a.cx - b.cx) + Math.abs(a.cy - b.cy);\n}\n\nfunction octileH(a: Cell, b: Cell): number {\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n return dx + dy + (SQRT2 - 2) * Math.min(dx, dy);\n}\n\nfunction snapToFree(grid: ObstacleGrid, c: Cell): Cell | null {\n if (isFreeCell(grid, c.cx, c.cy)) return c;\n for (let r = 1; r <= 8; r++) {\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n if (Math.abs(dx) !== r && Math.abs(dy) !== r) continue;\n if (isFreeCell(grid, c.cx + dx, c.cy + dy)) {\n return { cx: c.cx + dx, cy: c.cy + dy };\n }\n }\n }\n }\n return null;\n}\n\nfunction reconstruct(cameFrom: Map<number, number>, end: number, w: number): Cell[] {\n const out: Cell[] = [];\n let cur: number | undefined = end;\n while (cur !== undefined) {\n out.push({ cx: cur % w, cy: Math.floor(cur / w) });\n cur = cameFrom.get(cur);\n }\n return out.reverse();\n}\n\n/**\n * Minimal binary min-heap. Two parallel arrays — priorities and values —\n * keyed by the same index. Stable ordering is not required; A* tolerates\n * stale entries via the `closed` set in the search loop.\n */\nclass MinHeap {\n private p: number[] = [];\n private v: number[] = [];\n\n get size(): number {\n return this.p.length;\n }\n\n push(value: number, priority: number): void {\n this.p.push(priority);\n this.v.push(value);\n this.bubbleUp(this.p.length - 1);\n }\n\n pop(): number | undefined {\n if (this.p.length === 0) return undefined;\n const top = this.v[0]!;\n const lastP = this.p.pop()!;\n const lastV = this.v.pop()!;\n if (this.p.length > 0) {\n this.p[0] = lastP;\n this.v[0] = lastV;\n this.bubbleDown(0);\n }\n return top;\n }\n\n private bubbleUp(i: number): void {\n while (i > 0) {\n const parent = (i - 1) >> 1;\n if (this.p[i]! < this.p[parent]!) {\n this.swap(i, parent);\n i = parent;\n } else break;\n }\n }\n\n private bubbleDown(i: number): void {\n const n = this.p.length;\n while (true) {\n const left = i * 2 + 1;\n const right = i * 2 + 2;\n let smallest = i;\n if (left < n && this.p[left]! < this.p[smallest]!) smallest = left;\n if (right < n && this.p[right]! < this.p[smallest]!) smallest = right;\n if (smallest === i) break;\n this.swap(i, smallest);\n i = smallest;\n }\n }\n\n private swap(a: number, b: number): void {\n const pa = this.p[a]!;\n const va = this.v[a]!;\n this.p[a] = this.p[b]!;\n this.v[a] = this.v[b]!;\n this.p[b] = pa;\n this.v[b] = va;\n }\n}\n","import type { IRouter, Obstacle, Point } from '../../../../specs';\nimport { orthRouter } from './orth';\nimport { aStar, simplifyCellPath } from './_aStar';\nimport {\n buildObstacleGrid,\n cellToWorld,\n worldToCell,\n} from './_obstacleGrid';\n\ninterface ManhattanOpts {\n /** Grid cell size in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region. Default `64`. */\n readonly margin?: number;\n /** Obstacle inflation in world units. Default `4`. */\n readonly inflate?: number;\n /** Hard cap on grid cells (width × height). Default `40_000`. */\n readonly maxCells?: number;\n /**\n * Length of the perpendicular stub off each tangent-bearing endpoint when\n * A* takes over. Guarantees the line exits/enters the shape along its\n * tangent before A* bends it around obstacles — feels \"natural\" like ER\n * routing. Default `24` world units. Set to `0` to disable stubs (line\n * will exit/enter wherever A* decides).\n */\n readonly stubLength?: number;\n}\n\nconst DEFAULT_INFLATE = 4;\nconst DEFAULT_STUB_LENGTH = 24;\n\n/**\n * Manhattan router — H/V segments only, **routing around obstacles when\n * necessary**.\n *\n * Naming follows X6 / JointJS / mxGraph where `Manhattan` is the\n * obstacle-aware variant and `Orth` is the simple non-avoiding one.\n *\n * Pipeline (lazy A*):\n * 1. Compute the simple `orthRouter` polyline first (single L-bend or\n * tangent-aware Z-bend).\n * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline\n * crosses an inflated obstacle, return it directly. Same output as the\n * `orth` router — clean, no stair-stepping.\n * 3. Otherwise build a coarse `ObstacleGrid` and run A* (connectivity 4)\n * from source cell to target cell. Simplify the cell path to bend\n * points only and convert back to world coordinates.\n *\n * Failure cases all fall back to the simple `orthRouter` polyline:\n * - Grid construction returns `null` (cell-count cap exceeded).\n * - A* finds no path (source/target unreachable through inflated obstacles).\n *\n * The fallback emits a `console.warn` so the dev sees why avoidance didn't\n * kick in; toggle `routerOpts.obstacles: 'none'` to skip the obstacle check\n * entirely.\n *\n * Waypoints are not yet threaded through A* — when present, the simple orth\n * polyline (which respects waypoints) is checked against obstacles. If it's\n * clear, return it; if not, A* runs between source and target only.\n * Routing through waypoints with obstacle awareness is a future extension.\n */\nexport const manhattanRouter: IRouter = (source, target, waypoints, opts, ctx) => {\n const obstacles = ctx?.obstacles ?? [];\n const simple = orthRouter(source, target, waypoints, opts, ctx);\n\n if (obstacles.length === 0) return simple;\n\n const o = opts as ManhattanOpts | undefined;\n const inflate = o?.inflate ?? DEFAULT_INFLATE;\n\n if (!polylineCrossesObstacles(simple, obstacles, inflate)) {\n return simple;\n }\n\n const stubLength = o?.stubLength ?? DEFAULT_STUB_LENGTH;\n\n // Stub endpoints: when an endpoint provides a tangent (from the\n // perpendicular / boundary anchor), project the actual A* start/goal one\n // `stubLength` away along the tangent. This guarantees the visible line\n // exits the source / enters the target along the tangent direction — A*\n // never sees the literal endpoints, so it can't accidentally pick a\n // first/last move along the \"wrong\" axis.\n const sourceStub: Point = source.tangent && stubLength > 0\n ? { x: source.x + source.tangent.x * stubLength, y: source.y + source.tangent.y * stubLength }\n : { x: source.x, y: source.y };\n const targetStub: Point = target.tangent && stubLength > 0\n ? { x: target.x + target.tangent.x * stubLength, y: target.y + target.tangent.y * stubLength }\n : { x: target.x, y: target.y };\n\n const grid = buildObstacleGrid({\n source: sourceStub,\n target: targetStub,\n obstacles,\n gridStep: o?.gridStep,\n margin: o?.margin,\n inflate: o?.inflate,\n maxCells: o?.maxCells,\n });\n if (!grid) {\n if (typeof console !== 'undefined') {\n console.warn('manhattanRouter: obstacle grid exceeded maxCells; falling back to orth.');\n }\n return simple;\n }\n\n const startCell = worldToCell(grid, sourceStub);\n const goalCell = worldToCell(grid, targetStub);\n const cells = aStar(grid, startCell, goalCell, { connectivity: 4 });\n if (!cells) {\n if (typeof console !== 'undefined') {\n console.warn('manhattanRouter: A* found no path through obstacles; falling back to orth.');\n }\n return simple;\n }\n\n const simplified = simplifyCellPath(cells);\n\n // A* cell path between the stub points → world points.\n const middle: Point[] = [{ x: sourceStub.x, y: sourceStub.y }];\n for (let i = 1; i < simplified.length - 1; i++) {\n const c = simplified[i]!;\n middle.push(cellToWorld(grid, c.cx, c.cy));\n }\n middle.push({ x: targetStub.x, y: targetStub.y });\n\n // Greedy L-bend simplification ONLY across the stub-to-stub portion. The\n // source/target stub legs are preserved as the perpendicular exit/entry.\n const simplifiedMiddle = simplifyOrthPolylineAroundObstacles(middle, obstacles, inflate);\n\n // Prepend the literal source / append the literal target. The stub legs\n // (source → sourceStub and targetStub → target) emerge automatically\n // because `simplifiedMiddle` starts at `sourceStub` and ends at\n // `targetStub`. When an endpoint has no tangent, its stub equals the\n // endpoint itself; the dedup below collapses the zero-length segment.\n const out: Point[] = [{ x: source.x, y: source.y }];\n for (const p of simplifiedMiddle) {\n const last = out[out.length - 1]!;\n if (p.x === last.x && p.y === last.y) continue;\n out.push(p);\n }\n const tEnd = { x: target.x, y: target.y };\n const lastOut = out[out.length - 1]!;\n if (lastOut.x !== tEnd.x || lastOut.y !== tEnd.y) out.push(tEnd);\n return out;\n};\n\n/**\n * Returns `true` if any axis-aligned segment of `polyline` crosses any\n * inflated `obstacle` rect. Designed for orth output (H/V segments only);\n * diagonal segments fall through as non-crossing.\n */\nfunction polylineCrossesObstacles(\n polyline: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (let i = 0; i < polyline.length - 1; i++) {\n const a = polyline[i]!;\n const b = polyline[i + 1]!;\n for (const r of obstacles) {\n if (segmentCrossesRect(a, b, r, inflate)) return true;\n }\n }\n return false;\n}\n\nfunction segmentCrossesRect(a: Point, b: Point, r: Obstacle, inflate: number): boolean {\n const x0 = r.x - inflate;\n const y0 = r.y - inflate;\n const x1 = r.x + r.width + inflate;\n const y1 = r.y + r.height + inflate;\n\n // AABB pre-filter: if the segment misses the inflated bounding box, no\n // need to consult the silhouette.\n if (a.y === b.y) {\n if (a.y < y0 || a.y > y1) return false;\n const segMinX = a.x < b.x ? a.x : b.x;\n const segMaxX = a.x < b.x ? b.x : a.x;\n if (segMaxX < x0 || segMinX > x1) return false;\n // Inside AABB — silhouette refinement for non-rect obstacles.\n return segmentHitsSilhouette(a, b, r, inflate);\n }\n if (a.x === b.x) {\n if (a.x < x0 || a.x > x1) return false;\n const segMinY = a.y < b.y ? a.y : b.y;\n const segMaxY = a.y < b.y ? b.y : a.y;\n if (segMaxY < y0 || segMinY > y1) return false;\n return segmentHitsSilhouette(a, b, r, inflate);\n }\n // Diagonal segments (shouldn't appear in orth output) — be permissive\n // and let A* take over by reporting \"blocked\".\n return true;\n}\n\n/**\n * Walks an axis-aligned segment that already passed the AABB pre-filter and\n * tests sample points against the obstacle's `containsInflated` silhouette.\n * When the obstacle has no silhouette, the segment is considered blocked\n * (AABB IS the obstacle). Sample density is `~inflate / 2`, capped to a\n * reasonable max.\n */\nfunction segmentHitsSilhouette(\n a: Point,\n b: Point,\n obstacle: Obstacle,\n inflate: number,\n): boolean {\n const test = obstacle.containsInflated;\n if (!test) return true;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.abs(dx) + Math.abs(dy); // axis-aligned, so Manhattan = Euclidean\n const step = Math.max(inflate / 2, 2);\n const samples = Math.min(64, Math.max(2, Math.ceil(len / step)));\n for (let i = 0; i <= samples; i++) {\n const t = i / samples;\n const wx = a.x + dx * t;\n const wy = a.y + dy * t;\n if (test(wx, wy, inflate)) return true;\n }\n return false;\n}\n\n/**\n * Greedy L-bend reduction of an orthogonal polyline. Walks the points\n * forward; at each step looks as far ahead as possible while the connection\n * from the current point to that look-ahead point can still be made with\n * **at most one bend** that doesn't cross any obstacle. Replaces the\n * skipped intermediate points with that single bend (or no bend, when the\n * two points are already axis-aligned).\n *\n * The result preserves both endpoints exactly and stays obstacle-free; it\n * reduces a stair-stepped A* output to the minimum-bend orthogonal path\n * around the obstacle. Worst case is O(n²) in polyline length but n is\n * typically the bend count (≤ 10 for sensible diagrams), so this is cheap.\n */\nfunction simplifyOrthPolylineAroundObstacles(\n points: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): Point[] {\n if (points.length <= 2) return points.slice();\n\n const out: Point[] = [points[0]!];\n let i = 0;\n\n while (i < points.length - 1) {\n let bestJ = i + 1;\n let bestBend: Point | null = null;\n\n for (let j = i + 2; j < points.length; j++) {\n const conn = findClearOrthConnection(points[i]!, points[j]!, obstacles, inflate);\n if (conn === undefined) break;\n bestJ = j;\n bestBend = conn;\n }\n\n if (bestBend !== null) {\n const last = out[out.length - 1]!;\n if (bestBend.x !== last.x || bestBend.y !== last.y) out.push(bestBend);\n }\n out.push(points[bestJ]!);\n i = bestJ;\n }\n\n return out;\n}\n\n/**\n * Returns:\n * - `null` — `a` and `b` are axis-aligned and the straight segment is clear (no bend needed)\n * - `Point` — a clear L-bend (the bend point) connects `a` and `b`\n * - `undefined` — neither a straight nor an L-bend can connect `a` and `b` without crossing an obstacle\n */\nfunction findClearOrthConnection(\n a: Point,\n b: Point,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): Point | null | undefined {\n if (a.x === b.x || a.y === b.y) {\n return segmentCrosses(a, b, obstacles, inflate) ? undefined : null;\n }\n const bendH: Point = { x: b.x, y: a.y };\n const hClear =\n !segmentCrosses(a, bendH, obstacles, inflate) &&\n !segmentCrosses(bendH, b, obstacles, inflate);\n if (hClear) return bendH;\n\n const bendV: Point = { x: a.x, y: b.y };\n const vClear =\n !segmentCrosses(a, bendV, obstacles, inflate) &&\n !segmentCrosses(bendV, b, obstacles, inflate);\n if (vClear) return bendV;\n\n return undefined;\n}\n\nfunction segmentCrosses(\n a: Point,\n b: Point,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (const r of obstacles) {\n if (segmentCrossesRect(a, b, r, inflate)) return true;\n }\n return false;\n}\n","import type { Endpoint, IRouter, Obstacle, Point } from '../../../../specs';\nimport { aStar, simplifyCellPath } from './_aStar';\nimport { buildObstacleGrid, cellToWorld, worldToCell } from './_obstacleGrid';\n\ninterface MetroOpts {\n /** Grid cell size in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region. Default `64`. */\n readonly margin?: number;\n /** Obstacle inflation in world units. Default `4`. */\n readonly inflate?: number;\n /** Hard cap on grid cells (width × height). Default `40_000`. */\n readonly maxCells?: number;\n}\n\nconst DEFAULT_INFLATE = 4;\n\n/**\n * Metro router — manhattan-style topology with 45° diagonals.\n *\n * Pipeline (lazy A*):\n * 1. Compute the simple geometric metro polyline first — one straight\n * axis-aligned leg followed by a 45° diagonal absorbing the remaining\n * distance. Mirrors classic transit-map line drawing.\n * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline\n * crosses an inflated obstacle, return it directly.\n * 3. Otherwise run A* with **connectivity 8** (H + V + 45° moves) on a\n * coarse grid. Simplify cell runs and convert back to world coords.\n *\n * Connectivity 8 is what makes this metro-shaped: diagonal cost `√2` is\n * cheaper than two cardinals (`1 + 1 = 2`), so A* prefers 45° moves where\n * obstacles permit — producing the metro look around obstacles too.\n */\nexport const metroRouter: IRouter = (source, target, waypoints, opts, ctx) => {\n const simple = simpleMetroPolyline(source, target, waypoints);\n const obstacles = ctx?.obstacles ?? [];\n if (obstacles.length === 0) return simple;\n\n const o = opts as MetroOpts | undefined;\n const inflate = o?.inflate ?? DEFAULT_INFLATE;\n\n if (!polylineCrossesAnyObstacle(simple, obstacles, inflate)) {\n return simple;\n }\n\n const grid = buildObstacleGrid({\n source,\n target,\n obstacles,\n gridStep: o?.gridStep,\n margin: o?.margin,\n inflate: o?.inflate,\n maxCells: o?.maxCells,\n });\n if (!grid) {\n if (typeof console !== 'undefined') {\n console.warn('metroRouter: obstacle grid exceeded maxCells; falling back to simple metro.');\n }\n return simple;\n }\n\n const startCell = worldToCell(grid, source);\n const goalCell = worldToCell(grid, target);\n const cells = aStar(grid, startCell, goalCell, { connectivity: 8 });\n if (!cells) {\n if (typeof console !== 'undefined') {\n console.warn('metroRouter: A* found no path through obstacles; falling back to simple metro.');\n }\n return simple;\n }\n\n const simplified = simplifyCellPath(cells);\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n for (let i = 1; i < simplified.length - 1; i++) {\n const c = simplified[i]!;\n out.push(cellToWorld(grid, c.cx, c.cy));\n }\n out.push({ x: target.x, y: target.y });\n return out;\n};\n\n/**\n * Simple geometric metro — between two non-aligned points, one straight\n * axis-aligned leg followed by a 45° diagonal that absorbs the remaining\n * distance. Picks \"horizontal first\" when `|dx| ≥ |dy|`. Aligned points\n * and zero-area `|dx| === |dy|` cases collapse to a single straight\n * segment. Waypoints get the same per-pair treatment.\n */\nfunction simpleMetroPolyline(\n source: Endpoint,\n target: Endpoint,\n waypoints: ReadonlyArray<Point> | undefined,\n): Point[] {\n const points: ReadonlyArray<Endpoint | Point> = waypoints && waypoints.length > 0\n ? [source, ...waypoints, target]\n : [source, target];\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n\n for (let i = 0; i < points.length - 1; i++) {\n const P = points[i]!;\n const Q = points[i + 1]!;\n const dx = Q.x - P.x;\n const dy = Q.y - P.y;\n const adx = Math.abs(dx);\n const ady = Math.abs(dy);\n\n if (adx === 0 || ady === 0 || adx === ady) {\n out.push({ x: Q.x, y: Q.y });\n continue;\n }\n\n if (adx > ady) {\n const bend: Point = { x: P.x + Math.sign(dx) * (adx - ady), y: P.y };\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n } else {\n const bend: Point = { x: P.x, y: P.y + Math.sign(dy) * (ady - adx) };\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n }\n }\n\n return out;\n}\n\n/**\n * Returns `true` if any segment of `polyline` (H, V, or 45° diagonal)\n * crosses any inflated obstacle's bounding box plus silhouette test.\n * Conservative: diagonal segments are tested via point-sampling at the\n * obstacle's `containsInflated` (when present) or rejected on AABB-only\n * obstacles (since we can't quickly decide an arbitrary-diagonal vs\n * non-axis AABB intersection cheaper than sampling).\n */\nfunction polylineCrossesAnyObstacle(\n polyline: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (let i = 0; i < polyline.length - 1; i++) {\n const a = polyline[i]!;\n const b = polyline[i + 1]!;\n for (const r of obstacles) {\n if (segmentCrossesObstacle(a, b, r, inflate)) return true;\n }\n }\n return false;\n}\n\nfunction segmentCrossesObstacle(a: Point, b: Point, r: Obstacle, inflate: number): boolean {\n const x0 = r.x - inflate;\n const y0 = r.y - inflate;\n const x1 = r.x + r.width + inflate;\n const y1 = r.y + r.height + inflate;\n\n // Cheap AABB pre-filter: bounding box of the segment vs. obstacle.\n const segMinX = a.x < b.x ? a.x : b.x;\n const segMaxX = a.x < b.x ? b.x : a.x;\n const segMinY = a.y < b.y ? a.y : b.y;\n const segMaxY = a.y < b.y ? b.y : a.y;\n if (segMaxX < x0 || segMinX > x1 || segMaxY < y0 || segMinY > y1) return false;\n\n // Axis-aligned segment + AABB-only obstacle: the pre-filter is already\n // exact (segment within the AABB strip), so return true.\n if ((a.x === b.x || a.y === b.y) && !r.containsInflated) return true;\n\n // Silhouette refinement / diagonal segment: sample points along the\n // segment and consult `containsInflated`. Falls back to AABB-only\n // (sample test pass = blocked) when no silhouette test is present.\n const test = r.containsInflated;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy);\n const step = Math.max(inflate / 2, 2);\n const samples = Math.min(64, Math.max(2, Math.ceil(len / step)));\n for (let i = 0; i <= samples; i++) {\n const t = i / samples;\n const wx = a.x + dx * t;\n const wy = a.y + dy * t;\n if (test) {\n if (test(wx, wy, inflate)) return true;\n } else {\n // No silhouette test — fall back to AABB containment per sample.\n if (wx >= x0 && wx <= x1 && wy >= y0 && wy <= y1) return true;\n }\n }\n return false;\n}\n","import type { IRouter, Point, Vec2 } from '../../../../specs';\n\ninterface ErOpts {\n /**\n * Length of the perpendicular stub off each endpoint that has a tangent\n * (set by the `boundary` anchor). Default `16` world units.\n */\n readonly stubLength?: number;\n}\n\nconst DEFAULT_STUB_LENGTH = 16;\n\n/**\n * ER (entity-relationship) router — exits each endpoint perpendicular to\n * its boundary, then routes orthogonally between the stub points.\n *\n * Reads the outward `tangent` set by the `boundary` anchor on each endpoint.\n * Each stub leg is `tangent * stubLength`. The bridge between stubs is a\n * single H-or-V segment plus one bend, picked so the bend axis alternates\n * with each stub direction (horizontal stubs → vertical bridge first).\n *\n * Falls back to a single bend (manhattan-equivalent) when neither endpoint\n * has a tangent. Waypoints are inserted between the stubs as plain\n * polyline points (no extra orthogonalisation pass).\n */\nexport const erRouter: IRouter = (source, target, waypoints, opts) => {\n const stubLen = (opts as ErOpts | undefined)?.stubLength ?? DEFAULT_STUB_LENGTH;\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n\n let cur: Point = { x: source.x, y: source.y };\n if (source.tangent) {\n cur = offsetAlong(source, source.tangent, stubLen);\n out.push(cur);\n }\n\n let end: Point = { x: target.x, y: target.y };\n let preEnd: Point | null = null;\n if (target.tangent) {\n preEnd = offsetAlong(target, target.tangent, stubLen);\n }\n\n // Insert waypoints verbatim between the stub ends.\n if (waypoints && waypoints.length > 0) {\n for (const w of waypoints) {\n bridgeOrthogonal(out, cur, { x: w.x, y: w.y }, prevAxis(out));\n cur = { x: w.x, y: w.y };\n }\n }\n\n const bridgeTarget = preEnd ?? end;\n bridgeOrthogonal(out, cur, bridgeTarget, prevAxis(out));\n\n if (preEnd) out.push(end);\n\n return out;\n};\n\nfunction offsetAlong(p: Point, t: Vec2, dist: number): Point {\n return { x: p.x + t.x * dist, y: p.y + t.y * dist };\n}\n\n/**\n * Append a single H-then-V or V-then-H bend that connects `from` to `to`,\n * choosing H-first or V-first to alternate with the most recent leg axis.\n * Aligned points emit no bend.\n */\nfunction bridgeOrthogonal(\n out: Point[],\n from: Point,\n to: Point,\n prevAxisDir: 'H' | 'V' | null,\n): void {\n if (from.x === to.x || from.y === to.y) {\n if (from.x !== to.x || from.y !== to.y) out.push({ x: to.x, y: to.y });\n return;\n }\n // Alternate from previous axis; default to dominant axis if no history.\n const goHFirst = prevAxisDir === 'H'\n ? false\n : prevAxisDir === 'V'\n ? true\n : Math.abs(to.x - from.x) >= Math.abs(to.y - from.y);\n const bend: Point = goHFirst\n ? { x: to.x, y: from.y }\n : { x: from.x, y: to.y };\n out.push(bend);\n out.push({ x: to.x, y: to.y });\n}\n\n/** Direction of the most recently appended leg. */\nfunction prevAxis(out: ReadonlyArray<Point>): 'H' | 'V' | null {\n if (out.length < 2) return null;\n const a = out[out.length - 2]!;\n const b = out[out.length - 1]!;\n if (a.x === b.x && a.y !== b.y) return 'V';\n if (a.y === b.y && a.x !== b.x) return 'H';\n return null;\n}\n","import type { IRouter, Point } from '../../../../specs';\n\ninterface OneSideOpts {\n /**\n * Which side of the source the line must leave on. Default `'right'`.\n */\n readonly side?: 'top' | 'right' | 'bottom' | 'left';\n /**\n * How far the source projects along the chosen side direction before\n * turning toward the target. Default `30` world units.\n */\n readonly padLength?: number;\n}\n\nconst DEFAULT_SIDE: 'right' = 'right';\nconst DEFAULT_PAD = 30;\n\n/**\n * oneSide router — forces the line to exit the source on a designated side,\n * then routes orthogonally to the target. Useful for swimlane / \"all on one\n * side\" diagrams where every connector must leave the source in the same\n * direction regardless of where the target is.\n *\n * Polyline shape:\n * `source → exit → midBend → target`\n *\n * - `exit` — source stepped `padLength` along the side direction.\n * - `midBend` — perpendicular to the side at the target's parallel axis\n * (so the leg from exit→midBend is along the side direction\n * inverted, and midBend→target is perpendicular).\n *\n * For 'right' / 'left' the exit/midBend legs are horizontal then vertical;\n * for 'top' / 'bottom' they're vertical then horizontal. When source and\n * target are perfectly aligned with the side direction the path collapses\n * to a single-leg traversal.\n *\n * Waypoints are not honoured by this router — its purpose is the forced\n * exit, not free-form routing. Pass `manhattan` for waypoint routing.\n */\nexport const oneSideRouter: IRouter = (source, target, _waypoints, opts) => {\n const o = opts as OneSideOpts | undefined;\n const side = o?.side ?? DEFAULT_SIDE;\n const pad = o?.padLength ?? DEFAULT_PAD;\n\n const isHorizontal = side === 'left' || side === 'right';\n const exit: Point = isHorizontal\n ? { x: source.x + (side === 'right' ? pad : -pad), y: source.y }\n : { x: source.x, y: source.y + (side === 'bottom' ? pad : -pad) };\n\n // For horizontal sides, midBend is at (exit.x, target.y) — vertical leg\n // from exit, horizontal leg to target. For vertical sides, swap axes.\n const midBend: Point = isHorizontal\n ? { x: exit.x, y: target.y }\n : { x: target.x, y: exit.y };\n\n const out: Point[] = [{ x: source.x, y: source.y }, exit];\n if (midBend.x !== exit.x || midBend.y !== exit.y) out.push(midBend);\n if (midBend.x !== target.x || midBend.y !== target.y) out.push({ x: target.x, y: target.y });\n else if (out[out.length - 1]!.x !== target.x || out[out.length - 1]!.y !== target.y) {\n out.push({ x: target.x, y: target.y });\n }\n\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Sharp segments. Walks the polyline emitting `M` then `L L L …`.\n *\n * For a 2-point polyline, this is `[M source, L target]` — equivalent to\n * the straight-line baseline. For an N-point polyline (router-produced\n * bends), this draws straight segments between every consecutive pair with\n * no corner treatment.\n */\nexport const normalPathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n for (let i = 1; i < polyline.length; i++) {\n out.push({ kind: 'L', x: polyline[i]!.x, y: polyline[i]!.y });\n }\n return out;\n};\n","import type { IPathStyle, PathCommand, Point } from '../../../../specs';\n\ninterface RoundedOpts {\n /** Corner fillet radius in world units. Default `8`. Auto-clamped per corner. */\n readonly radius?: number;\n}\n\nconst DEFAULT_RADIUS = 8;\n\n/**\n * Quadratic arc fillets at every interior polyline corner.\n *\n * For each interior corner B between segments A→B and B→C:\n * - Pick a per-corner radius `t = min(radius, |AB|/2, |BC|/2)`.\n * - Approach point P1 on segment AB at distance `t` from B.\n * - Departure point P2 on segment BC at distance `t` from B.\n * - Emit `L P1`, then `Q B P2` — the corner becomes a quadratic with control\n * at the original corner.\n *\n * For a 2-point polyline (no interior corners) the output is identical to\n * `normal`: `[M, L]`. Collinear corners (parallel incoming/outgoing) emit a\n * straight `L` through B with no Q (degenerate fillet).\n */\nexport const roundedPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const radius = (opts as RoundedOpts | undefined)?.radius ?? DEFAULT_RADIUS;\n\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n\n if (polyline.length === 2) {\n out.push({ kind: 'L', x: polyline[1]!.x, y: polyline[1]!.y });\n return out;\n }\n\n for (let i = 1; i < polyline.length - 1; i++) {\n const a = polyline[i - 1]!;\n const b = polyline[i]!;\n const c = polyline[i + 1]!;\n\n const ab = sub(b, a);\n const bc = sub(c, b);\n const lenAB = len(ab);\n const lenBC = len(bc);\n if (lenAB === 0 || lenBC === 0) {\n out.push({ kind: 'L', x: b.x, y: b.y });\n continue;\n }\n\n // Cap the fillet so adjacent corners can't overlap on short segments.\n const t = Math.min(radius, lenAB / 2, lenBC / 2);\n if (t <= 0) {\n out.push({ kind: 'L', x: b.x, y: b.y });\n continue;\n }\n\n const p1 = { x: b.x - (ab.x / lenAB) * t, y: b.y - (ab.y / lenAB) * t };\n const p2 = { x: b.x + (bc.x / lenBC) * t, y: b.y + (bc.y / lenBC) * t };\n\n out.push({ kind: 'L', x: p1.x, y: p1.y });\n out.push({ kind: 'Q', cx: b.x, cy: b.y, x: p2.x, y: p2.y });\n }\n\n const last = polyline[polyline.length - 1]!;\n out.push({ kind: 'L', x: last.x, y: last.y });\n return out;\n};\n\nfunction sub(a: Point, b: Point): Point {\n return { x: a.x - b.x, y: a.y - b.y };\n}\n\nfunction len(v: Point): number {\n return Math.hypot(v.x, v.y);\n}\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BezierOpts {\n /**\n * Direction of the s-curve. `'h'` pulls control points horizontally,\n * `'v'` pulls them vertically, `'auto'` picks the dominant axis from the\n * source→target delta. Default `'auto'`.\n */\n readonly axis?: 'h' | 'v' | 'auto';\n /**\n * How far the control points pull along the axis, as a fraction of the\n * source→target delta on that axis. `0.5` produces a balanced s-curve;\n * `0` collapses to a straight line; `>0.5` produces an exaggerated swing.\n * Default `0.5`.\n */\n readonly tension?: number;\n}\n\nconst DEFAULT_TENSION = 0.5;\n\n/**\n * Single cubic Bézier between the first and last polyline points, with\n * auto-generated control handles. Intermediate polyline points (router\n * waypoints, manhattan corners, …) are **ignored** — pick `smooth` if you\n * want the path to follow them.\n *\n * Control-point strategy: direction-aware s-curve.\n * - For horizontal-dominant layouts the controls pull horizontally:\n * `c1 = source + (dx * tension, 0)`, `c2 = target - (dx * tension, 0)`.\n * Source leaves and target arrives along the x-axis.\n * - For vertical-dominant layouts the controls pull vertically.\n *\n * Output: `[M source, C target]` — a single curve segment.\n */\nexport const bezierPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const o = opts as BezierOpts | undefined;\n const tension = o?.tension ?? DEFAULT_TENSION;\n const axisOpt = o?.axis ?? 'auto';\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const dx = t.x - s.x;\n const dy = t.y - s.y;\n\n const axis: 'h' | 'v' = axisOpt === 'auto'\n ? Math.abs(dx) >= Math.abs(dy) ? 'h' : 'v'\n : axisOpt;\n\n const c1: { x: number; y: number } = axis === 'h'\n ? { x: s.x + dx * tension, y: s.y }\n : { x: s.x, y: s.y + dy * tension };\n\n const c2: { x: number; y: number } = axis === 'h'\n ? { x: t.x - dx * tension, y: t.y }\n : { x: t.x, y: t.y - dy * tension };\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface QuadraticOpts {\n /**\n * Perpendicular offset of the control point from the source→target chord,\n * in world units. Positive values bow the curve to the **right** of the\n * chord direction (in screen-y-down coordinates: rotating the chord 90°\n * CW); negative values bow it to the left. Default `30`.\n *\n * Choose the sign to give every edge in a radial / hub-and-spoke layout\n * a consistent rotational bias — a positive offset on every spoke makes\n * the bundle read as a coherent swirl rather than a noisy spray.\n */\n readonly curveOffset?: number;\n /**\n * Where along the chord the control point's foot sits, as a fraction\n * `0..1` (`0` = source, `1` = target). The perpendicular offset is\n * applied from this foot. Default `0.5` (chord midpoint), which\n * produces a symmetric arc.\n */\n readonly curvePosition?: number;\n}\n\nconst DEFAULT_OFFSET = 30;\nconst DEFAULT_POSITION = 0.5;\n\n/**\n * Quadratic Bézier from the first polyline point to the last with a single\n * control point placed **perpendicular to the chord** at `curvePosition`\n * along it and `curveOffset` units to the side.\n *\n * This is the G6-style \"quadratic edge\": one control point, signed\n * perpendicular offset, fixed position along the chord. Unlike axis-aligned\n * `bezier` (whose control handles pull along `axis: 'h' | 'v'`), the\n * perpendicular construction gives a real bow on **every** orientation —\n * cardinal chords no longer collapse to straight lines.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored (a router that produces extra points doesn't compose\n * meaningfully with a single-control-point quadratic).\n *\n * Edge cases:\n * - Polyline shorter than two points → `[]` (matches the other pathStyles).\n * - Coincident endpoints (`len === 0`) → degenerate `M` only; the\n * perpendicular is undefined.\n */\nexport const quadraticPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n\n const o = opts as QuadraticOpts | undefined;\n const offset = o?.curveOffset ?? DEFAULT_OFFSET;\n const position = o?.curvePosition ?? DEFAULT_POSITION;\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const dx = t.x - s.x;\n const dy = t.y - s.y;\n const len = Math.hypot(dx, dy);\n\n if (len === 0) {\n return [{ kind: 'M', x: s.x, y: s.y }];\n }\n\n // Anchor point along the chord at `position` (0 = source, 1 = target).\n const ax = s.x + dx * position;\n const ay = s.y + dy * position;\n\n // Unit perpendicular to the chord. In screen-y-down coords this rotates\n // the chord direction 90° clockwise so positive `offset` bows the curve\n // to the visual right of the chord direction (source → target).\n const px = dy / len;\n const py = -dx / len;\n\n const cx = ax + px * offset;\n const cy = ay + py * offset;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'Q', cx, cy, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BumpRadialOpts {\n /**\n * Polar origin (centre of the polar coordinate system) in world units.\n * Source / target angles are measured from this point. Default `(0, 0)`.\n *\n * Set this when your radial layout is centred somewhere other than the\n * world origin — e.g. an offset hierarchy, a sub-tree positioned beside\n * a sibling cluster.\n */\n readonly origin?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Single cubic Bézier from the first to the last polyline point with control\n * points placed on the **midradius circle** at the source and target angles.\n *\n * This is the same curve `d3.linkRadial()` produces, ported to operate on\n * cartesian polyline endpoints (we recover the polar coordinates from the\n * configured origin). It gives a tree edge that:\n * - leaves the source tangent to the radius (radially outward / inward),\n * - sweeps through the midradius arc between the two angles,\n * - arrives at the target tangent to the radius.\n *\n * The result reads correctly in any orientation — it doesn't bulge sideways\n * the way an axis-aligned `bezier` does on near-vertical edges. Pair with\n * `router: 'straight'`; intermediate polyline waypoints are ignored (a\n * router that produces extra points doesn't compose meaningfully with a\n * polar curve).\n *\n * Edge cases:\n * - Co-linear with the origin (`r0` or `r1` is zero, or both angles equal):\n * falls back to a straight line, since a polar curve isn't defined.\n * - Polyline shorter than two points: returns `[]` (matches other styles).\n */\nexport const bumpRadialPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const origin = (opts as BumpRadialOpts | undefined)?.origin ?? { x: 0, y: 0 };\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const sxRel = s.x - origin.x;\n const syRel = s.y - origin.y;\n const txRel = t.x - origin.x;\n const tyRel = t.y - origin.y;\n\n const r0 = Math.hypot(sxRel, syRel);\n const r1 = Math.hypot(txRel, tyRel);\n\n // Degenerate cases — emit a straight segment. A polar curve would either\n // collapse to zero or NaN.\n if (r0 === 0 || r1 === 0) {\n return [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'L', x: t.x, y: t.y },\n ];\n }\n\n const a0 = Math.atan2(syRel, sxRel);\n const a1 = Math.atan2(tyRel, txRel);\n const rMid = (r0 + r1) / 2;\n\n const c1x = origin.x + rMid * Math.cos(a0);\n const c1y = origin.y + rMid * Math.sin(a0);\n const c2x = origin.x + rMid * Math.cos(a1);\n const c2y = origin.y + rMid * Math.sin(a1);\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x, c1y, c2x, c2y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Single cubic Bézier from the first to the last polyline point.\n *\n * Two modes depending on whether anchor `endpoints` are passed in:\n *\n * - **Tangent-aware (preferred)** — when `endpoints.source.tangent` and / or\n * `endpoints.target.tangent` are available, the control points are placed\n * along each shape's outward surface normal: `c1 = s + sTan × handle`,\n * `c2 = t + tTan × handle`, with `handle = |tx − sx| / 2`. The curve\n * therefore leaves the source flush with its silhouette tangent and\n * arrives at the target flush with *its* silhouette tangent — no kink\n * at off-equator anchors (circles, polygons, rounded rects).\n *\n * - **Fallback** — when no tangents are available (direct unit-test\n * invocation, or an anchor that produced no tangent), the control\n * points fall back to the **vertical midline** between source and\n * target — `c1 = ((sx + tx)/2, sy)` and `c2 = ((sx + tx)/2, ty)` —\n * matching d3-shape's `linkHorizontal()` / d3-sankey's\n * `sankeyLinkHorizontal()` ribbon curve. For rect + horizontal-face\n * anchors (`edge-port` on `'left'` / `'right'`) the tangent-aware\n * formula reduces to this same placement, so existing rect-on-rect\n * visuals are unchanged.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored (a router that produces extra points doesn't compose\n * meaningfully with a horizontal-bump curve).\n *\n * Edge cases:\n * - Polyline shorter than two points → `[]` (matches the other pathStyles).\n * - `sx === tx` (vertical link) → tangent-aware path uses `handle = 0`,\n * collapsing both control points onto the endpoints (a straight line);\n * fallback degenerates to a vertical line on `x = sx`. Both stay\n * well-defined.\n */\nexport const bumpHorizontalPathStyle: IPathStyle = (polyline, _opts, endpoints) => {\n if (polyline.length < 2) return [];\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const handle = Math.abs(t.x - s.x) / 2;\n\n const sTan = endpoints?.source.tangent;\n const tTan = endpoints?.target.tangent;\n\n const c1x = sTan ? s.x + sTan.x * handle : (s.x + t.x) / 2;\n const c1y = sTan ? s.y + sTan.y * handle : s.y;\n const c2x = tTan ? t.x + tTan.x * handle : (s.x + t.x) / 2;\n const c2y = tTan ? t.y + tTan.y * handle : t.y;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x, c1y, c2x, c2y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Single cubic Bézier from the first to the last polyline point, pulled\n * **vertically** — the curve of a top-to-bottom tree, d3-shape's\n * `linkVertical()`: `c1 = (sx, (sy + ty)/2)`, `c2 = (tx, (sy + ty)/2)`.\n *\n * Unlike `bump-horizontal` it ignores the anchors' tangents. On a circle with\n * the default `boundary` anchor the tangent points at the other node, so a\n * tangent-following curve flattens into a straight line; the midline keeps the\n * S-curve on every shape.\n *\n * Pair with `router: 'straight'`; intermediate waypoints are ignored.\n *\n * Edge cases: fewer than two points → `[]`; `sy === ty` → a straight line.\n */\nexport const bumpVerticalPathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const midY = (s.y + t.y) / 2;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x: s.x, c1y: midY, c2x: t.x, c2y: midY, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ntype Pt = { readonly x: number; readonly y: number };\n\n/** Below this distance (world units) two points are the same point. */\nconst COINCIDENT = 0.5;\n\n/**\n * A piecewise cubic Bézier read from its **control points** — the curve a\n * layout engine computed, drawn as it computed it.\n *\n * Pair with `router: 'straight'`, which yields\n * `[sourceAnchor, ...waypoints, targetAnchor]`. The waypoints are read as a\n * Bézier chain `P0, C1, C2, P1, C1, C2, P2, …, Pn` — `3k + 1` points, every\n * third one on the curve. That is how ELK's `SPLINES` edge routing reports a\n * section: start point, bend points (always `3k − 1` of them), end point. The\n * chain is drawn as is, so the curve keeps the clearance from nodes the engine\n * routed it for — unlike `smooth`, which interpolates *through* points and can\n * overshoot.\n *\n * The anchors join the chain with a straight leg when they don't sit on its\n * ends. With the default `boundary` anchor aiming at the first / last waypoint,\n * and ELK's section ends on the node border, the legs are zero-length and are\n * left out.\n *\n * Waypoints that don't form a chain (wrong count, or none) are drawn as a\n * polyline through them — the same as `normal` — so a misconfigured edge stays\n * visible and connected.\n */\nexport const splinePathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n const source = polyline[0]!;\n const target = polyline[polyline.length - 1]!;\n const chain = polyline.slice(1, -1);\n\n if (chain.length < 4 || (chain.length - 1) % 3 !== 0) {\n return polyline.map((p, i): PathCommand =>\n i === 0 ? { kind: 'M', x: p.x, y: p.y } : { kind: 'L', x: p.x, y: p.y },\n );\n }\n\n const first = chain[0]!;\n const last = chain[chain.length - 1]!;\n const out: PathCommand[] = [{ kind: 'M', x: source.x, y: source.y }];\n if (!coincident(source, first)) out.push({ kind: 'L', x: first.x, y: first.y });\n for (let i = 1; i + 2 < chain.length; i += 3) {\n const c1 = chain[i]!;\n const c2 = chain[i + 1]!;\n const p = chain[i + 2]!;\n out.push({ kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: p.x, y: p.y });\n }\n if (!coincident(last, target)) out.push({ kind: 'L', x: target.x, y: target.y });\n return out;\n};\n\nfunction coincident(a: Pt, b: Pt): boolean {\n return Math.abs(a.x - b.x) < COINCIDENT && Math.abs(a.y - b.y) < COINCIDENT;\n}\n","import type { IPathStyle, PathCommand, Point } from '../../../../specs';\n\ninterface SmoothOpts {\n /**\n * Catmull-Rom tension. `1` is the standard uniform spline (visually\n * smooth, slightly loose at sharp turns); higher values tighten the\n * curve toward the polyline; `0` collapses to straight segments. Default\n * `1`.\n */\n readonly tension?: number;\n}\n\nconst DEFAULT_TENSION = 1;\n\n/**\n * Catmull-Rom spline through every polyline point, emitted as cubic Béziers.\n * The curve passes through every input point exactly; intermediate router\n * waypoints / manhattan corners become smoothly interpolated bends.\n *\n * For each segment `Pi → Pi+1`, the control points use Catmull-Rom to Bézier\n * conversion:\n * `c1 = Pi + (Pi+1 - Pi-1) * tension / 6`\n * `c2 = Pi+1 - (Pi+2 - Pi) * tension / 6`\n *\n * At the endpoints, the missing virtual neighbour is mirrored\n * (`P-1 = P0`, `Pn+1 = Pn`).\n *\n * For a 2-point polyline this produces a single cubic with collinear control\n * points — visually identical to a straight line.\n */\nexport const smoothPathStyle: IPathStyle = (polyline, opts) => {\n const n = polyline.length;\n if (n < 2) return [];\n\n const tension = (opts as SmoothOpts | undefined)?.tension ?? DEFAULT_TENSION;\n const k = tension / 6;\n\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n\n for (let i = 0; i < n - 1; i++) {\n const p0 = polyline[i - 1] ?? polyline[i]!;\n const p1 = polyline[i]!;\n const p2 = polyline[i + 1]!;\n const p3 = polyline[i + 2] ?? p2;\n\n const c1: Point = { x: p1.x + (p2.x - p0.x) * k, y: p1.y + (p2.y - p0.y) * k };\n const c2: Point = { x: p2.x - (p3.x - p1.x) * k, y: p2.y - (p3.y - p1.y) * k };\n\n out.push({ kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: p2.x, y: p2.y });\n }\n\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface StepRadialOpts {\n /**\n * Polar origin (centre of the polar coordinate system) in world units.\n * Source / target angles are measured from this point. Default `(0, 0)`.\n *\n * Set this when your radial layout is centred somewhere other than the\n * world origin.\n */\n readonly origin?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Two-segment **radial step** (a.k.a. \"elbow\") link, matching the d3\n * `linkStep` helper used by the canonical Tree of Life example:\n *\n * 1. Circular **arc** at the source's radius from the source angle to the\n * target angle (constant-radius sweep along the parent's tier).\n * 2. Straight **radial line** outward from there to the target.\n *\n * Visually this produces the boxy / angular cluster-dendrogram look — every\n * subtree fans out from a horizontal arc at its parent's radius, then shoots\n * outward as straight spokes. It's the right pick for radial *clusters*\n * (where all leaves sit on a single outer rim and the eye reads tiers via\n * the constant-radius arcs); the smooth {@link bumpRadialPathStyle} is the\n * right pick for radial *trees* (where edges should curve continuously).\n *\n * The arc is approximated with cubic Bézier sub-arcs (≤ 90° each) using the\n * standard `k = (4/3) tan(θ/4) r` handle-length formula — visually\n * indistinguishable from a true SVG `A` command at any zoom, and stays a\n * flat sequence of `M / C / L` commands the Pixi renderer already knows\n * how to consume.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored. Use `anchor: 'center'` on the edge so the tangent is computed\n * from the true node-centre angle (otherwise the arc would launch from the\n * trimmed boundary cut-point and read crooked).\n *\n * Edge cases:\n * - `r0 === 0` (source at the origin): emits a single straight `M → L`.\n * - Source / target angles equal (single-child clade, or angular wrap\n * collapses to zero): emits a straight radial `M → L`.\n * - Polyline shorter than two points: returns `[]`.\n */\nexport const stepRadialPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const origin = (opts as StepRadialOpts | undefined)?.origin ?? { x: 0, y: 0 };\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const sxRel = s.x - origin.x;\n const syRel = s.y - origin.y;\n const txRel = t.x - origin.x;\n const tyRel = t.y - origin.y;\n\n const r0 = Math.hypot(sxRel, syRel);\n\n // Degenerate: source has no defined angle. Straight line is the only\n // sensible fallback.\n if (r0 === 0) {\n return [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'L', x: t.x, y: t.y },\n ];\n }\n\n const a0 = Math.atan2(syRel, sxRel);\n const a1 = Math.atan2(tyRel, txRel);\n\n // Normalise the angular sweep into (-π, π] so we always take the shorter\n // way around. In a hierarchical layout the parent-to-child angular gap is\n // small (well under π/2 in practice), so this is just defensive.\n let delta = a1 - a0;\n while (delta > Math.PI) delta -= 2 * Math.PI;\n while (delta < -Math.PI) delta += 2 * Math.PI;\n\n // Arc-end point: same radius as source, angle of target.\n const arcEndX = origin.x + r0 * Math.cos(a1);\n const arcEndY = origin.y + r0 * Math.sin(a1);\n\n const out: PathCommand[] = [{ kind: 'M', x: s.x, y: s.y }];\n\n if (Math.abs(delta) > 1e-9) {\n // Approximate the arc with one or more cubic Béziers, each spanning at\n // most ~π/2 of the circle so the standard handle-length formula stays\n // visually exact.\n const numSegments = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2)));\n const segAngle = delta / numSegments;\n // Signed handle length — sign of `tan(segAngle / 4)` already tracks\n // the direction of the sweep, so the same formula works for both\n // clockwise and anti-clockwise arcs.\n const k = (4 / 3) * Math.tan(segAngle / 4) * r0;\n\n let theta = a0;\n let px = origin.x + r0 * Math.cos(theta);\n let py = origin.y + r0 * Math.sin(theta);\n for (let i = 0; i < numSegments; i++) {\n const nextTheta = theta + segAngle;\n const nx = origin.x + r0 * Math.cos(nextTheta);\n const ny = origin.y + r0 * Math.sin(nextTheta);\n // Tangent at each endpoint of a circle (ccw): (-sin θ, cos θ).\n // Signed `k` flips it for clockwise sweeps automatically.\n const c1x = px + k * -Math.sin(theta);\n const c1y = py + k * Math.cos(theta);\n const c2x = nx - k * -Math.sin(nextTheta);\n const c2y = ny - k * Math.cos(nextTheta);\n out.push({ kind: 'C', c1x, c1y, c2x, c2y, x: nx, y: ny });\n theta = nextTheta;\n px = nx;\n py = ny;\n }\n } else {\n // Same ray — no arc, just glide to the arc-end point (which equals the\n // source up to floating-point noise) before emitting the radial line.\n out.push({ kind: 'L', x: arcEndX, y: arcEndY });\n }\n\n // Radial segment: straight line out to the target.\n out.push({ kind: 'L', x: t.x, y: t.y });\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BundleOpts {\n /**\n * Bundling tension in `[0, 1]`. `0` collapses the curve to a straight chord\n * between the endpoints (the B-spline through the lerp line is linear);\n * `1` is a strict open cubic B-spline through every polyline point;\n * intermediate values β-blend each control point toward the chord per\n * `P_i' = β·P_i + (1 - β)·lerp(P_0, P_{n-1}, i/(n-1))`. Default `0.85`,\n * matching d3-shape's `curveBundle` default and the Observable\n * Hierarchical Edge Bundling example.\n */\n readonly beta?: number;\n}\n\nconst DEFAULT_BETA = 0.85;\n\n/**\n * Hierarchical-edge-bundling curve through the polyline, emitted as cubic\n * Béziers. This is the d3-shape `curveBundle.beta(β)` shape: an open cubic\n * B-spline driven by control points that are β-blended toward the straight\n * line from `P_0` to `P_{n-1}`.\n *\n * Pair with `router: 'straight'` and feed the hierarchy-ancestor sequence as\n * `waypoints` on the connector spec (per-edge layout output); the router will\n * pass `[source, ...waypoints, target]` through unchanged, and this pathStyle\n * sees the full sequence.\n *\n * Reference: d3-shape `src/curve/bundle.js` + `src/curve/basis.js`.\n */\nexport const bundlePathStyle: IPathStyle = (polyline, opts) => {\n const n = polyline.length;\n if (n < 2) return [];\n\n const p0 = polyline[0]!;\n const pn = polyline[n - 1]!;\n\n // 2 points = no interior to bundle — straight line.\n if (n === 2) {\n return [\n { kind: 'M', x: p0.x, y: p0.y },\n { kind: 'L', x: pn.x, y: pn.y },\n ];\n }\n\n const beta = clamp01((opts as BundleOpts | undefined)?.beta ?? DEFAULT_BETA);\n const dx = pn.x - p0.x;\n const dy = pn.y - p0.y;\n const inv = 1 / (n - 1);\n\n // β-blend each control point toward the straight chord. β=1 leaves the\n // polyline untouched (strict B-spline); β=0 maps every point onto the\n // chord (the B-spline through collinear points is linear).\n const bx: number[] = new Array(n);\n const by: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const t = i * inv;\n const pi = polyline[i]!;\n bx[i] = beta * pi.x + (1 - beta) * (p0.x + t * dx);\n by[i] = beta * pi.y + (1 - beta) * (p0.y + t * dy);\n }\n\n // Open cubic B-spline emitted as Bézier segments. Matches d3.Basis.lineEnd\n // semantics: a `moveTo(B0)`, a `lineTo((5·B0 + B1)/6)` to anchor the first\n // segment, then for each `i ≥ 2` a Bézier from the running pen to the\n // averaged knot `(B_{i-2} + 4·B_{i-1} + B_i)/6` using the standard\n // B-spline-to-Bézier conversion, and finally a closing Bézier into\n // `(B_{n-2} + 5·B_{n-1})/6` plus a `lineTo(B_{n-1})` so the curve actually\n // terminates at the last input point rather than at the averaged knot.\n const out: PathCommand[] = [];\n out.push({ kind: 'M', x: bx[0]!, y: by[0]! });\n out.push({\n kind: 'L',\n x: (5 * bx[0]! + bx[1]!) / 6,\n y: (5 * by[0]! + by[1]!) / 6,\n });\n\n for (let i = 2; i < n; i++) {\n const x0 = bx[i - 2]!;\n const y0 = by[i - 2]!;\n const x1 = bx[i - 1]!;\n const y1 = by[i - 1]!;\n const x = bx[i]!;\n const y = by[i]!;\n out.push({\n kind: 'C',\n c1x: (2 * x0 + x1) / 3,\n c1y: (2 * y0 + y1) / 3,\n c2x: (x0 + 2 * x1) / 3,\n c2y: (y0 + 2 * y1) / 3,\n x: (x0 + 4 * x1 + x) / 6,\n y: (y0 + 4 * y1 + y) / 6,\n });\n }\n\n const xN1 = bx[n - 2]!;\n const yN1 = by[n - 2]!;\n const xN = bx[n - 1]!;\n const yN = by[n - 1]!;\n out.push({\n kind: 'C',\n c1x: (2 * xN1 + xN) / 3,\n c1y: (2 * yN1 + yN) / 3,\n c2x: (xN1 + 2 * xN) / 3,\n c2y: (yN1 + 2 * yN) / 3,\n x: (xN1 + 5 * xN) / 6,\n y: (yN1 + 5 * yN) / 6,\n });\n out.push({ kind: 'L', x: xN, y: yN });\n\n return out;\n};\n\nfunction clamp01(v: number): number {\n return v < 0 ? 0 : v > 1 ? 1 : v;\n}\n","import type { IPathStyle } from '../../../../specs';\n\ntype LoopPolylineCardinalSide = 'top' | 'right' | 'bottom' | 'left';\ntype LoopPolylineCornerSide =\n | 'top-right' | 'bottom-right' | 'bottom-left' | 'top-left';\ntype LoopPolylineSide = LoopPolylineCardinalSide | LoopPolylineCornerSide;\n\ninterface LoopPolylineOpts {\n /**\n * Where the loop sits relative to the pivot. Two families:\n *\n * **Cardinals** (`top` / `right` / `bottom` / `left`) — the loop is a\n * three-segment U-bracket sticking straight out from one side of the\n * host. Both feet sit on a chord perpendicular to `side` at distance\n * `baseOffset`.\n *\n * **Corners** (`top-right` / `bottom-right` / `bottom-left` /\n * `top-left`) — the loop is a three-segment orthogonal wrap around the\n * named corner of the host. One foot lands on a line parallel to the\n * horizontal edge, the other on a line parallel to the vertical edge;\n * the middle segment runs past the outer corner of the wrap. Use\n * `baseOffsetX` / `baseOffsetY` (or the symmetric fallback\n * `baseOffset`) to position the wrap corner relative to the host\n * silhouette.\n *\n * For arbitrary directions pass a number — radians, screen\n * coordinates (y points down). Numeric `side` always renders the\n * cardinal U-bracket geometry, even when the angle is diagonal.\n * Default `'top'`.\n */\n readonly side?: LoopPolylineSide | number;\n /**\n * Symmetric clearance from the pivot to the host silhouette. For\n * cardinals: distance along `side` from pivot to the foot midpoint.\n * For corners: distance along *both* axes from pivot to the named\n * corner of the silhouette — use `baseOffsetX` / `baseOffsetY` for\n * non-square hosts. Default `28`.\n */\n readonly baseOffset?: number;\n /**\n * Horizontal-axis distance from pivot to silhouette. Only consulted\n * for corner sides; defaults to `baseOffset` when omitted.\n */\n readonly baseOffsetX?: number;\n /**\n * Vertical-axis distance from pivot to silhouette. Only consulted\n * for corner sides; defaults to `baseOffset` when omitted.\n */\n readonly baseOffsetY?: number;\n /**\n * How far each stub extends past the silhouette. For cardinals: both\n * stubs run `stubLength` further along `side` from the feet. For\n * corners: each stub runs `stubLength` further outward (away from the\n * named corner) along its perpendicular axis. Default `30`.\n */\n readonly stubLength?: number;\n /**\n * Foot separation along the silhouette. For cardinals: tangential\n * distance perpendicular to `side` — both feet sit on a chord, one\n * at `-gap/2`, the other at `+gap/2`. For corners: along-edge\n * distance from the named corner of the silhouette to each foot —\n * one foot sits `gap` from the corner along the horizontal edge, the\n * other `gap` along the vertical edge. Default `30`.\n */\n readonly gap?: number;\n}\n\nconst DEFAULT_SIDE: LoopPolylineSide = 'top';\nconst DEFAULT_BASE_OFFSET = 28;\nconst DEFAULT_STUB_LENGTH = 30;\nconst DEFAULT_GAP = 30;\n\nconst CORNER_SIDES = new Set<LoopPolylineSide>([\n 'top-right', 'bottom-right', 'bottom-left', 'top-left',\n]);\n\nfunction sideToAngle(side: LoopPolylineSide | number): number {\n if (typeof side === 'number') return side;\n switch (side) {\n case 'top': return -Math.PI / 2;\n case 'top-right': return -Math.PI / 4;\n case 'right': return 0;\n case 'bottom-right': return Math.PI / 4;\n case 'bottom': return Math.PI / 2;\n case 'bottom-left': return 3 * Math.PI / 4;\n case 'left': return Math.PI;\n case 'top-left': return -3 * Math.PI / 4;\n }\n}\n\n/**\n * Signed unit vector components for each corner. Sign convention:\n * sx = +1 for *-right, -1 for *-left\n * sy = -1 for top-*, +1 for bottom-*\n */\nfunction cornerSigns(side: LoopPolylineCornerSide): { sx: number; sy: number } {\n switch (side) {\n case 'top-right': return { sx: 1, sy: -1 };\n case 'bottom-right': return { sx: 1, sy: 1 };\n case 'bottom-left': return { sx: -1, sy: 1 };\n case 'top-left': return { sx: -1, sy: -1 };\n }\n}\n\n/**\n * Self-loop pathStyle — orthogonal polyline anchored at the first\n * polyline point. Designed for edges where source and target reference\n * the same shape; the router output is `[p, p]` and this style ignores\n * everything after `polyline[0]`.\n *\n * Two geometries dispatch on `side`:\n *\n * **Cardinal U-bracket** (`top` / `right` / `bottom` / `left` or any\n * numeric angle) — three segments. Feet sit on a chord perpendicular\n * to `side` at distance `baseOffset` from the pivot, separated by\n * `gap`. From each foot the path runs `stubLength` further along\n * `side` to the two outer corners, joined by one cross segment.\n *\n * **Corner wrap** (`top-right` / `bottom-right` / `bottom-left` /\n * `top-left`) — four segments. Both feet sit on the host silhouette:\n * one on the horizontal edge `gap` from the named corner, the other\n * on the vertical edge `gap` from the same corner. From each foot the\n * path runs `stubLength` perpendicular to its edge (outward), the two\n * outward stubs are joined by a cross segment past the corner, and the\n * arrow lands flush with the perpendicular edge. The wrap's inner\n * corner sits at `(±baseOffsetX, ±baseOffsetY)` from the pivot.\n *\n * Pair with `router: 'straight'`; the polyline content beyond the first\n * point is ignored.\n *\n * Edge cases:\n * - Polyline shorter than one point: returns `[]`.\n * - Cardinal `gap = 0`: both stubs collapse onto the same line — the\n * loop reads as a single out-and-back spike.\n * - Corner `gap = 0`: both feet land at the corner itself; the wrap\n * degenerates to a closed rectangle whose inner corner touches the\n * silhouette.\n */\nexport const loopPolylinePathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 1) return [];\n const o = opts as LoopPolylineOpts | undefined;\n const side = o?.side ?? DEFAULT_SIDE;\n const baseOffset = o?.baseOffset ?? DEFAULT_BASE_OFFSET;\n const stubLength = o?.stubLength ?? DEFAULT_STUB_LENGTH;\n const gap = o?.gap ?? DEFAULT_GAP;\n const p = polyline[0]!;\n\n // Corner wrap — named corner sides only. Numeric angles always fall\n // through to the cardinal U-bracket geometry, even when the angle is\n // diagonal — callers asking for a literal corner wrap must use the\n // named corner sides.\n if (typeof side === 'string' && CORNER_SIDES.has(side)) {\n const { sx, sy } = cornerSigns(side as LoopPolylineCornerSide);\n const offX = o?.baseOffsetX ?? baseOffset;\n const offY = o?.baseOffsetY ?? baseOffset;\n // Silhouette corner in world coords (the named corner of the host).\n const cornerX = p.x + sx * offX;\n const cornerY = p.y + sy * offY;\n // Foot A — on the horizontal edge, `gap` along it from the corner.\n const ax = cornerX - sx * gap;\n const ay = cornerY;\n // Foot B — on the vertical edge, `gap` along it from the corner.\n const bx = cornerX;\n const by = cornerY - sy * gap;\n // Outer corner of the wrap bracket — `stubLength` past the silhouette\n // in both axes.\n const ox = cornerX + sx * stubLength;\n const oy = cornerY + sy * stubLength;\n // Path: out from horizontal edge, across past the corner, down past\n // the vertical-edge level, in to the vertical edge. Both endpoints\n // sit on the host silhouette so the arrow marker lands flush.\n return [\n { kind: 'M', x: ax, y: ay },\n { kind: 'L', x: ax, y: oy },\n { kind: 'L', x: ox, y: oy },\n { kind: 'L', x: ox, y: by },\n { kind: 'L', x: bx, y: by },\n ];\n }\n\n // Cardinal U-bracket — applies to the four cardinal sides and any\n // numeric angle.\n const angle = sideToAngle(side);\n const ux = Math.cos(angle);\n const uy = Math.sin(angle);\n // Perpendicular to `angle`, rotated 90° anti-clockwise.\n const px = -uy;\n const py = ux;\n // Foot midpoint sits `baseOffset` along the loop direction from pivot.\n const mx = p.x + ux * baseOffset;\n const my = p.y + uy * baseOffset;\n const halfG = gap / 2;\n const sx = mx - px * halfG;\n const sy = my - py * halfG;\n const ex = mx + px * halfG;\n const ey = my + py * halfG;\n const c1x = sx + ux * stubLength;\n const c1y = sy + uy * stubLength;\n const c2x = ex + ux * stubLength;\n const c2y = ey + uy * stubLength;\n return [\n { kind: 'M', x: sx, y: sy },\n { kind: 'L', x: c1x, y: c1y },\n { kind: 'L', x: c2x, y: c2y },\n { kind: 'L', x: ex, y: ey },\n ];\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ntype LoopCurveSide =\n | 'top' | 'right' | 'bottom' | 'left'\n | 'top-right' | 'bottom-right' | 'bottom-left' | 'top-left';\n\ninterface LoopCurveOpts {\n /**\n * Which way the petal blooms from the host. Named sides resolve to\n * world-space angles in screen coordinates (y points down):\n *\n * top = -π/2 top-right = -π/4\n * right = 0 bottom-right = π/4\n * bottom = π/2 bottom-left = 3π/4\n * left = π top-left = -3π/4\n *\n * Wins over `angle` when both are provided.\n */\n readonly side?: LoopCurveSide;\n /**\n * Direction the petal blooms from the host, in radians. `0` points\n * right, `π/2` points down (screen coords — y grows downward),\n * `-π/2` points up. Default `-π/2` — petal blooms above the host.\n * Ignored when `side` is set.\n */\n readonly angle?: number;\n /**\n * How far the balloon tip sits past the chord between the two feet,\n * measured along `angle` from the chord midpoint. The geometric apex\n * of the curve lands at roughly `0.75 * radius` past the chord\n * (cubic-bezier control-arm pull falls short of the geometric\n * maximum). Default `40`.\n */\n readonly radius?: number;\n /**\n * Belly half-spread of the balloon — distance from the tip along the\n * chord direction to each control point. When `bulge > clen/2` (half\n * the chord length) the control points lie past the feet in chord\n * direction, splaying the curve outward → balloon. When\n * `bulge = clen/2` the controls sit directly above the feet → U\n * (parallel-sided hairpin). When `bulge < clen/2` controls converge\n * toward the tip → teardrop. Default `radius` (round balloon).\n */\n readonly bulge?: number;\n /**\n * Used only in **single-pivot mode**, i.e. when the polyline's first\n * and last points coincide (source and target endpoints resolved to\n * the same world point — typical when both use the `center` anchor).\n * Distance from the pivot to the foot midpoint, measured along\n * `angle`. Ignored when the polyline has two distinct endpoints\n * (two-foot mode), since the feet are then taken directly from the\n * polyline. Default `28`.\n */\n readonly baseOffset?: number;\n /**\n * Used only in **single-pivot mode**. Tangential separation between\n * the two feet, perpendicular to `angle`. Ignored in two-foot mode.\n * Default `12`.\n */\n readonly width?: number;\n /**\n * Used only in **single-pivot mode**. World-space shift of the foot\n * midpoint, applied before `baseOffset` is added along `angle`. Lets\n * callers land the petal on a specific edge/corner when working\n * from a single `center` anchor. Ignored in two-foot mode (anchors\n * already position the feet). Default `{ dx: 0, dy: 0 }`.\n */\n readonly pivotOffset?: { readonly dx: number; readonly dy: number };\n}\n\nconst DEFAULT_ANGLE = -Math.PI / 2; // petal points up\nconst DEFAULT_BASE_OFFSET = 28;\nconst DEFAULT_RADIUS = 40;\nconst DEFAULT_WIDTH = 12;\n// Below this chord length we treat the two polyline endpoints as\n// coincident and fall back to single-pivot mode. 0.5 world units is\n// well below visible — anything smaller is sub-pixel jitter.\nconst COINCIDENT_EPS = 0.5;\n\n/**\n * Named loop-curve shape presets. Each preset carries the four\n * profile-shaping opts (`baseOffset`, `radius`, `width`, `bulge`); the\n * caller fills in placement (`side` / `angle`, `pivotOffset`) per\n * instance. Spread into `pathStyleOpts`:\n *\n * pathStyleOpts: { ...LOOP_CURVE_PRESETS.balloon, side: 'top' }\n *\n * Definitions:\n * - `balloon` — fat puffed belly. `bulge >> width/2` → controls\n * splay wide; `bulge > radius` → belly bulges past the tip.\n * - `teardrop` — slender pointed petal. `radius >> bulge`, narrow\n * `width` → long axis with controls converging toward the tip.\n * - `ring` — near-circular loop. `radius ≈ bulge`, modest neck.\n * - `hairpin` — parallel-sided U (legacy). `bulge ≈ width/2` →\n * controls sit directly above the feet, no flare.\n */\nexport const LOOP_CURVE_PRESETS = {\n balloon: { baseOffset: 2, radius: 22, width: 6, bulge: 26 },\n teardrop: { baseOffset: 2, radius: 34, width: 4, bulge: 8 },\n ring: { baseOffset: 2, radius: 20, width: 10, bulge: 20 },\n hairpin: { baseOffset: 2, radius: 28, width: 8, bulge: 4 },\n} as const satisfies Record<string, Required<Pick<LoopCurveOpts, 'baseOffset' | 'radius' | 'width' | 'bulge'>>>;\n\nexport type LoopCurvePresetName = keyof typeof LOOP_CURVE_PRESETS;\n\nfunction sideToAngle(side: LoopCurveSide): number {\n switch (side) {\n case 'top': return -Math.PI / 2;\n case 'top-right': return -Math.PI / 4;\n case 'right': return 0;\n case 'bottom-right': return Math.PI / 4;\n case 'bottom': return Math.PI / 2;\n case 'bottom-left': return 3 * Math.PI / 4;\n case 'left': return Math.PI;\n case 'top-left': return -3 * Math.PI / 4;\n }\n}\n\n/**\n * Self-loop pathStyle — single cubic Bézier \"balloon / petal / teardrop\"\n * drawn between two foot points. Mirrors AntV G6's `loop-curve` placement\n * model: cardinal placements (`top`, `right`, `bottom`, `left`) put both\n * feet on the same edge of the host; diagonal placements (`top-right`,\n * `bottom-right`, `bottom-left`, `top-left`) put the two feet on the two\n * adjacent edges that meet at the named corner.\n *\n * The path style runs in one of two modes depending on the polyline it\n * receives:\n *\n * - **Two-foot mode** (preferred): when `polyline[0]` and `polyline[N-1]`\n * are distinct (chord length > {@link COINCIDENT_EPS}), they are used\n * as the two feet. The caller positions them via anchors — typically\n * an `edge-port` anchor on the source endpoint and another on the\n * target endpoint. The path style only shapes the curve between them.\n *\n * - **Single-pivot mode** (legacy): when the two endpoints coincide\n * (typical when both source and target use the `center` anchor on the\n * same shape), the feet are synthesised from `pivotOffset`,\n * `baseOffset` and `width`. `baseOffset` shifts the foot midpoint\n * along `angle`; `width` separates the feet perpendicular to it.\n * Useful when no edge-port anchor is configured.\n *\n * Geometry (both modes): given two feet `start` and `end`, the tip sits\n * at `chordMid + bloom * radius`, and the two cubic control points are\n * placed at `tip ± chordDir * bulge`. `bulge > chordLen/2` → balloon\n * (controls splayed outward past the feet); `bulge = chordLen/2` →\n * parallel-sided U; `bulge < chordLen/2` → teardrop (controls converge).\n *\n * Pair with `router: 'straight'`. The polyline content between\n * `polyline[0]` and `polyline[N-1]` is ignored.\n *\n * Edge cases:\n * - Polyline shorter than one point: returns `[]`.\n * - `width = 0` in single-pivot mode: feet coincide → closed teardrop\n * cusp; the arrow marker lands on the start point.\n */\nexport const loopCurvePathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 1) return [];\n const o = opts as LoopCurveOpts | undefined;\n const angle = o?.side !== undefined ? sideToAngle(o.side) : (o?.angle ?? DEFAULT_ANGLE);\n const radius = o?.radius ?? DEFAULT_RADIUS;\n const bulge = o?.bulge ?? radius;\n\n const ux = Math.cos(angle);\n const uy = Math.sin(angle);\n\n // Resolve the two feet. Two-foot mode honours the polyline's start /\n // end directly (positioned by anchors); single-pivot mode synthesises\n // them from baseOffset + width.\n const start = polyline[0]!;\n const end = polyline[polyline.length - 1] ?? start;\n const chordDx = end.x - start.x;\n const chordDy = end.y - start.y;\n const chordLen = Math.hypot(chordDx, chordDy);\n\n let sx: number;\n let sy: number;\n let ex: number;\n let ey: number;\n\n if (chordLen > COINCIDENT_EPS) {\n sx = start.x; sy = start.y;\n ex = end.x; ey = end.y;\n } else {\n // Single-pivot mode — derive feet from baseOffset/width/pivotOffset.\n const baseOffset = o?.baseOffset ?? DEFAULT_BASE_OFFSET;\n const width = o?.width ?? DEFAULT_WIDTH;\n const pivotDx = o?.pivotOffset?.dx ?? 0;\n const pivotDy = o?.pivotOffset?.dy ?? 0;\n // Foot midpoint = pivot + pivotOffset + baseOffset along angle.\n const mx = start.x + pivotDx + ux * baseOffset;\n const my = start.y + pivotDy + uy * baseOffset;\n // Feet split perpendicular to angle by ±width/2.\n const px = -uy;\n const py = ux;\n const halfW = width / 2;\n sx = mx - px * halfW; sy = my - py * halfW;\n ex = mx + px * halfW; ey = my + py * halfW;\n }\n\n // Place controls. Tip sits `radius` along bloom direction from chord\n // midpoint. Controls flank the tip ±`bulge` along the chord direction\n // (start→end). When `bulge` exceeds the chord half-length, controls\n // splay past the feet → balloon.\n const midx = (sx + ex) / 2;\n const midy = (sy + ey) / 2;\n const tipx = midx + ux * radius;\n const tipy = midy + uy * radius;\n\n // Chord direction; falls back to perpendicular-to-bloom when chord is\n // degenerate (single-pivot mode with width = 0 — both feet identical).\n let cdx: number;\n let cdy: number;\n const realChordLen = Math.hypot(ex - sx, ey - sy);\n if (realChordLen > COINCIDENT_EPS) {\n cdx = (ex - sx) / realChordLen;\n cdy = (ey - sy) / realChordLen;\n } else {\n cdx = -uy;\n cdy = ux;\n }\n\n const c1x = tipx - cdx * bulge;\n const c1y = tipy - cdy * bulge;\n const c2x = tipx + cdx * bulge;\n const c2y = tipy + cdy * bulge;\n\n const out: PathCommand[] = [\n { kind: 'M', x: sx, y: sy },\n { kind: 'C', c1x, c1y, c2x, c2y, x: ex, y: ey },\n ];\n return out;\n};\n","/**\n * Path-walking utilities. Used by:\n * - `PrimitivesRenderer.hitTest` — needs a polyline approximation of the\n * path for distance-to-segment checks.\n * - `ConnectorBase.paintMarkers` — needs the tangent angle at the source /\n * target endpoints to orient marker shapes.\n * - Any future connector decoration that walks arc length (e.g. label-along-\n * path). Static / glow / halo decorations don't sample — they call\n * `connector.paintInto(...)` for native-rendered silhouettes.\n *\n * For v0 the only router is `straight` (just `[M, L]`), so the sampling /\n * tangent paths are degenerate. The functions are written to handle the full\n * `Path` type so additional router kinds drop in without changes.\n */\n\nimport type { Path, PathCommand, Point, Rect, Vec2 } from '../../../specs';\n\n/** Substeps per Q/C segment when densifying. Higher = smoother polyline. */\nconst QUAD_STEPS = 12;\nconst CUBIC_STEPS = 16;\n\n/**\n * Densify a `Path` into a flat polyline. Lines emit two endpoints per\n * segment; quadratic / cubic curves are sampled with fixed substep counts.\n * Returns at least the move-to point when the path has only one command.\n */\nexport function samplePath(path: Path): Point[] {\n const out: Point[] = [];\n if (path.length === 0) return out;\n\n let cx = 0;\n let cy = 0;\n\n for (const cmd of path) {\n switch (cmd.kind) {\n case 'M':\n out.push({ x: cmd.x, y: cmd.y });\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'L':\n out.push({ x: cmd.x, y: cmd.y });\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'Q':\n for (let i = 1; i <= QUAD_STEPS; i++) {\n const t = i / QUAD_STEPS;\n const mt = 1 - t;\n out.push({\n x: mt * mt * cx + 2 * mt * t * cmd.cx + t * t * cmd.x,\n y: mt * mt * cy + 2 * mt * t * cmd.cy + t * t * cmd.y,\n });\n }\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'C':\n for (let i = 1; i <= CUBIC_STEPS; i++) {\n const t = i / CUBIC_STEPS;\n const mt = 1 - t;\n out.push({\n x: mt * mt * mt * cx + 3 * mt * mt * t * cmd.c1x + 3 * mt * t * t * cmd.c2x + t * t * t * cmd.x,\n y: mt * mt * mt * cy + 3 * mt * mt * t * cmd.c1y + 3 * mt * t * t * cmd.c2y + t * t * t * cmd.y,\n });\n }\n cx = cmd.x;\n cy = cmd.y;\n break;\n }\n }\n\n return out;\n}\n\n/**\n * Compute the tangent unit vector at `t ∈ [0, 1]` along the path.\n * For v0 we only need `t = 0` (source) and `t = 1` (target) for marker\n * orientation; intermediate `t` is sampled via `samplePath` for now.\n */\nexport function tangentAt(path: Path, t: number): Vec2 {\n if (path.length < 2) return { x: 1, y: 0 };\n\n if (t <= 0) return tangentAtStart(path);\n if (t >= 1) return tangentAtEnd(path);\n\n // Approximate intermediate t via sampled polyline.\n const samples = samplePath(path);\n if (samples.length < 2) return { x: 1, y: 0 };\n const idx = Math.min(samples.length - 2, Math.floor(t * (samples.length - 1)));\n const a = samples[idx]!;\n const b = samples[idx + 1]!;\n return normalize(b.x - a.x, b.y - a.y);\n}\n\n/**\n * Combined point + unit-tangent sample at parameter `t ∈ [0, 1]` along the\n * path. Used by labels-along-path and any other decoration that needs both\n * the location and the local direction at the same parameter (e.g. for\n * `autoRotate`). Cheaper than calling `samplePath` + `tangentAt` separately\n * because it walks the polyline once.\n *\n * `t` is fractional in arc-length space — the function picks the segment of\n * the densified polyline whose cumulative length most closely matches `t *\n * totalLength` and linearly interpolates inside it. For most practical path\n * kinds this matches an analytical sample to within a pixel; orthogonal\n * paths reproduce segment endpoints exactly.\n */\nexport function samplePathAt(path: Path, t: number): { point: Point; tangent: Vec2 } {\n const samples = samplePath(path);\n if (samples.length === 0) return { point: { x: 0, y: 0 }, tangent: { x: 1, y: 0 } };\n if (samples.length === 1) return { point: samples[0]!, tangent: { x: 1, y: 0 } };\n\n // Compute cumulative arc length once.\n let total = 0;\n const cum = new Array<number>(samples.length);\n cum[0] = 0;\n for (let i = 1; i < samples.length; i++) {\n const a = samples[i - 1]!;\n const b = samples[i]!;\n total += Math.hypot(b.x - a.x, b.y - a.y);\n cum[i] = total;\n }\n\n if (total <= 0) {\n return { point: samples[0]!, tangent: { x: 1, y: 0 } };\n }\n\n const clamped = t <= 0 ? 0 : t >= 1 ? 1 : t;\n const target = clamped * total;\n\n // Binary search for the segment containing `target`.\n let lo = 0;\n let hi = samples.length - 1;\n while (lo < hi - 1) {\n const mid = (lo + hi) >>> 1;\n if (cum[mid]! <= target) lo = mid;\n else hi = mid;\n }\n const a = samples[lo]!;\n const b = samples[lo + 1]!;\n const segLen = cum[lo + 1]! - cum[lo]!;\n const u = segLen > 0 ? (target - cum[lo]!) / segLen : 0;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n return {\n point: { x: a.x + dx * u, y: a.y + dy * u },\n tangent: normalize(dx, dy),\n };\n}\n\n/** AABB of the path's anchor + control points. Used by hit-test bbox indexing. */\nexport function pathBounds(path: Path): Rect {\n if (path.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visit = (x: number, y: number): void => {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n };\n for (const cmd of path) {\n switch (cmd.kind) {\n case 'M':\n case 'L':\n visit(cmd.x, cmd.y);\n break;\n case 'Q':\n visit(cmd.cx, cmd.cy);\n visit(cmd.x, cmd.y);\n break;\n case 'C':\n visit(cmd.c1x, cmd.c1y);\n visit(cmd.c2x, cmd.c2y);\n visit(cmd.x, cmd.y);\n break;\n }\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/**\n * Pull the path's start / end anchors inward by the requested arc-length\n * insets so the connector body stops short of where its markers will be\n * drawn. Markers themselves still anchor at the *original* endpoints (their\n * tips touch the target) — only the body is shortened.\n *\n * Correctness:\n * - `L` segments are trimmed in closed form (exact).\n * - `Q` / `C` segments are trimmed by walking arc length over a fine\n * sub-step table, refining the parameter `t` between bracketing samples,\n * and **De Casteljau subdividing** the curve at `t`. The kept half is\n * emitted as a new `Q` / `C` command, preserving correct curvature on\n * tight bends — chord-along-tangent approximation would diverge.\n * - When an inset exceeds the trailing segment's arc length, the segment\n * is consumed entirely and the trim continues into the prior segment.\n *\n * v0 only ships the `straight` router, so curve trimming is forward-looking\n * scaffolding for the upcoming `bezier` / `orthogonal` routers.\n */\nexport function trimPathEnds(path: Path, startInset: number, endInset: number): Path {\n if (path.length < 2) return path;\n if (startInset <= 0 && endInset <= 0) return path;\n\n let result: PathCommand[] = path.slice();\n\n if (endInset > 0) {\n result = trimPathEnd(result, endInset);\n if (result.length < 2) return result;\n }\n\n if (startInset > 0) {\n result = trimPathStart(result, startInset);\n }\n\n return result;\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\n/** Substeps used during arc-length trim — finer than display sampling. */\nconst TRIM_QUAD_STEPS = 24;\nconst TRIM_CUBIC_STEPS = 32;\n\n/**\n * Trim `remaining` pixels from the end of the path, consuming whole segments\n * when they're shorter than what's left to remove. Returns a fresh\n * `PathCommand[]`. If the inset exceeds the path's total length, returns the\n * leading `M` (degenerate but well-formed).\n */\nfunction trimPathEnd(path: PathCommand[], remaining: number): PathCommand[] {\n let work = path.slice();\n while (work.length >= 2 && remaining > 0) {\n const tail = work[work.length - 1]!;\n const prev = anchorBefore(work, work.length - 1);\n const segLen = segmentLength(prev, tail);\n\n if (segLen <= 0) {\n // Degenerate segment — drop it and continue.\n work.pop();\n continue;\n }\n\n if (remaining >= segLen) {\n // Consume the whole segment and continue trimming into the prior one.\n remaining -= segLen;\n work.pop();\n continue;\n }\n\n // Partial trim: clip the tail at arc-length distance `segLen - remaining`\n // from `prev`. The result is a fresh segment whose end anchor sits at\n // that interior point.\n const keepLen = segLen - remaining;\n work[work.length - 1] = clipSegmentEnd(prev, tail, keepLen);\n remaining = 0;\n }\n return work;\n}\n\n/**\n * Trim `remaining` pixels from the start of the path. Walks forward from\n * the leading `M`, dropping commands whose arc length is fully consumed and\n * partially clipping the first segment that survives.\n */\nfunction trimPathStart(path: PathCommand[], remaining: number): PathCommand[] {\n if (path.length < 2) return path;\n const first = path[0];\n if (!first || first.kind !== 'M') return path;\n\n let cursor: Point = { x: first.x, y: first.y };\n let i = 1;\n while (i < path.length && remaining > 0) {\n const seg = path[i]!;\n const segLen = segmentLength(cursor, seg);\n\n if (segLen <= 0) {\n // Degenerate — advance cursor (without dropping; preserves anchor flow).\n cursor = endpointOf(seg, cursor);\n i++;\n continue;\n }\n\n if (remaining >= segLen) {\n remaining -= segLen;\n cursor = endpointOf(seg, cursor);\n i++;\n continue;\n }\n\n // Partial trim: split at arc-length `remaining` from cursor and keep\n // the back half. The new `M` lands at the split point.\n const split = clipSegmentStart(cursor, seg, remaining);\n const head: PathCommand[] = [{ kind: 'M', x: split.start.x, y: split.start.y }, split.tail];\n return head.concat(path.slice(i + 1));\n }\n\n // The inset consumed every segment — collapse to a bare moveTo at the\n // last anchor we walked through.\n return [{ kind: 'M', x: cursor.x, y: cursor.y }];\n}\n\n/**\n * Replace `seg` with a new segment that runs from `start` to the point on\n * `seg` at arc length `keepLen` (measured from `start`). For `Q` / `C`\n * segments, sub-divides via De Casteljau at the parameter t found by walking\n * the sampled arc-length table.\n */\nfunction clipSegmentEnd(start: Point, seg: PathCommand, keepLen: number): PathCommand {\n switch (seg.kind) {\n case 'L': {\n const dx = seg.x - start.x;\n const dy = seg.y - start.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) return seg;\n const u = keepLen / len;\n return { kind: 'L', x: start.x + dx * u, y: start.y + dy * u };\n }\n case 'Q': {\n const t = quadParamAtArcLength(start, seg, keepLen);\n const split = subdivideQuad(start, seg, t);\n return { kind: 'Q', cx: split.head.cx, cy: split.head.cy, x: split.head.x, y: split.head.y };\n }\n case 'C': {\n const t = cubicParamAtArcLength(start, seg, keepLen);\n const split = subdivideCubic(start, seg, t);\n return {\n kind: 'C',\n c1x: split.head.c1x, c1y: split.head.c1y,\n c2x: split.head.c2x, c2y: split.head.c2y,\n x: split.head.x, y: split.head.y,\n };\n }\n case 'M':\n return seg;\n }\n}\n\n/**\n * Split `seg` at arc length `dropLen` from `start` and return both halves,\n * along with the new start anchor for the back half. Used by start-trim.\n */\nfunction clipSegmentStart(\n start: Point,\n seg: PathCommand,\n dropLen: number,\n): { start: Point; tail: PathCommand } {\n switch (seg.kind) {\n case 'L': {\n const dx = seg.x - start.x;\n const dy = seg.y - start.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) return { start, tail: seg };\n const u = dropLen / len;\n const splitPoint = { x: start.x + dx * u, y: start.y + dy * u };\n return { start: splitPoint, tail: { kind: 'L', x: seg.x, y: seg.y } };\n }\n case 'Q': {\n const t = quadParamAtArcLength(start, seg, dropLen);\n const split = subdivideQuad(start, seg, t);\n return {\n start: { x: split.head.x, y: split.head.y },\n tail: { kind: 'Q', cx: split.tail.cx, cy: split.tail.cy, x: split.tail.x, y: split.tail.y },\n };\n }\n case 'C': {\n const t = cubicParamAtArcLength(start, seg, dropLen);\n const split = subdivideCubic(start, seg, t);\n return {\n start: { x: split.head.x, y: split.head.y },\n tail: {\n kind: 'C',\n c1x: split.tail.c1x, c1y: split.tail.c1y,\n c2x: split.tail.c2x, c2y: split.tail.c2y,\n x: split.tail.x, y: split.tail.y,\n },\n };\n }\n case 'M':\n return { start, tail: seg };\n }\n}\n\n/**\n * Total arc length of a single segment from `start` to its endpoint.\n * Straight segments use Euclidean distance; curved segments accumulate\n * chord lengths over a fixed substep count.\n */\nfunction segmentLength(start: Point, seg: PathCommand): number {\n switch (seg.kind) {\n case 'L':\n return Math.hypot(seg.x - start.x, seg.y - start.y);\n case 'Q': {\n let total = 0;\n let px = start.x, py = start.y;\n for (let i = 1; i <= TRIM_QUAD_STEPS; i++) {\n const t = i / TRIM_QUAD_STEPS;\n const mt = 1 - t;\n const x = mt * mt * start.x + 2 * mt * t * seg.cx + t * t * seg.x;\n const y = mt * mt * start.y + 2 * mt * t * seg.cy + t * t * seg.y;\n total += Math.hypot(x - px, y - py);\n px = x; py = y;\n }\n return total;\n }\n case 'C': {\n let total = 0;\n let px = start.x, py = start.y;\n for (let i = 1; i <= TRIM_CUBIC_STEPS; i++) {\n const t = i / TRIM_CUBIC_STEPS;\n const mt = 1 - t;\n const x = mt * mt * mt * start.x + 3 * mt * mt * t * seg.c1x + 3 * mt * t * t * seg.c2x + t * t * t * seg.x;\n const y = mt * mt * mt * start.y + 3 * mt * mt * t * seg.c1y + 3 * mt * t * t * seg.c2y + t * t * t * seg.y;\n total += Math.hypot(x - px, y - py);\n px = x; py = y;\n }\n return total;\n }\n case 'M':\n return 0;\n }\n}\n\nfunction endpointOf(seg: PathCommand, fallback: Point): Point {\n if (seg.kind === 'M' || seg.kind === 'L' || seg.kind === 'Q' || seg.kind === 'C') {\n return { x: seg.x, y: seg.y };\n }\n return fallback;\n}\n\n/** Walk the quadratic and find `t` where cumulative arc length ≈ targetLen. */\nfunction quadParamAtArcLength(\n start: Point,\n seg: { cx: number; cy: number; x: number; y: number },\n targetLen: number,\n): number {\n let prevX = start.x, prevY = start.y;\n let acc = 0;\n for (let i = 1; i <= TRIM_QUAD_STEPS; i++) {\n const t = i / TRIM_QUAD_STEPS;\n const mt = 1 - t;\n const x = mt * mt * start.x + 2 * mt * t * seg.cx + t * t * seg.x;\n const y = mt * mt * start.y + 2 * mt * t * seg.cy + t * t * seg.y;\n const step = Math.hypot(x - prevX, y - prevY);\n if (acc + step >= targetLen) {\n const frac = step === 0 ? 0 : (targetLen - acc) / step;\n const tPrev = (i - 1) / TRIM_QUAD_STEPS;\n return tPrev + (t - tPrev) * frac;\n }\n acc += step;\n prevX = x; prevY = y;\n }\n return 1;\n}\n\n/** Walk the cubic and find `t` where cumulative arc length ≈ targetLen. */\nfunction cubicParamAtArcLength(\n start: Point,\n seg: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number },\n targetLen: number,\n): number {\n let prevX = start.x, prevY = start.y;\n let acc = 0;\n for (let i = 1; i <= TRIM_CUBIC_STEPS; i++) {\n const t = i / TRIM_CUBIC_STEPS;\n const mt = 1 - t;\n const x = mt * mt * mt * start.x + 3 * mt * mt * t * seg.c1x + 3 * mt * t * t * seg.c2x + t * t * t * seg.x;\n const y = mt * mt * mt * start.y + 3 * mt * mt * t * seg.c1y + 3 * mt * t * t * seg.c2y + t * t * t * seg.y;\n const step = Math.hypot(x - prevX, y - prevY);\n if (acc + step >= targetLen) {\n const frac = step === 0 ? 0 : (targetLen - acc) / step;\n const tPrev = (i - 1) / TRIM_CUBIC_STEPS;\n return tPrev + (t - tPrev) * frac;\n }\n acc += step;\n prevX = x; prevY = y;\n }\n return 1;\n}\n\n/**\n * De Casteljau subdivision for a quadratic Bézier at parameter `t`.\n * Returns the two halves: `head` runs from `start` to the split point,\n * `tail` runs from the split point to the original endpoint. Each half is\n * itself a valid quadratic.\n */\nfunction subdivideQuad(\n start: Point,\n seg: { cx: number; cy: number; x: number; y: number },\n t: number,\n): {\n head: { cx: number; cy: number; x: number; y: number };\n tail: { cx: number; cy: number; x: number; y: number };\n} {\n const p0 = start, p1 = { x: seg.cx, y: seg.cy }, p2 = { x: seg.x, y: seg.y };\n const a = lerp(p0, p1, t);\n const b = lerp(p1, p2, t);\n const m = lerp(a, b, t);\n return {\n head: { cx: a.x, cy: a.y, x: m.x, y: m.y },\n tail: { cx: b.x, cy: b.y, x: p2.x, y: p2.y },\n };\n}\n\n/**\n * De Casteljau subdivision for a cubic Bézier at parameter `t`.\n * Returns the two halves as cubic segments.\n */\nfunction subdivideCubic(\n start: Point,\n seg: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number },\n t: number,\n): {\n head: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number };\n tail: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number };\n} {\n const p0 = start;\n const p1 = { x: seg.c1x, y: seg.c1y };\n const p2 = { x: seg.c2x, y: seg.c2y };\n const p3 = { x: seg.x, y: seg.y };\n const a = lerp(p0, p1, t);\n const b = lerp(p1, p2, t);\n const c = lerp(p2, p3, t);\n const d = lerp(a, b, t);\n const e = lerp(b, c, t);\n const m = lerp(d, e, t);\n return {\n head: { c1x: a.x, c1y: a.y, c2x: d.x, c2y: d.y, x: m.x, y: m.y },\n tail: { c1x: e.x, c1y: e.y, c2x: c.x, c2y: c.y, x: p3.x, y: p3.y },\n };\n}\n\nfunction lerp(a: Point, b: Point, t: number): Point {\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n}\n\nfunction tangentAtStart(path: Path): Vec2 {\n // Find the first non-M command; tangent points from M's anchor toward it.\n const m = path[0];\n if (!m || m.kind !== 'M') return { x: 1, y: 0 };\n const next = path[1];\n if (!next) return { x: 1, y: 0 };\n switch (next.kind) {\n case 'L': {\n const to = distinctAnchorAfter(path, 1, m);\n return normalize(to.x - m.x, to.y - m.y);\n }\n case 'Q':\n return normalize(next.cx - m.x, next.cy - m.y);\n case 'C':\n return normalize(next.c1x - m.x, next.c1y - m.y);\n default:\n return { x: 1, y: 0 };\n }\n}\n\nfunction tangentAtEnd(path: Path): Vec2 {\n const last = path[path.length - 1];\n if (!last) return { x: 1, y: 0 };\n // Need the prior point (or control point) to compute the incoming tangent.\n const prevAnchor = anchorBefore(path, path.length - 1);\n switch (last.kind) {\n case 'M':\n return { x: 1, y: 0 };\n case 'L': {\n // Walk back to the last *distinct* anchor rather than trusting the\n // immediately-preceding one — see `distinctAnchorBefore`.\n const from = distinctAnchorBefore(path, path.length - 1, last);\n return normalize(last.x - from.x, last.y - from.y);\n }\n case 'Q': {\n // Tangent at t=1 of a quadratic is 2·(P2 − P1). Degenerate when the\n // control point coincides with the endpoint — walk back one leg.\n const dx = last.x - last.cx;\n const dy = last.y - last.cy;\n const chordDx = last.x - prevAnchor.x;\n const chordDy = last.y - prevAnchor.y;\n if (isDegenerateLeg(dx, dy, chordDx, chordDy)) {\n return normalize(chordDx, chordDy);\n }\n return normalize(dx, dy);\n }\n case 'C': {\n // Tangent at t=1 of a cubic is 3·(P3 − P2). When the c2 → endpoint\n // leg is vanishingly short relative to the c1 → c2 leg (e.g. a polar\n // d3.linkRadial curve whose endpoints sit at near-equal radii from\n // the polar origin), that direction is ill-conditioned and bears no\n // resemblance to the curve's visual approach. Fall back to the\n // c1 → endpoint direction, which carries the dominant angular sweep.\n const dx = last.x - last.c2x;\n const dy = last.y - last.c2y;\n const c1dx = last.x - last.c1x;\n const c1dy = last.y - last.c1y;\n if (isDegenerateLeg(dx, dy, c1dx, c1dy)) {\n if (c1dx !== 0 || c1dy !== 0) return normalize(c1dx, c1dy);\n return normalize(last.x - prevAnchor.x, last.y - prevAnchor.y);\n }\n return normalize(dx, dy);\n }\n }\n}\n\n// A terminal Bézier handle is \"degenerate\" when its length is less than 1%\n// of the preceding control-polygon leg. Compared squared to avoid sqrts.\nfunction isDegenerateLeg(\n legDx: number, legDy: number,\n refDx: number, refDy: number,\n): boolean {\n const legSq = legDx * legDx + legDy * legDy;\n const refSq = refDx * refDx + refDy * refDy;\n return refSq > 0 && legSq * 10000 < refSq;\n}\n\nfunction anchorBefore(path: Path, idx: number): Point {\n // Return the anchor point reached after executing path[0..idx-1].\n let x = 0, y = 0;\n for (let i = 0; i < idx; i++) {\n const c: PathCommand = path[i]!;\n if (c.kind === 'M' || c.kind === 'L' || c.kind === 'Q' || c.kind === 'C') {\n x = c.x;\n y = c.y;\n }\n }\n return { x, y };\n}\n\n/**\n * Nearest anchor **before** `idx` that is not coincident with `to`.\n *\n * A zero-length terminal segment is easy to produce: any layout that pins an\n * endpoint to the same point it already emitted as its final waypoint leaves\n * two identical anchors at the end of the polyline. Differencing those yields\n * `(0, 0)`, and {@link normalize} then answers its `{ x: 1, y: 0 }` fallback —\n * so a marker silently points due east instead of along the path, which reads\n * as an arrowhead at the wrong angle (and, against a node that paints above\n * connectors, as a half-occluded one). Walking back to the last distinct\n * anchor keeps the direction honest without changing any non-degenerate case.\n *\n * Falls back to {@link anchorBefore} when every prior anchor is coincident —\n * a genuinely zero-length path, where any direction is equally meaningless.\n */\nfunction distinctAnchorBefore(path: Path, idx: number, to: Point): Point {\n for (let i = idx - 1; i >= 0; i--) {\n const c: PathCommand = path[i]!;\n if (c.kind !== 'M' && c.kind !== 'L' && c.kind !== 'Q' && c.kind !== 'C') continue;\n if (c.x !== to.x || c.y !== to.y) return { x: c.x, y: c.y };\n }\n return anchorBefore(path, idx);\n}\n\n/** Mirror of {@link distinctAnchorBefore} for the leading tangent. */\nfunction distinctAnchorAfter(path: Path, idx: number, from: Point): Point {\n for (let i = idx; i < path.length; i++) {\n const c: PathCommand = path[i]!;\n if (c.kind !== 'M' && c.kind !== 'L' && c.kind !== 'Q' && c.kind !== 'C') continue;\n if (c.x !== from.x || c.y !== from.y) return { x: c.x, y: c.y };\n }\n return from;\n}\n\nfunction normalize(dx: number, dy: number): Vec2 {\n const len = Math.hypot(dx, dy);\n if (len === 0) return { x: 1, y: 0 };\n return { x: dx / len, y: dy / len };\n}\n\n/**\n * Squared minimum distance from `(px, py)` to any segment of the polyline.\n * Squared (no sqrt) so callers can compare against a squared tolerance —\n * faster + branch-free for the common no-hit case.\n */\nexport function distanceToPolylineSq(\n poly: ReadonlyArray<Point>,\n px: number,\n py: number,\n): number {\n if (poly.length < 2) return Infinity;\n let best = Infinity;\n for (let i = 0; i < poly.length - 1; i++) {\n const a = poly[i]!;\n const b = poly[i + 1]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n let t = lenSq === 0 ? 0 : ((px - a.x) * dx + (py - a.y) * dy) / lenSq;\n if (t < 0) t = 0;\n else if (t > 1) t = 1;\n const cx = a.x + dx * t;\n const cy = a.y + dy * t;\n const ex = px - cx;\n const ey = py - cy;\n const d = ex * ex + ey * ey;\n if (d < best) best = d;\n }\n return best;\n}\n","/**\n * Pure placement math for badges. Given the host's world-space AABB and the\n * badge's local-space AABB, resolve the world-space `(x, y)` to put on the\n * badge spec so that a chosen point on the badge's AABB lands at a chosen\n * point on the host's AABB (plus an optional pixel offset).\n *\n * No Pixi imports. Trivially testable.\n *\n * The maths splits cleanly along two axes:\n * 1. **Host anchor** — which point on the host AABB is the target. Driven by\n * `BadgePlacement` (8 named points around the host).\n * 2. **Badge origin** — which point on the badge AABB lands at that anchor.\n * Driven by the optional `origin` field. Defaults to the *mirror* of the\n * placement so the badge sits fully outside the host edge.\n */\n\nimport type { Rect } from '../../../specs';\nimport type { BadgeOptions, BadgePlacement, NamedBadgePlacement } from './types';\n\n/**\n * Returns the world-space anchor point for `placement`. Named placements\n * resolve against `hostBounds` (corner or edge midpoint of the AABB); the\n * raw `{ x, y }` variant is the world-space point itself, with `hostBounds`\n * ignored.\n */\nexport function placementToHostAnchor(\n hostBounds: Rect,\n placement: BadgePlacement,\n): { x: number; y: number } {\n if (typeof placement === 'object') {\n return { x: placement.x, y: placement.y };\n }\n return namedPlacementToAnchor(hostBounds, placement);\n}\n\n/**\n * Returns the world-space point on `bounds` named by a {@link\n * NamedBadgePlacement}. Edge names sit at the midpoint of that edge; corner\n * names at the corner. Used by both host-anchor resolution and badge-origin\n * resolution (with the badge's local AABB as the bounds).\n */\nfunction namedPlacementToAnchor(\n bounds: Rect,\n placement: NamedBadgePlacement,\n): { x: number; y: number } {\n const { x, y, width: w, height: h } = bounds;\n switch (placement) {\n case 'top': return { x: x + w / 2, y };\n case 'bottom': return { x: x + w / 2, y: y + h };\n case 'left': return { x, y: y + h / 2 };\n case 'right': return { x: x + w, y: y + h / 2 };\n case 'top-left': return { x, y };\n case 'top-right': return { x: x + w, y };\n case 'bottom-left': return { x, y: y + h };\n case 'bottom-right': return { x: x + w, y: y + h };\n }\n}\n\n/**\n * Returns the point on the badge's local AABB that should land at the host\n * anchor, given the chosen origin. The default (omitted origin) is the\n * mirror of `placement` so the badge sits fully outside the host edge.\n * When `placement` is a raw `{x, y}` point with no inherent mirror, the\n * default falls back to `'center'`.\n */\nexport function originToBadgeLocal(\n badgeLocalBounds: Rect,\n placement: BadgePlacement,\n origin: BadgeOptions['origin'],\n): { x: number; y: number } {\n if (origin === 'center' || (origin === undefined && typeof placement === 'object')) {\n return {\n x: badgeLocalBounds.x + badgeLocalBounds.width / 2,\n y: badgeLocalBounds.y + badgeLocalBounds.height / 2,\n };\n }\n const point = origin ?? mirrorPlacement(placement as NamedBadgePlacement);\n // Reuse named-point math — it's the same \"point on an AABB\" computation,\n // just applied to the badge's local AABB instead of the host's world AABB.\n return namedPlacementToAnchor(badgeLocalBounds, point);\n}\n\n/**\n * Mirror of a named placement across the host centre. `top-right` ↔\n * `bottom-left`, `right` ↔ `left`, and so on. Used as the default `origin`\n * so a badge with `placement: 'top-right'` sits with its `bottom-left`\n * corner at the host's top-right corner — i.e. the badge nests fully\n * outside the host edge. Only defined for {@link NamedBadgePlacement};\n * raw `{x, y}` placements have no symmetric counterpart on the host AABB.\n */\nexport function mirrorPlacement(p: NamedBadgePlacement): NamedBadgePlacement {\n switch (p) {\n case 'top': return 'bottom';\n case 'bottom': return 'top';\n case 'left': return 'right';\n case 'right': return 'left';\n case 'top-left': return 'bottom-right';\n case 'top-right': return 'bottom-left';\n case 'bottom-left': return 'top-right';\n case 'bottom-right': return 'top-left';\n }\n}\n\n/**\n * Resolve the badge spec's `(x, y)` so that the chosen origin point on the\n * badge AABB lands at the chosen anchor point on the host AABB, plus the\n * caller's pixel offset.\n *\n * The badge spec's `(x, y)` represents the badge's *local-origin* in world\n * space (e.g. circle centre, rect top-left). Local AABB origin is at\n * `(badgeLocalBounds.x, badgeLocalBounds.y)` — for a circle these are\n * negative (`-r, -r`); for a rect they are `(0, 0)`. We compute the badge's\n * `(x, y)` such that the chosen origin point — at\n * `(specX + originLocal.x, specY + originLocal.y)` in world space — equals\n * the host anchor + offset.\n */\nexport function resolveBadgePosition(\n hostWorldBounds: Rect,\n badgeLocalBounds: Rect,\n options: BadgeOptions,\n): { x: number; y: number } {\n // Shape-host dispatch: `options.placement` is statically widened to\n // `BadgePlacement | ConnectorBadgePlacement`. `setBadge` routes connector\n // hosts away from this function, so by construction the runtime placement\n // is always a `BadgePlacement` here. The cast collapses the unused union\n // arm at the type level only.\n const placement = options.placement as BadgePlacement;\n const anchor = placementToHostAnchor(hostWorldBounds, placement);\n const originLocal = originToBadgeLocal(\n badgeLocalBounds,\n placement,\n options.origin,\n );\n return {\n x: anchor.x + (options.offsetX ?? 0) - originLocal.x,\n y: anchor.y + (options.offsetY ?? 0) - originLocal.y,\n };\n}\n","/**\n * Pure placement math for connector-hosted badges. Given a router-resolved\n * `Path` and the badge's local-space AABB, resolve the world-space `(x, y)`\n * (plus optional rotation) so that a chosen point on the badge's AABB lands\n * on a chosen anchor along the path — `'start'` / `'middle'` / `'end'` or\n * an arbitrary arc-length `t ∈ [0, 1]`.\n *\n * No Pixi imports. The math mirrors {@link LabelConnectorDecoration} so\n * connector badges and connector labels share the same arc-length walk.\n */\n\nimport type { Path } from '../../../specs';\nimport type { BadgeOptions, ConnectorBadgePlacement } from './types';\nimport { samplePathAt } from '../connectors/pathSampling';\nimport { originToBadgeLocal } from './placement';\nimport type { Rect } from '../../../specs';\n\n/**\n * Map a {@link ConnectorBadgePlacement} to an arc-length parameter `t ∈\n * [0, 1]`. Numbers outside the closed unit interval are clamped.\n */\nexport function resolveConnectorT(placement: ConnectorBadgePlacement): number {\n if (typeof placement === 'number') {\n if (placement <= 0) return 0;\n if (placement >= 1) return 1;\n return placement;\n }\n switch (placement) {\n case 'start':\n return 0;\n case 'middle':\n return 0.5;\n case 'end':\n return 1;\n }\n}\n\n/**\n * Resolve the badge spec's `(x, y)` (and optional `rotation`) so that the\n * chosen origin point on the badge's local AABB lands at the path-anchor\n * defined by `options.placement`. The origin defaults to `'center'` for\n * connector hosts (badge centres on the path point); shape-style mirror\n * defaults don't apply here because the path has no \"outside edge\".\n *\n * The returned `rotation` is `0` unless {@link BadgeOptions.autoRotate} is\n * `true`. When auto-rotating with `keepUpright !== false` (the default),\n * tangents whose angle exceeds `±90°` are flipped by `π` so the badge's\n * top edge keeps facing the viewer.\n */\n/**\n * Per-endpoint extra clearance added to the auto-shift when\n * {@link BadgeOptions.placement} is `'start'` or `'end'`. The renderer\n * passes the source / target marker length here (so the badge clears the\n * arrowhead, not just the trimmed path endpoint) plus a small visual gap.\n *\n * Numeric placements (`0`, `1`, raw `t`) ignore this — they're the \"raw\n * arc-length\" escape hatch.\n */\nexport interface ConnectorBadgeEndpointClearance {\n readonly source: number;\n readonly target: number;\n}\n\n/** Default pixel gap inserted between an endpoint-anchored badge and the\n * endpoint shape's silhouette (or, when a marker is present, the marker's\n * far tip). Tunable by callers via the `clearance` parameter — this is\n * just the engine-side floor when the renderer doesn't know better. */\nexport const DEFAULT_ENDPOINT_BADGE_GAP_PX = 8;\n\nexport function resolveConnectorBadgePosition(\n path: Path,\n badgeLocalBounds: Rect,\n options: BadgeOptions,\n clearance: ConnectorBadgeEndpointClearance = { source: 0, target: 0 },\n): { x: number; y: number; rotation: number } {\n const placement = options.placement as ConnectorBadgePlacement;\n const t = resolveConnectorT(placement);\n const sample = samplePathAt(path, t);\n\n let baseX = sample.point.x;\n let baseY = sample.point.y;\n\n // Endpoint-clearance for the named `'start'` / `'end'` placements.\n //\n // The routed path stops at the source / target shape's *silhouette*, so a\n // badge centred on `t=0` or `t=1` would half-overlap the endpoint shape.\n // For the named placements we treat that overlap as a bug: shift the\n // badge tangentially by its own tangent-aligned half-extent so its\n // line-facing edge kisses the silhouette from outside, leaving the\n // endpoint shape un-occluded.\n //\n // Numeric placement (`0`, `1`, or any `t ∈ [0,1]`) keeps the raw\n // arc-length contract — use `placement: 0` / `placement: 1` when you\n // explicitly want a badge anchored at the silhouette point.\n if (placement === 'start' || placement === 'end') {\n // L1-norm projection of the badge's local half-extents onto the\n // tangent. Conservative for axis-aligned badges; exact when the badge\n // is rotated to align with the tangent (autoRotate).\n const halfTangentExtent =\n Math.abs(sample.tangent.x) * (badgeLocalBounds.width / 2) +\n Math.abs(sample.tangent.y) * (badgeLocalBounds.height / 2);\n // Per-endpoint extra clearance — marker length + a visual gap so the\n // arrowhead doesn't end up tucked under the badge. The renderer\n // computes these from `markerInsetFor(...)` + the engine-default gap.\n const extra = placement === 'start' ? clearance.source : clearance.target;\n // `'start'` at t=0: tangent points *forward* (toward target). Pushing\n // forward moves the badge off the source silhouette toward the line.\n // `'end'` at t=1: tangent still points forward (continuing past target).\n // Pushing backward moves the badge off the target silhouette toward\n // the line.\n const dir = placement === 'start' ? 1 : -1;\n const totalShift = (halfTangentExtent + extra) * dir;\n baseX += sample.tangent.x * totalShift;\n baseY += sample.tangent.y * totalShift;\n }\n\n // Tangent-space `pathOffset` — additional shift along the tangent on top\n // of any endpoint-clearance, so users can fine-tune.\n const pathOffset = options.pathOffset ?? 0;\n if (pathOffset !== 0) {\n baseX += sample.tangent.x * pathOffset;\n baseY += sample.tangent.y * pathOffset;\n }\n\n // Rotation — atan2 of the tangent vector. `keepUpright` flips the badge\n // by π when the tangent points \"downwards\" so text decorations stay\n // readable on every edge orientation.\n let rotation = 0;\n if (options.autoRotate === true) {\n let theta = Math.atan2(sample.tangent.y, sample.tangent.x);\n if (options.keepUpright !== false) {\n if (theta > Math.PI / 2) theta -= Math.PI;\n else if (theta < -Math.PI / 2) theta += Math.PI;\n }\n rotation = theta;\n }\n\n // Connector hosts default `origin` to `'center'` (badge sits *on* the\n // path point); shape-style mirror defaults have no analog here. Reuse\n // {@link originToBadgeLocal} — passing `'top'` as a sentinel placement\n // is fine because the function only consults `placement` when the\n // origin is omitted, and we always supply `'center'` as the fallback.\n const originLocal = originToBadgeLocal(\n badgeLocalBounds,\n 'top',\n options.origin ?? 'center',\n );\n\n // Screen-space offset applied after rotation so the badge keeps its\n // intended offset relative to the path's local frame.\n const offsetX = options.offsetX ?? 0;\n const offsetY = options.offsetY ?? 0;\n let rotatedOffsetX = offsetX;\n let rotatedOffsetY = offsetY;\n if (rotation !== 0 && (offsetX !== 0 || offsetY !== 0)) {\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n rotatedOffsetX = offsetX * cos - offsetY * sin;\n rotatedOffsetY = offsetX * sin + offsetY * cos;\n }\n\n return {\n x: baseX + rotatedOffsetX - originLocal.x,\n y: baseY + rotatedOffsetY - originLocal.y,\n rotation,\n };\n}\n","import type { LabelSizePolicy } from '../../../contracts/IElementRenderer';\n\n/**\n * The scale to draw a label at so its on-screen font size follows `policy`.\n *\n * Positional arguments, not an options object: the renderer calls this once per\n * label per zoom-changed frame, so it must not allocate.\n *\n * @param fontSize The label's authored font size — its on-screen size at zoom `1`.\n * @param zoom Current camera zoom (`camera.scale`).\n * @param hostScale Visual scale the label inherits from its host before any label\n * scaling — e.g. a node-size LOD drawing the node at `1 / zoom`; `1` for\n * connectors. Excludes display-only magnification (a fisheye lens), which\n * should still enlarge the label.\n * @param policy The policy in force, or `null` for none.\n * @param contained `true` when the label must stay inside its host (an `inside-*`\n * placement): the result never exceeds `1`, so the host's fit-to-box budget holds.\n *\n * - `natural = fontSize × zoom × hostScale` — what the label measures on\n * screen with no policy.\n * - `target = zoomGrowth === undefined ? natural : fontSize × zoom ^ zoomGrowth`,\n * then clamped to `[minFontPx, maxFontPx]`.\n * - Result: `target / natural`, capped at `1` for a contained label.\n *\n * Returns `1` for a `null` policy and for degenerate input (non-positive font\n * size, zoom or host scale), so a caller can apply the result unconditionally.\n *\n * @example\n * ```ts\n * resolveLabelScale(12, 4, 1, { maxFontPx: 20 });\n * // → 20 / 48 ≈ 0.417 — the label reads 20px on screen instead of 48px\n * ```\n */\nexport function resolveLabelScale(\n fontSize: number,\n zoom: number,\n hostScale: number,\n policy: LabelSizePolicy | null,\n contained = false,\n): number {\n if (policy === null) return 1;\n if (!(fontSize > 0) || !(zoom > 0) || !(hostScale > 0)) return 1;\n\n const natural = fontSize * zoom * hostScale;\n let target =\n policy.zoomGrowth === undefined\n ? natural\n : fontSize * Math.pow(zoom, clampUnit(policy.zoomGrowth));\n if (policy.minFontPx !== undefined && target < policy.minFontPx) target = policy.minFontPx;\n if (policy.maxFontPx !== undefined && target > policy.maxFontPx) target = policy.maxFontPx;\n\n const scale = target / natural;\n return contained && scale > 1 ? 1 : scale;\n}\n\n/** Clamp to `[0, 1]`; a non-finite value falls back to `1` (grow with the world). */\nfunction clampUnit(v: number): number {\n if (!Number.isFinite(v)) return 1;\n return v < 0 ? 0 : v > 1 ? 1 : v;\n}\n","import { Tween } from './Tween';\nimport { easeOutCubic, type Easing } from './easings';\n\n/**\n * Options for {@link animatePositions}.\n *\n * Positions are passed as flat `Float32Array`s of length `n * 2` — `x, y`\n * interleaved per node — the same shape `GraphStore.setPositionsBulk` consumes,\n * so a layout can hand its result buffer straight through.\n */\nexport interface PositionTransitionOptions {\n /** Start positions (`n * 2`, x/y interleaved). Usually the nodes' current spots. */\n from: Float32Array;\n /** Target positions (`n * 2`, x/y interleaved). The computed layout result. */\n to: Float32Array;\n /** Transition duration in milliseconds. `<= 0` snaps to `to` immediately. */\n duration: number;\n /** Eased progress curve. Default {@link easeOutCubic}. */\n easing?: Easing;\n /**\n * Called once per frame with the interpolated buffer — write it straight to\n * the store (e.g. `store.setPositionsBulk(ids, xy)`). The SAME buffer is\n * reused every frame; copy it if you need to retain it.\n *\n * `progress` is the **eased** fraction of the transition, `0..1` — the same\n * factor the buffer was interpolated with — and is exactly `1` on the final\n * frame. Lets a caller move something else in lock-step (e.g. the camera).\n */\n onFrame: (xy: Float32Array, progress: number) => void;\n /** Fires once when the transition finishes naturally. NOT called on `cancel()`. */\n onComplete?: () => void;\n}\n\n/** Handle to an in-flight {@link animatePositions} transition. */\nexport interface PositionTransition {\n /** Abort the transition. `onComplete` will not fire; positions stop where they are. */\n cancel(): void;\n /** `true` once the transition has finished or been cancelled. */\n readonly done: boolean;\n}\n\n/** Default transition length when a caller opts in without specifying one. */\nexport const DEFAULT_POSITION_TRANSITION_MS = 500;\n\n/**\n * Tween a set of node positions from `from` to `to` over `duration` ms,\n * self-driven on `requestAnimationFrame`.\n *\n * One-shot layouts (ELK, d3-hierarchy, d3-sankey, …) compute a final position\n * set in a single pass and would otherwise `setPositionsBulk` it in one write,\n * teleporting every node. Routing that final buffer through `animatePositions`\n * instead glides each node from where it currently sits to its computed slot —\n * a far more legible layout switch / re-layout.\n *\n * The `Layout` base class is deliberately canvas-agnostic (it owns no RAF), so\n * this helper drives its own frame loop — mirroring how `D3ForceLayout` rides\n * d3's internal timer. It is store-agnostic: it only interpolates buffers and\n * hands each frame back via `onFrame`; the caller owns the write.\n *\n * Cancellation: call `cancel()` (typically from the layout's `stop()` or its\n * next `apply()`) to abort cleanly — the next run can start a fresh transition\n * from wherever the nodes currently are. SSR-safe and degenerate-input-safe:\n * with no `requestAnimationFrame`, a non-positive `duration`, or an empty set,\n * it writes the final positions once and completes synchronously.\n *\n * @throws if `from.length !== to.length`.\n */\nexport function animatePositions(opts: PositionTransitionOptions): PositionTransition {\n const { from, to, duration, easing = easeOutCubic, onFrame, onComplete } = opts;\n if (from.length !== to.length) {\n throw new Error(\n `animatePositions: from.length=${from.length} must equal to.length=${to.length}`,\n );\n }\n\n const n = from.length;\n let done = false;\n let cancelled = false;\n let rafId: number | null = null;\n let last = 0;\n\n const finish = (): void => {\n done = true;\n onFrame(to, 1); // land on the exact target, free of float drift\n onComplete?.();\n };\n\n const raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null;\n if (!raf || duration <= 0 || n === 0) {\n finish();\n return { cancel() {}, get done() { return done; } };\n }\n\n const buffer = new Float32Array(n);\n const tween = new Tween({ from: 0, to: 1, duration, easing });\n\n const step = (now: number): void => {\n if (cancelled) return;\n const dt = last === 0 ? 0 : now - last;\n last = now;\n const alive = tween.tick(dt);\n if (!alive) {\n finish();\n return;\n }\n const t = tween.value;\n for (let i = 0; i < n; i++) buffer[i] = from[i]! + (to[i]! - from[i]!) * t;\n onFrame(buffer, t);\n rafId = raf(step);\n };\n rafId = raf(step);\n\n return {\n cancel(): void {\n if (done) return;\n cancelled = true;\n done = true;\n if (rafId !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(rafId);\n },\n get done(): boolean {\n return done;\n },\n };\n}\n","/**\n * SVG markup primitives — number formatting, XML escaping, attribute\n * serialisation and colour conversion shared by every serialiser in this\n * folder (and by the `exportSVG` document assembler in `@invana/canvas`).\n *\n * Pure string helpers: no DOM, no canvas, no backend.\n */\n\nimport type { Point } from '../../specs';\n\n/** Round to 3 decimals and drop a trailing `.0` — keeps the markup compact. */\nexport function n(v: number): string {\n return Number.isInteger(v) ? String(v) : v.toFixed(3).replace(/\\.?0+$/, '');\n}\n\n/** Escape text for use in an XML text node / attribute value. */\nexport function esc(s: string): string {\n return s.replace(/[&<>\"']/g, (c) =>\n c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '\"' ? '&quot;' : '&#39;',\n );\n}\n\n/** Serialise an attribute map, skipping `undefined` / empty values. */\nexport function attrs(map: Record<string, string | number | undefined>): string {\n return Object.entries(map)\n .filter(([, v]) => v !== undefined && v !== '')\n .map(([k, v]) => `${k}=\"${typeof v === 'number' ? n(v) : v}\"`)\n .join(' ');\n}\n\n/** `points=\"x,y x,y …\"` for `<polygon>`. */\nexport function pointsAttr(pts: readonly Point[]): string {\n return pts.map((p) => `${n(p.x)},${n(p.y)}`).join(' ');\n}\n\n/** `0xRRGGBB` → `#rrggbb`. */\nexport function hexToCss(n: number): string {\n return `#${(n & 0xffffff).toString(16).padStart(6, '0')}`;\n}\n","/**\n * `Path` → SVG path-data serialisation. Pure: a routed {@link Path} in, a `d`\n * attribute string out.\n */\n\nimport type { Path } from '../../specs';\nimport { n } from './markup';\n\n/** A `Path` (M/L/Q/C commands) → an SVG `d` attribute string. */\nexport function pathToSvgD(path: Path): string {\n const out: string[] = [];\n for (const c of path) {\n if (c.kind === 'M') out.push(`M ${n(c.x)} ${n(c.y)}`);\n else if (c.kind === 'L') out.push(`L ${n(c.x)} ${n(c.y)}`);\n else if (c.kind === 'Q') out.push(`Q ${n(c.cx)} ${n(c.cy)} ${n(c.x)} ${n(c.y)}`);\n else out.push(`C ${n(c.c1x)} ${n(c.c1y)} ${n(c.c2x)} ${n(c.c2y)} ${n(c.x)} ${n(c.y)}`);\n }\n return out.join(' ');\n}\n","/**\n * Spec paint → SVG paint attributes — the fill/stroke resolution shared by the\n * shape and connector serialisers, plus label-content extraction.\n *\n * Only the first `solid` fill layer is representable in flat SVG; `image` /\n * `glyph` / `svg` fills are skipped (→ `fill: none`) — a raster-only feature.\n */\n\nimport type { LabelContent, ShapeFill, ShapeStroke } from '../../specs';\nimport { hexToCss, n } from './markup';\n\n/**\n * Resolve a {@link ShapeFill} to SVG `fill` / `fill-opacity`. Only the first\n * `solid` layer is representable in flat SVG; `image` / `glyph` / `svg` fills\n * are skipped (→ `fill: none`), documented as a raster-only feature.\n */\nexport function fillPaint(fill: ShapeFill | undefined): Record<string, string | number | undefined> {\n if (fill === undefined) return { fill: 'none' };\n if (typeof fill === 'number') return { fill: hexToCss(fill) };\n const layers = Array.isArray(fill) ? fill : [fill];\n for (const layer of layers) {\n if (layer.kind === 'solid') {\n return { fill: hexToCss(layer.color), 'fill-opacity': layer.alpha ?? undefined };\n }\n }\n return { fill: 'none' };\n}\n\n/** Resolve a {@link ShapeStroke} to SVG stroke attributes. `widthScale` mirrors LOD scaling. */\nexport function strokePaint(stroke: ShapeStroke | undefined, widthScale = 1): Record<string, string | number | undefined> {\n if (!stroke) return {};\n const width = (stroke.width ?? 1) * widthScale;\n return {\n stroke: hexToCss(stroke.color),\n 'stroke-width': width,\n 'stroke-opacity': stroke.alpha ?? undefined,\n 'stroke-linecap': stroke.cap,\n 'stroke-linejoin': stroke.join,\n 'stroke-dasharray': stroke.dashArray ? `${n(stroke.dashArray[0])} ${n(stroke.dashArray[1])}` : undefined,\n 'stroke-dashoffset': stroke.dashOffset,\n };\n}\n\n/** Extract plain-text `LabelContent` from a label decoration style, if any. */\nexport function textContent(style: unknown): (LabelContent & { kind: 'text' }) | undefined {\n const content = (style as { content?: LabelContent } | undefined)?.content;\n return content?.kind === 'text' ? content : undefined;\n}\n","/**\n * Shape spec → SVG element serialisation — one half of the vector export path\n * (see `@invana/canvas`'s `exportSVG` for document assembly, and\n * {@link connectorToSvg} for the other half).\n *\n * The serialisers here are **pure and domain-free** (a `CircleSpec` knows\n * nothing about \"nodes\"): a spec goes in, markup comes out — no display object,\n * no canvas handle, which is why they live in `@invana/canvas-core` where a\n * rendering backend can call them directly.\n *\n * ## Coverage (v1)\n *\n * Faithful: `circle`, `ellipse`, `rect` (+ `cornerRadius`), `polygon`,\n * `regular-polygon`, `star`, `arc`, `composite` (root silhouette + `rect` /\n * `circle` / `line` / `label` parts), solid fills, strokes (colour / width /\n * alpha / dash / cap / join), per-shape `alpha` and container `rotation`, and\n * `text`-kind label decorations (approximate placement).\n *\n * Not represented (raster export covers these exactly — prefer PNG when they\n * matter): `image` / `glyph` / `svg` / `svg-url` fills, decorations other than\n * labels (glow / halo / rings / pulses), effects, blur / shadow filters, and\n * `html-text` labels. These are skipped rather than approximated.\n */\n\nimport type {\n ArcSpec,\n BaseShapeSpec,\n CircleSpec,\n CompositePart,\n CompositeSpec,\n EllipseSpec,\n Point,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n ShapeLabelStyle,\n StarSpec,\n TabbedRectSpec,\n} from '../../specs';\nimport { tabbedRectFoldLine, tabbedRectOutline } from '../../specs';\nimport { attrs, esc, hexToCss, n, pointsAttr } from './markup';\nimport { fillPaint, strokePaint, textContent } from './paint';\n\n/** Vertices of a regular n-gon (pointy-top at `rotation = 0`). */\nfunction regularPolygonPoints(cx: number, cy: number, sides: number, radius: number, rotation = 0): Point[] {\n const pts: Point[] = [];\n const step = (Math.PI * 2) / Math.max(3, sides);\n const start = -Math.PI / 2 - rotation;\n for (let i = 0; i < sides; i++) {\n const a = start + i * step;\n pts.push({ x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) });\n }\n return pts;\n}\n\n/** Vertices of a star alternating outer/inner radius. */\nfunction starPoints(cx: number, cy: number, points: number, innerR: number, outerR: number, rotation = 0): Point[] {\n const pts: Point[] = [];\n const step = Math.PI / Math.max(2, points);\n const start = -Math.PI / 2 - rotation;\n for (let i = 0; i < points * 2; i++) {\n const r = i % 2 === 0 ? outerR : innerR;\n const a = start + i * step;\n pts.push({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });\n }\n return pts;\n}\n\n/**\n * Wrap `inner` in a `<g>` when the spec carries a container-level `alpha` or\n * `rotation` (radians, about the spec origin). Returns `inner` unchanged when\n * neither applies, to keep the markup minimal.\n */\nfunction wrapTransform(spec: BaseShapeSpec, inner: string): string {\n const rot = spec.rotation ?? 0;\n const hasAlpha = spec.alpha !== undefined && spec.alpha !== 1;\n if (!rot && !hasAlpha) return inner;\n const t = rot ? `transform=\"rotate(${n((rot * 180) / Math.PI)} ${n(spec.x)} ${n(spec.y)})\"` : '';\n const o = hasAlpha ? `opacity=\"${n(spec.alpha as number)}\"` : '';\n return `<g ${[t, o].filter(Boolean).join(' ')}>${inner}</g>`;\n}\n\n/**\n * Serialise a single shape spec to an SVG element. Returns `''` for a shape\n * kind that has no vector representation. `labelStyle` (from an attached\n * `label` decoration) is rendered as `<text>` when present.\n */\nexport function shapeSpecToSvg(spec: BaseShapeSpec, labelStyle?: unknown): string {\n if (spec.visible === false) return '';\n const paint = { ...fillPaint(spec.fill), ...strokePaint(spec.stroke) };\n let body = '';\n\n switch (spec.kind) {\n case 'circle': {\n const s = spec as CircleSpec;\n body = `<circle ${attrs({ cx: s.x, cy: s.y, r: s.radius, ...paint })}/>`;\n break;\n }\n case 'ellipse': {\n const s = spec as EllipseSpec;\n body = `<ellipse ${attrs({ cx: s.x, cy: s.y, rx: s.radiusX, ry: s.radiusY, ...paint })}/>`;\n break;\n }\n case 'rect': {\n const s = spec as RectSpec;\n body = `<rect ${attrs({ x: s.x, y: s.y, width: s.width, height: s.height, rx: s.cornerRadius || undefined, ...paint })}/>`;\n break;\n }\n case 'tabbed-rect': {\n const s = spec as TabbedRectSpec;\n // The folder outline is already a polyline (fillets sampled as\n // segments), so it exports exactly as the renderer draws it.\n const pts = tabbedRectOutline(s).map((v) => ({ x: v.x + s.x, y: v.y + s.y }));\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n // The fold line closing the tab's base is interior geometry, so it\n // rides as a separate stroked segment rather than part of the outline.\n const fold = tabbedRectFoldLine(s);\n if (fold && s.stroke) {\n body += `<line ${attrs({\n x1: fold[0].x + s.x,\n y1: fold[0].y + s.y,\n x2: fold[1].x + s.x,\n y2: fold[1].y + s.y,\n ...strokePaint(s.stroke),\n fill: 'none',\n })}/>`;\n }\n break;\n }\n case 'polygon': {\n const s = spec as PolygonSpec;\n const pts = s.vertices.map((v) => ({ x: v.x + s.x, y: v.y + s.y }));\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'regular-polygon': {\n const s = spec as RegularPolygonSpec;\n const pts = regularPolygonPoints(s.x, s.y, s.sides, s.radius, s.rotation ?? 0);\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'star': {\n const s = spec as StarSpec;\n const pts = starPoints(s.x, s.y, s.points, s.innerRadius, s.outerRadius, s.rotation ?? 0);\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'arc': {\n body = `<path ${attrs({ d: arcToSvgD(spec as ArcSpec), 'fill-rule': 'evenodd', ...paint })}/>`;\n break;\n }\n case 'composite': {\n body = compositeToSvg(spec as CompositeSpec);\n break;\n }\n default:\n return ''; // unknown / raster-only shape kind\n }\n\n return wrapTransform(spec, body + labelToSvg(spec, labelStyle));\n}\n\n/** Annular-sector / pie `arc` spec → SVG path `d`. */\nfunction arcToSvgD(s: ArcSpec): string {\n const { x: cx, y: cy, innerR, outerR, startAngle: a0, endAngle: a1 } = s;\n const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;\n const pt = (r: number, a: number): Point => ({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });\n\n if (full) {\n // Full disc / annulus — two half-arcs per ring; evenodd punches the hole.\n const ring = (r: number) =>\n `M ${n(cx - r)} ${n(cy)} A ${n(r)} ${n(r)} 0 1 1 ${n(cx + r)} ${n(cy)} A ${n(r)} ${n(r)} 0 1 1 ${n(cx - r)} ${n(cy)} Z`;\n return innerR > 0 ? `${ring(outerR)} ${ring(innerR)}` : ring(outerR);\n }\n\n const large = Math.abs(a1 - a0) > Math.PI ? 1 : 0;\n const os = pt(outerR, a0);\n const oe = pt(outerR, a1);\n if (innerR <= 0) {\n // Pie slice.\n return `M ${n(cx)} ${n(cy)} L ${n(os.x)} ${n(os.y)} A ${n(outerR)} ${n(outerR)} 0 ${large} 1 ${n(oe.x)} ${n(oe.y)} Z`;\n }\n const ie = pt(innerR, a1);\n const is = pt(innerR, a0);\n return (\n `M ${n(os.x)} ${n(os.y)} A ${n(outerR)} ${n(outerR)} 0 ${large} 1 ${n(oe.x)} ${n(oe.y)} ` +\n `L ${n(ie.x)} ${n(ie.y)} A ${n(innerR)} ${n(innerR)} 0 ${large} 0 ${n(is.x)} ${n(is.y)} Z`\n );\n}\n\n/**\n * Composite card → an SVG `<g>` translated to the composite's top-left origin:\n * the background silhouette (default rounded-rect, or the `root` shape centred\n * in the box) followed by each `rect` / `circle` / `line` / `label` part.\n */\nfunction compositeToSvg(s: CompositeSpec): string {\n const els: string[] = [];\n const paint = { ...fillPaint(s.fill), ...strokePaint(s.stroke) };\n\n if (s.root) {\n // Centre the borrowed root shape in the width×height box (its own x/y are\n // ignored per CompositeSpec) and serialise it as a normal shape.\n const centred = { ...s.root, x: s.width / 2, y: s.height / 2 } as BaseShapeSpec;\n // Rect roots are top-left anchored — offset so the box is centred.\n if (s.root.kind === 'rect') {\n const r = s.root as RectSpec;\n (centred as { x: number; y: number }).x = (s.width - r.width) / 2;\n (centred as { x: number; y: number }).y = (s.height - r.height) / 2;\n }\n els.push(shapeSpecToSvg(centred));\n } else {\n els.push(`<rect ${attrs({ x: 0, y: 0, width: s.width, height: s.height, rx: s.cornerRadius || undefined, ...paint })}/>`);\n }\n\n for (const part of s.parts) els.push(partToSvg(part));\n return `<g ${attrs({ transform: `translate(${n(s.x)} ${n(s.y)})` })}>${els.join('')}</g>`;\n}\n\n/** A single {@link CompositePart} → SVG element (coords relative to the card origin). */\nfunction partToSvg(part: CompositePart): string {\n switch (part.part) {\n case 'rect':\n return `<rect ${attrs({\n x: part.x,\n y: part.y,\n width: part.width,\n height: part.height,\n rx: part.cornerRadius || undefined,\n fill: part.fill !== undefined ? hexToCss(part.fill) : 'none',\n 'fill-opacity': part.fillAlpha,\n ...(part.stroke ? { stroke: hexToCss(part.stroke.color), 'stroke-width': part.stroke.width ?? 1, 'stroke-opacity': part.stroke.alpha } : {}),\n })}/>`;\n case 'circle':\n return `<circle ${attrs({\n cx: part.x,\n cy: part.y,\n r: part.radius,\n fill: part.fill !== undefined ? hexToCss(part.fill) : 'none',\n 'fill-opacity': part.fillAlpha,\n ...(part.stroke ? { stroke: hexToCss(part.stroke.color), 'stroke-width': part.stroke.width ?? 1, 'stroke-opacity': part.stroke.alpha } : {}),\n })}/>`;\n case 'line':\n return `<line ${attrs({\n x1: part.x,\n y1: part.y,\n x2: part.x2,\n y2: part.y2,\n stroke: hexToCss(part.stroke.color),\n 'stroke-width': part.stroke.width ?? 1,\n 'stroke-opacity': part.stroke.alpha,\n })}/>`;\n case 'label': {\n const anchor = part.anchor === 'center' ? 'middle' : part.anchor === 'right' ? 'end' : 'start';\n return `<text ${attrs({\n x: part.x,\n y: part.y,\n 'font-size': part.fontSize ?? 12,\n 'font-weight': part.fontWeight as string | number | undefined,\n 'font-style': part.fontStyle,\n 'text-anchor': anchor,\n 'dominant-baseline': 'hanging',\n fill: part.fill !== undefined ? hexToCss(part.fill) : '#111827',\n })}>${esc(part.text)}</text>`;\n }\n default:\n return '';\n }\n}\n\n/**\n * Approximate an attached `text` label as `<text>`, anchored at the shape\n * centre with a placement-derived vertical offset. Placement is coarse (SVG\n * can't run the engine's fit/collision cascade); it captures the text, colour,\n * and rough position — good enough for a legible vector export.\n */\nfunction labelToSvg(spec: BaseShapeSpec, style: unknown): string {\n const content = textContent(style);\n if (!content) return '';\n const s = style as ShapeLabelStyle;\n const placement = s.placement ?? 'bottom';\n // Rough half-extent from any radius/size field so outside labels clear the shape.\n const r =\n (spec as { radius?: number }).radius ??\n (spec as { outerRadius?: number }).outerRadius ??\n ((spec as { height?: number }).height ?? 24) / 2;\n let dy = 0;\n if (placement.includes('bottom')) dy = r + (content.fontSize ?? 12);\n else if (placement.includes('top')) dy = -(r + 4);\n const ox = s.offset?.x ?? 0;\n const oy = s.offset?.y ?? 0;\n return `<text ${attrs({\n x: spec.x + ox,\n y: spec.y + dy + oy,\n 'font-size': content.fontSize ?? 12,\n 'font-family': content.fontFamily ?? 'sans-serif',\n 'font-weight': content.fontWeight as string | number | undefined,\n 'font-style': content.fontStyle,\n 'text-anchor': 'middle',\n 'dominant-baseline': 'middle',\n fill: content.fill !== undefined ? hexToCss(content.fill) : '#111827',\n opacity: content.alpha,\n })}>${esc(content.text)}</text>`;\n}\n","/**\n * Connector spec → SVG serialisation — the other half of the vector export\n * path (see {@link shapeSpecToSvg}). Pure: a spec + its routed {@link Path} in,\n * markup out.\n */\n\nimport type { BaseConnectorSpec, ConnectorLabelStyle, Path, Point } from '../../specs';\nimport { attrs, esc, hexToCss, n, pointsAttr } from './markup';\nimport { strokePaint, textContent } from './paint';\nimport { pathToSvgD } from './pathToSvgD';\n\n/**\n * Serialise a connector (its routed `path` + stroke + optional arrow markers)\n * to SVG. `strokeWidthScale` mirrors the renderer's per-instance LOD scaling.\n */\nexport function connectorToSvg(\n spec: BaseConnectorSpec,\n path: Path,\n strokeWidthScale = 1,\n labelStyle?: unknown,\n): string {\n if (spec.visible === false || path.length === 0) return '';\n const paint = strokePaint(spec.stroke, strokeWidthScale);\n const width = (spec.stroke?.width ?? 1) * strokeWidthScale;\n const els = [`<path ${attrs({ d: pathToSvgD(path), fill: 'none', ...paint })}/>`];\n\n // Arrow markers as filled triangles at the path ends, oriented along the\n // terminal segment. Approximate (marker geometry sizes off stroke width).\n const color = spec.stroke ? hexToCss(spec.stroke.color) : '#000000';\n if (spec.targetMarker) els.push(arrowMarker(path, 'target', width, color));\n if (spec.sourceMarker) els.push(arrowMarker(path, 'source', width, color));\n\n const label = connectorLabelToSvg(path, labelStyle);\n const alpha = spec.alpha !== undefined && spec.alpha !== 1 ? ` opacity=\"${n(spec.alpha)}\"` : '';\n return `<g${alpha}>${els.join('')}${label}</g>`;\n}\n\n/** A triangular arrowhead at the source/target end of a path. */\nfunction arrowMarker(path: Path, end: 'source' | 'target', strokeWidth: number, color: string): string {\n const pts = pathPoints(path);\n if (pts.length < 2) return '';\n const tip = end === 'target' ? pts[pts.length - 1]! : pts[0]!;\n const prev = end === 'target' ? pts[pts.length - 2]! : pts[1]!;\n const ang = Math.atan2(tip.y - prev.y, tip.x - prev.x);\n const len = Math.max(6, strokeWidth * 4);\n const half = Math.max(3, strokeWidth * 2);\n const back = { x: tip.x - len * Math.cos(ang), y: tip.y - len * Math.sin(ang) };\n const nx = Math.cos(ang + Math.PI / 2);\n const ny = Math.sin(ang + Math.PI / 2);\n const p1 = { x: back.x + half * nx, y: back.y + half * ny };\n const p2 = { x: back.x - half * nx, y: back.y - half * ny };\n return `<polygon ${attrs({ points: pointsAttr([tip, p1, p2]), fill: color })}/>`;\n}\n\n/** Sample a path's command endpoints as a coarse polyline (ignores control points). */\nfunction pathPoints(path: Path): Point[] {\n return path.filter((c) => c.kind !== undefined).map((c) => ({ x: c.x, y: c.y }));\n}\n\n/** Approximate a connector's `text` label at the path midpoint. */\nfunction connectorLabelToSvg(path: Path, style: unknown): string {\n const content = textContent(style);\n if (!content) return '';\n const pts = pathPoints(path);\n if (pts.length === 0) return '';\n const mid = pts[Math.floor(pts.length / 2)]!;\n const s = style as ConnectorLabelStyle;\n return `<text ${attrs({\n x: mid.x + (s.offset?.x ?? 0),\n y: mid.y + (s.offset?.y ?? 0),\n 'font-size': content.fontSize ?? 12,\n 'font-family': content.fontFamily ?? 'sans-serif',\n 'text-anchor': 'middle',\n 'dominant-baseline': 'middle',\n fill: content.fill !== undefined ? hexToCss(content.fill) : '#111827',\n })}>${esc(content.text)}</text>`;\n}\n","import type { EasingName } from '../../lib/animation/easings';\nimport type { CameraTransform, Rect } from '../../specs/geom';\nimport type { ControlPanelSpec } from './controlPanels';\nimport type { CameraIntent } from '../log/types';\n\n/**\n * `CanvasView` — the reactive, observable, syncable half of `CanvasStore`: how a\n * visualisation is **defined**, **viewed**, and its small transient **runtime**\n * status. Small + human-rate → it lives on a {@link ReactiveStore}. Bulk data\n * (nodes/edges/positions) is the **other** half (`CanvasStore.data`, typed-array,\n * never reactive).\n *\n * Three compartments, three sync physics (see `docs/canvas-state-plan.md` §9):\n * - **`definition`** — \"what it IS\": persisted, converges (a CRDT doc later).\n * - **`interaction`** — \"the live view\": ephemeral / per-user (Awareness later).\n * - **`runtime`** — small observable transient status (layout run, message):\n * reactive so UIs can react, but **never synced**.\n *\n * Per-instance option bags are intentionally loose (`Record<string, unknown>`) at\n * this layer — the engine and the schema-driven editors give them concrete shape,\n * and the kernel stays domain-free (it treats element `style` as opaque).\n */\n/** A layout preset by id, and the options changed over its defaults. */\nexport interface CanvasLayoutPreset {\n id: string;\n /** Option key → chosen value, only where it differs from the preset's default. */\n overrides?: Record<string, string>;\n}\n\nexport interface CanvasView {\n /** \"What the visualisation IS\" — persisted, converged (a CRDT doc later). */\n definition: {\n /** Canvas/scene-level config (background, zoom limits, world bounds, …). */\n canvas: CanvasSceneOptions;\n /** Layer options keyed by instance id (a rendering layer binds a data source). */\n layers: Record<string, Record<string, unknown>>;\n /** Behaviour options keyed by instance id. `enabled` is explicit (rule 7). */\n behaviours: Record<string, Record<string, unknown>>;\n /** Layout options keyed by instance id. */\n layouts: Record<string, Record<string, unknown>>;\n /** Id of the active layout among {@link layouts}, or `null`. */\n activeLayout: string | null;\n /**\n * The layout preset the layout, edge and layout-option slices were last set\n * from, and the options changed over it — `null` when none was applied. The\n * expanded slices are what take effect; this names them, for the picker,\n * *Reset to preset* and a replayed walkthrough step.\n */\n layoutPreset: CanvasLayoutPreset | null;\n /** Authored node/edge templates (designer output). */\n templates: unknown[];\n /** Theme **config** (registry + active family + mode + accent). The *resolved* theme is derived. */\n theme: Record<string, unknown>;\n /**\n * Floating control panels over the canvas, keyed by panel id. Pure JSON —\n * items name commands / icons / widgets by string (see {@link ControlPanelSpec}).\n */\n controlPanels: Record<string, ControlPanelSpec>;\n };\n /** \"The live view onto it\" — mostly ephemeral / per-user (Awareness later). */\n interaction: {\n /** The semantic selection set (D11 — owned here, not in a behaviour). */\n selection: ReadonlySet<string>;\n /** Hovered element id, or `null`. */\n hover: string | null;\n /** Visual state sets (highlighted / context-open / …) keyed by state name (presence overlay). */\n states: Record<string, ReadonlySet<string>>;\n /**\n * Elements lifted above their peers, keyed by the **source** that lifted\n * them (a behaviour id) — so independent sources (hover, selection, …)\n * never clobber each other's set, and each can be cleared on its own.\n *\n * The renderer projects the union of every source onto its own paint order\n * and lowers anything absent from it. That single projection is what keeps\n * the lift honest: a raise is *derived from state*, not a side effect, so\n * it self-corrects when the state that motivated it changes (an element\n * stops being hovered, a frame opens and becomes a backdrop, …). Before,\n * each behaviour reparented display objects imperatively and tracked what\n * it had touched privately — nothing could reconcile them, so a stale lift\n * outranked the whole scene until that behaviour happened to run again.\n *\n * Ids only: the kernel stays domain-free. What an id *means* (a frame\n * lifting its contents instead of itself, say) is the renderer's business.\n */\n raised: Record<string, ReadonlySet<string>>;\n /** Abstract camera transform — renderer-agnostic; throttled/ephemeral. */\n camera: CameraTransform;\n /**\n * Focal-emphasis: the highlight set + whether the rest is dimmed. O(1) to set;\n * \"muted\" is a render-time derivation (`dim && !ids.has(id)`), not a per-node\n * write (see `canvas-state-plan.md` §7.1B). `null` when no focus is active.\n */\n focus: { ids: ReadonlySet<string>; dim: boolean } | null;\n /**\n * The element whose properties are open (a node or edge id), or `null`.\n * Written by a playbook step, the assistant or a panel; a property-view\n * behaviour (`ClickViewBehaviour`) follows it and writes it back when the\n * user opens or closes one. Recorded as view intent — plain undo steps\n * over it.\n */\n inspect: string | null;\n /**\n * The latest request to frame the camera — `'focus'` (the focus set),\n * `'visible'` (every visible element) or `'all'` (all content, hidden\n * included) — or `null` before any. An **intent, not pixels** (RFC D-4):\n * whoever owns that framing performs it once the canvas settles (the\n * engine frames `'visible'` / `'all'`, `FocusBehaviour` frames `'focus'`).\n * `seq` increases on every request, so asking for the same intent twice\n * frames twice. Recorded as view intent — plain undo steps over it.\n */\n cameraIntent: { intent: CameraIntent; seq: number } | null;\n /**\n * Nodes transiently locked during a drag/resize gesture — held against the\n * layout for the gesture's duration. **Distinct from data `pinned`** (the\n * permanent, synced user flag); these are ephemeral and never synced.\n */\n transientPins: ReadonlySet<string>;\n /**\n * Active interaction mode — the modeller \"tool\" (`'select'`, `'add'`,\n * `'connect'`, `'delete'`, or any string a host defines). Per-user and\n * ephemeral like the rest of `interaction`. Behaviours opt into following it\n * through `BehaviourOptions.modes`; commands switch it (`tool.active`).\n * Seeded from `definition.canvas.defaultViewMode` when a canvas starts.\n */\n viewMode: string;\n /**\n * Parameters of the active mode, as plain strings keyed by name — e.g.\n * `{ nodeKind: 'circle' }` for an \"add node\" tool. A bag rather than typed\n * fields so the kernel stays domain-free: what a key means is the\n * business of whoever reads it (the graph's `tool.nodeKind` command).\n */\n viewModeArgs: Readonly<Record<string, string>>;\n };\n /** Small observable transient status — reactive (UIs react) but **never synced**. */\n runtime: {\n /** Layout run status — drives spinners / a stop control. */\n layout: {\n running: boolean;\n /** The layout id currently executing, or `null`. */\n activeId: string | null;\n /** Whether the run animates its settle (force sim) vs jumps to final positions. */\n animate: boolean;\n /** 0..1 progress when known (force `alpha`); `null` for one-shot / unknown. */\n progress: number | null;\n };\n /** Transient overlay/status message, or `null`. */\n message: string | null;\n };\n}\n\n/**\n * Canvas/scene-level configuration — the settings that sit *above* individual\n * layers/behaviours/layouts. Renderer-init options (`preference`, `antialias`,\n * `resolution`, …) are deliberately **not** here: those belong to the renderer\n * adapter, not the syncable definition.\n */\nexport interface CanvasSceneOptions {\n /** Scene background colour (`0xRRGGBB`). */\n backgroundColor?: number;\n /** Suppress the browser's native context menu over the canvas. */\n suppressBrowserContextMenu?: boolean;\n /** Zoom clamp for the abstract camera. */\n zoom: { min: number; max: number };\n /** Initial camera transform applied on load. */\n initialCamera?: CameraTransform;\n /** Optional world/scene bounds (for fit-on-load / clamping), or `null`. */\n worldBounds?: Rect | null;\n /** Default interaction mode the view starts in. */\n defaultViewMode?: string;\n\n // ── Load behaviour ───────────────────────────────────────────────────────\n // These three are *how the scene arrives*, not what it is — but they are\n // authored config like any other, so they live in the definition and\n // round-trip through export / import. The engine reads them on `update()`.\n\n /**\n * Frame the camera on the content once on load. See\n * `CanvasConfig.fitOnLoad`.\n */\n fitOnLoad?: boolean;\n /**\n * Ease the first auto-fit instead of snapping to it. See\n * `CanvasConfig.fitAnimation`.\n */\n fitAnimation?: {\n durationMs?: number;\n easing?: EasingName;\n };\n /**\n * Fade the world content in once, the first time it is worth showing. See\n * `CanvasConfig.entrance`.\n */\n entrance?: {\n kind: 'fade';\n durationMs?: number;\n easing?: EasingName;\n };\n}\n\n/** The empty-but-valid initial {@link CanvasView}. */\nexport function defaultCanvasView(): CanvasView {\n return {\n definition: {\n canvas: { zoom: { min: 0.01, max: 100 } },\n layers: {},\n behaviours: {},\n layouts: {},\n activeLayout: null,\n layoutPreset: null,\n templates: [],\n theme: {},\n controlPanels: {},\n },\n interaction: {\n selection: new Set<string>(),\n hover: null,\n states: {},\n raised: {},\n camera: { x: 0, y: 0, zoom: 1 },\n focus: null,\n inspect: null,\n cameraIntent: null,\n transientPins: new Set<string>(),\n viewMode: 'select',\n viewModeArgs: {},\n },\n runtime: {\n layout: { running: false, activeId: null, animate: false, progress: null },\n message: null,\n },\n };\n}\n","import type { LayerData, NodeRecord, EdgeRecord, GroupRecord, AnnotationRecord } from '../data/LayerData';\nimport type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { ReactiveStore } from '../port/types';\nimport type { CanvasSceneOptions, CanvasView } from './CanvasView';\nimport type { ControlPanelSpec } from './controlPanels';\nimport type { CameraIntent } from '../log/types';\n\n/** Loose option/patch bag for the view's per-instance config. */\ntype Bag = Record<string, unknown>;\n/** Partial camera transform. */\ntype CameraInput = Partial<{ x: number; y: number; zoom: number }>;\n\n/**\n * `createActions` — the **named, action-typed command API** over the kernel.\n *\n * Every mutation is a discoverable method (not a raw `view.update(recipe, …)`),\n * and each **bakes in its action label** (`'view:layer:setStyle'`, `'view:camera:zoom'`, …),\n * so telemetry, history, and the CRDT op-log all read as intent. View commands go\n * through the one `view.update(recipe, action)` seam; data commands proxy to the\n * target {@link LayerData}.\n *\n * Group by concern: `node / edge / group / annotation / positions` (data) and\n * `layers / behaviours / layouts / camera / selection / hover / viewMode / templates /\n * theme / controlPanels` (view).\n *\n * ⚠ **Data actions target the default {@link LayerData} store only.** The\n * injected `layer(id)` accessor (see `createCanvasStore`) **throws** for any id\n * where a *custom* {@link DataSource} was registered via `setSource` — e.g.\n * `@invana/graph`'s `GraphStore`. For those, mutate through the domain store's\n * own API (`store.source(id)` / the layer's methods) instead. Unifying the data\n * actions over the `DataSource` interface is future work — audited and\n * deliberately deferred 2026-08-13 (the contract would need write methods it\n * doesn't carry today).\n */\nexport function createActions(\n view: ReactiveStore<CanvasView>,\n layer: (id: string) => LayerData,\n events: CanvasEventBus,\n) {\n // ── view helper: every command names its action ─────────────────────────────\n const v = (action: string, recipe: (s: CanvasView) => void): void => view.update(recipe, action);\n const mergeInto = (bag: Bag | undefined, patch: Bag): Bag => ({ ...(bag ?? {}), ...patch });\n // ── data helper: emit the GRANULAR taxonomy event (e.g. 'data:node:add') on the\n // tap — one per action (the per-frame 'data:flush' delta is separate). ─────\n const di = (type: string, layerId: string, ids: readonly string[]): void =>\n events.publish(type, { action: type, layerId, ids }, { kind: 'data', id: layerId });\n\n return {\n // ── DATA (proxy to the layer's bulk store + an intent record) ─────────────\n node: {\n add: (l: string, n: NodeRecord) => {\n layer(l).addNode(n);\n di('data:node:add', l, [n.id]);\n },\n update: (l: string, id: string, patch: Partial<NodeRecord>) => {\n layer(l).updateNode(id, patch);\n di('data:node:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeNode(id);\n di('data:node:remove', l, [id]);\n },\n moveTo: (l: string, id: string, x: number, y: number) => {\n layer(l).updateNode(id, { x, y });\n di('data:node:move', l, [id]);\n },\n },\n edge: {\n add: (l: string, e: EdgeRecord) => {\n layer(l).addEdge(e);\n di('data:edge:add', l, [e.id]);\n },\n update: (l: string, id: string, patch: Partial<EdgeRecord>) => {\n layer(l).updateEdge(id, patch);\n di('data:edge:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeEdge(id);\n di('data:edge:remove', l, [id]);\n },\n },\n group: {\n add: (l: string, g: GroupRecord) => {\n layer(l).addGroup(g);\n di('data:group:add', l, [g.id]);\n },\n update: (l: string, id: string, patch: Partial<GroupRecord>) => {\n layer(l).updateGroup(id, patch);\n di('data:group:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeGroup(id);\n di('data:group:remove', l, [id]);\n },\n },\n annotation: {\n add: (l: string, a: AnnotationRecord) => {\n layer(l).addAnnotation(a);\n di('data:annotation:add', l, [a.id]);\n },\n update: (l: string, id: string, patch: Partial<AnnotationRecord>) => {\n layer(l).updateAnnotation(id, patch);\n di('data:annotation:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeAnnotation(id);\n di('data:annotation:remove', l, [id]);\n },\n },\n /** Bulk layout output → node positions (transform-only re-render). */\n positions: {\n apply: (l: string, positions: Iterable<{ id: string; x: number; y: number }>) => {\n const arr = [...positions];\n layer(l).applyPositions(arr);\n di('data:position:apply', l, arr.map((p) => p.id));\n },\n },\n\n // ── VIEW · layers ─────────────────────────────────────────────────────────\n layers: {\n add: (id: string, opts: Bag) => v('view:layer:add', (s) => void (s.definition.layers[id] = opts)),\n update: (id: string, patch: Bag) =>\n v('view:layer:update', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], patch))),\n setStyle: (id: string, style: Bag) =>\n v('view:layer:setStyle', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], { style }))),\n setVisible: (id: string, visible: boolean) =>\n v('view:layer:setVisible', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], { visible }))),\n remove: (id: string) => v('view:layer:remove', (s) => void delete s.definition.layers[id]),\n },\n\n // ── VIEW · behaviours ─────────────────────────────────────────────────────\n behaviours: {\n add: (id: string, opts: Bag) => v('view:behaviour:add', (s) => void (s.definition.behaviours[id] = opts)),\n update: (id: string, patch: Bag) =>\n v('view:behaviour:update', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], patch))),\n enable: (id: string) =>\n v('view:behaviour:enable', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], { enabled: true }))),\n disable: (id: string) =>\n v('view:behaviour:disable', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], { enabled: false }))),\n remove: (id: string) => v('view:behaviour:remove', (s) => void delete s.definition.behaviours[id]),\n },\n\n // ── VIEW · layouts ────────────────────────────────────────────────────────\n layouts: {\n set: (id: string, opts: Bag) => v('view:layout:set', (s) => void (s.definition.layouts[id] = opts)),\n tune: (id: string, patch: Bag) =>\n v('view:layout:tune', (s) => void (s.definition.layouts[id] = mergeInto(s.definition.layouts[id], patch))),\n run: (id: string) => v('view:layout:run', (s) => void (s.definition.activeLayout = id)),\n remove: (id: string) =>\n v('view:layout:remove', (s) => {\n delete s.definition.layouts[id];\n if (s.definition.activeLayout === id) s.definition.activeLayout = null;\n }),\n },\n\n // ── VIEW · camera (interaction; abstract transform) ───────────────────────\n camera: {\n set: (c: CameraInput) => v('view:camera:set', (s) => void (s.interaction.camera = { ...s.interaction.camera, ...c })),\n pan: (dx: number, dy: number) =>\n v('view:camera:pan', (s) => {\n s.interaction.camera = {\n ...s.interaction.camera,\n x: s.interaction.camera.x + dx,\n y: s.interaction.camera.y + dy,\n };\n }),\n zoom: (factor: number) =>\n v('view:camera:zoom', (s) => void (s.interaction.camera = { ...s.interaction.camera, zoom: s.interaction.camera.zoom * factor })),\n zoomTo: (zoom: number) =>\n v('view:camera:zoomTo', (s) => void (s.interaction.camera = { ...s.interaction.camera, zoom })),\n reset: () => v('view:camera:reset', (s) => void (s.interaction.camera = { x: 0, y: 0, zoom: 1 })),\n },\n\n // ── VIEW · selection / hover (interaction) ────────────────────────────────\n selection: {\n set: (ids: Iterable<string>) => v('view:selection:set', (s) => void (s.interaction.selection = new Set(ids))),\n add: (ids: Iterable<string>) =>\n v('view:selection:add', (s) => void (s.interaction.selection = new Set([...s.interaction.selection, ...ids]))),\n toggle: (id: string) =>\n v('view:selection:toggle', (s) => {\n const next = new Set(s.interaction.selection);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n s.interaction.selection = next;\n }),\n clear: () => v('view:selection:clear', (s) => void (s.interaction.selection = new Set())),\n },\n hover: {\n set: (id: string) => v('view:hover:set', (s) => void (s.interaction.hover = id)),\n clear: () => v('view:hover:clear', (s) => void (s.interaction.hover = null)),\n },\n /**\n * Paint-order lift, per source. `source` is the id of whatever is asking\n * (a behaviour id) — each owns its own set, so a hover lift and a selection\n * lift coexist and either can be dropped without disturbing the other.\n * The renderer projects the union; see `CanvasView.interaction.raised`.\n */\n raise: {\n set: (source: string, ids: Iterable<string>) =>\n v('view:raise:set', (s) => void (s.interaction.raised = { ...s.interaction.raised, [source]: new Set(ids) })),\n clear: (source: string) =>\n v('view:raise:clear', (s) => {\n if (!(source in s.interaction.raised)) return;\n const next = { ...s.interaction.raised };\n delete next[source];\n s.interaction.raised = next;\n }),\n },\n\n // ── VIEW · interaction mode (the modeller \"tool\") ─────────────────────────\n viewMode: {\n /**\n * Switch the active mode. `args`, when given, **replaces** the mode's\n * parameters; omit it to keep the current ones (a tool's node kind\n * survives a trip through Select).\n */\n set: (mode: string, args?: Readonly<Record<string, string>>) =>\n v('view:viewMode:set', (s) => {\n s.interaction.viewMode = mode;\n if (args !== undefined) s.interaction.viewModeArgs = { ...args };\n }),\n /** Shallow-merge `patch` into the mode parameters. */\n setArgs: (patch: Readonly<Record<string, string>>) =>\n v('view:viewMode:setArgs', (s) => void (s.interaction.viewModeArgs = { ...s.interaction.viewModeArgs, ...patch })),\n },\n\n // ── VIEW · templates (e.g. node templates) ────────────────────────────────\n templates: {\n create: (template: unknown) =>\n v('view:template:create', (s) => void (s.definition.templates = [...s.definition.templates, template])),\n update: (id: string, patch: Bag) =>\n v('view:template:update', (s) => {\n s.definition.templates = s.definition.templates.map((t) =>\n (t as { id?: string }).id === id ? { ...(t as object), ...patch } : t,\n );\n }),\n remove: (id: string) =>\n v('view:template:remove', (s) => void (s.definition.templates = s.definition.templates.filter((t) => (t as { id?: string }).id !== id))),\n },\n\n // ── VIEW · control panels (floating chrome over the canvas) ───────────────\n controlPanels: {\n /** Add (or replace) the panel `id`. */\n add: (id: string, spec: ControlPanelSpec) =>\n v('view:controlPanel:add', (s) => void (s.definition.controlPanels[id] = spec)),\n /** Shallow-merge `patch` into panel `id` (`items` replaces). No-op when absent. */\n update: (id: string, patch: Partial<ControlPanelSpec>) =>\n v('view:controlPanel:update', (s) => {\n const cur = s.definition.controlPanels[id];\n if (cur) s.definition.controlPanels[id] = { ...cur, ...patch };\n }),\n show: (id: string) =>\n v('view:controlPanel:show', (s) => {\n const cur = s.definition.controlPanels[id];\n if (cur) s.definition.controlPanels[id] = { ...cur, visible: true };\n }),\n hide: (id: string) =>\n v('view:controlPanel:hide', (s) => {\n const cur = s.definition.controlPanels[id];\n if (cur) s.definition.controlPanels[id] = { ...cur, visible: false };\n }),\n remove: (id: string) => v('view:controlPanel:remove', (s) => void delete s.definition.controlPanels[id]),\n },\n\n // ── VIEW · theme ──────────────────────────────────────────────────────────\n theme: {\n set: (patch: Bag) => v('view:theme:set', (s) => void (s.definition.theme = { ...s.definition.theme, ...patch })),\n },\n\n // ── VIEW · scene (canvas-level definition) ────────────────────────────────\n scene: {\n set: (patch: Partial<CanvasSceneOptions>) =>\n v('view:scene:set', (s) => void (s.definition.canvas = { ...s.definition.canvas, ...patch })),\n setBackground: (backgroundColor: number) =>\n v('view:scene:setBackground', (s) => void (s.definition.canvas = { ...s.definition.canvas, backgroundColor })),\n setZoomLimits: (min: number, max: number) =>\n v('view:scene:setZoomLimits', (s) => void (s.definition.canvas = { ...s.definition.canvas, zoom: { min, max } })),\n },\n\n // ── RUNTIME · layout run status (observable, NOT synced) ───────────────────\n layoutStatus: {\n begin: (id: string, animate = false) =>\n v('view:layout:status:begin', (s) => void (s.runtime.layout = { running: true, activeId: id, animate, progress: animate ? 0 : null })),\n progress: (progress: number) =>\n v('view:layout:status:progress', (s) => void (s.runtime.layout = { ...s.runtime.layout, progress })),\n end: () =>\n v('view:layout:status:end', (s) => void (s.runtime.layout = { ...s.runtime.layout, running: false, progress: null })),\n },\n\n // ── RUNTIME · transient overlay message ───────────────────────────────────\n message: {\n show: (text: string) => v('view:message:show', (s) => void (s.runtime.message = text)),\n clear: () => v('view:message:clear', (s) => void (s.runtime.message = null)),\n },\n\n // ── VIEW · focus (highlight-neighbourhood; O(1) set + mode — §7.1B) ────────\n focus: {\n set: (ids: Iterable<string>, dim = true) =>\n v('view:focus:set', (s) => void (s.interaction.focus = { ids: new Set(ids), dim })),\n clear: () => v('view:focus:clear', (s) => void (s.interaction.focus = null)),\n },\n\n // ── VIEW · inspect (whose properties are open) ────────────────────────────\n inspect: {\n set: (id: string) => v('view:inspect:set', (s) => void (s.interaction.inspect = id)),\n clear: () => v('view:inspect:clear', (s) => void (s.interaction.inspect = null)),\n },\n\n // ── VIEW · camera intent (frame the focus / the visible / everything) ─────\n cameraIntent: {\n /** Ask for a framing; the owner performs it once the canvas settles. */\n request: (intent: CameraIntent) =>\n v(\n 'view:cameraIntent:request',\n (s) => void (s.interaction.cameraIntent = { intent, seq: (s.interaction.cameraIntent?.seq ?? 0) + 1 }),\n ),\n },\n\n // ── VIEW · transient pins (drag/resize gesture locks; NOT data `pinned`) ───\n transientPins: {\n add: (ids: Iterable<string>) =>\n v('view:transientPins:add', (s) => void (s.interaction.transientPins = new Set([...s.interaction.transientPins, ...ids]))),\n remove: (ids: Iterable<string>) =>\n v('view:transientPins:remove', (s) => {\n const next = new Set(s.interaction.transientPins);\n for (const id of ids) next.delete(id);\n s.interaction.transientPins = next;\n }),\n clear: () => v('view:transientPins:clear', (s) => void (s.interaction.transientPins = new Set())),\n },\n };\n}\n\n/** The named, action-typed command API (see {@link createActions}). */\nexport type CanvasActions = ReturnType<typeof createActions>;\n","/** Who emitted an event. */\nexport type EventSourceKind = 'canvas' | 'layer' | 'behaviour' | 'layout' | 'store' | 'data';\n\n/** The emitting instance — `kind` + its id. */\nexport interface EventSource {\n kind: EventSourceKind;\n id: string;\n}\n\n/**\n * A structured event envelope as seen on the **tap** channel: the type, a\n * timestamp, the source instance, and the payload. One tap subscriber reading\n * these reconstructs the whole loop (input → state change → render) for telemetry\n * and collaboration.\n */\nexport interface CanvasEvent<P = unknown> {\n type: string;\n timestamp: number;\n source: EventSource;\n payload: P;\n}\n\n/** The default source for bus-level emits with no explicit origin. */\nexport const CANVAS_SOURCE: EventSource = { kind: 'canvas', id: 'canvas' };\n","import type { SpecFlush } from '../../specs/SpecStore';\nimport type { LayerFlush } from '../data/LayerData';\nimport type { FrameTick } from '../frame';\nimport type { ResolvedTheme } from '../theme/types';\nimport { CANVAS_SOURCE, type CanvasEvent, type EventSource } from './CanvasEvent';\nimport { EventEmitter, type Listener } from './EventEmitter';\n\n/**\n * The canvas-wide event map. Consumers (engine, domain) **augment** this via\n * declaration merging — `declare module '@invana/canvas-core' { interface\n * CanvasGlobalEvents { 'shape:click': … } }` — so new events are typed without\n * touching the core.\n */\nexport interface CanvasGlobalEvents {\n // ── coarse aggregate channels (kernel-emitted) ──────────────────────────────\n /**\n * A `view`-store mutation, bridged onto the bus (see `createCanvasStore`).\n * `durationMs` is the update's produce+commit wall-clock cost, when the store\n * reports it — so a tap can attribute time without a separate telemetry sink.\n */\n 'state:change': { action?: string; changedPaths: string[]; durationMs?: number };\n /** A `layer` data flush (nodes/edges/groups/annotations delta), bridged onto the bus. */\n 'data:flush': { layerId: string; delta: LayerFlush };\n /**\n * One layer's coalesced **spec** changes — the visual description, ids only.\n * Domain-free by construction: a renderer subscribes to this and never learns\n * what a node or an edge is. See `docs/renderer-split-design.md` §4.2b.\n */\n 'specs:flush': { layerId: string; delta: SpecFlush };\n /** A named data **intent** — one per data action (audit / collab), distinct from the per-frame flush. */\n 'data:intent': { action: string; layerId: string; ids: readonly string[] };\n\n // ── scene — registry composition (engine-emitted) ───────────────────────────\n 'scene:layer:add': { id: string };\n 'scene:layer:remove': { id: string };\n /**\n * A layer's whole-layer `visible` flag changed via `Layer.setVisible`. Lets\n * dependent layers (e.g. a `MiniMapLayer` mirroring a source graph) react\n * without polling. `visible` is the post-change value.\n */\n 'scene:layer:visibilitychange': { id: string; visible: boolean };\n 'scene:behaviour:register': { id: string };\n /**\n * A behaviour was removed via `BehaviourRegistry.unregister` (or `clear`).\n * Fires after `scene:behaviour:disable` (when it was enabled) and after the\n * behaviour is destroyed — the counterpart of `scene:layer:remove`.\n */\n 'scene:behaviour:unregister': { id: string };\n 'scene:behaviour:enable': { id: string };\n 'scene:behaviour:disable': { id: string };\n 'scene:layout:add': { id: string };\n 'scene:layout:remove': { id: string };\n\n // ── input — raw user input (engine/renderer-emitted; behaviours consume) ─────\n 'input:node:click': { layerId: string; id: string; x: number; y: number };\n 'input:node:hover': { layerId: string; id: string | null };\n 'input:node:drag:start': { layerId: string; id: string };\n 'input:node:drag:end': { layerId: string; id: string };\n 'input:background:click': { x: number; y: number };\n 'input:background:contextmenu': { x: number; y: number };\n /**\n * A pan **gesture** reported by the renderer (drag / keyboard / inertia) —\n * gesture *intent*, distinct from the resulting `view.interaction.camera` change\n * (a `state:change`). `x`/`y` are the world-origin offset the camera settled on.\n */\n 'input:camera:pan': { x: number; y: number };\n /** A zoom **gesture** reported by the renderer (wheel / pinch). `scale` is the resolved uniform zoom; `center*` the screen pivot. */\n 'input:camera:zoom': { scale: number; centerX: number; centerY: number };\n\n // ── layout — execution lifecycle (engine-emitted) ───────────────────────────\n /** A layout run started. `nodeCount`/`edgeCount`/`animate` describe the run when the producer knows them. */\n 'layout:run:start': {\n id: string;\n layerId: string;\n nodeCount?: number;\n edgeCount?: number;\n animate?: boolean;\n /** The run was asked to leave the camera alone (`LayoutRunOptions.preserveCamera`). */\n preserveCamera?: boolean;\n /** The run frames itself (`LayoutRunOptions.fitCamera`) — other fitters stand down. */\n fitCamera?: boolean;\n };\n /** A layout run ended. `reason` distinguishes a natural settle from an external stop / abort. */\n 'layout:run:end': {\n id: string;\n layerId: string;\n reason?: 'settled' | 'stopped' | 'cancelled';\n /** The run was asked to leave the camera alone (`LayoutRunOptions.preserveCamera`). */\n preserveCamera?: boolean;\n /** The run frames itself (`LayoutRunOptions.fitCamera`) — other fitters stand down. */\n fitCamera?: boolean;\n };\n 'layout:run:tick': { id: string; progress?: number; preserveCamera?: boolean; fitCamera?: boolean };\n /** An off-screen solve advanced — `done` of `total` iterations. Nothing is drawn until `layout:run:tick` / `end`. */\n 'layout:run:progress': { id: string; layerId: string; done: number; total: number };\n\n // ── render / canvas — lifecycle (engine/renderer-emitted) ───────────────────\n 'canvas:renderer:ready': { backend: string; capabilities?: Record<string, unknown> };\n /**\n * The active renderer crashed at **render time** and the engine has halted its\n * render loop. Emitted once (experimental WebGPU only — see\n * `CanvasOptions.preference`); the consumer should tear the canvas down and\n * re-init on `to` (WebGL). `reason` is a short diagnostic tag.\n */\n 'canvas:renderer:fallback': { from: string; to: string; reason?: string };\n /**\n * One measured engine frame — emitted once per `Canvas.tickOnce`. Carries the\n * inter-frame period, per-phase CPU breakdown, and the attributed\n * {@link InteractionKind}, so a tap can drive an FPS trace + attribute dips to\n * the gesture that caused them. See {@link FrameTick}.\n */\n 'render:loop:tick': FrameTick;\n /** The shared status-message channel. `text: null` clears; `timeout` (ms) auto-clears. */\n 'canvas:message:show': { text: string | null; timeout?: number };\n /** A tap dropped an event (filtered or sampled out) — diagnostic. */\n 'tap:dropped': { type: string; reason: 'excluded' | 'sampled' };\n\n // ── theme — resolved-theme broadcast (CanvasThemeState.set) ──────────────────\n 'theme:change': ResolvedTheme;\n}\n\n/**\n * The granular **`<domain>:<subject>:<action>`** types (`view:layer:setStyle`,\n * `data:node:add`, …) are open-ended — emitted via {@link CanvasEventBus.publish}\n * (they ride on the tap, keyed by the action label) rather than enumerated here.\n * The map above types the **finite, engine-emitted** events for `on()`/`emit()`.\n */\n\n/** Per-tap filters. */\nexport interface TapOptions {\n /** Event `type`s to drop from this tap. */\n exclude?: readonly string[];\n /** Fraction (0..1) of events to forward — cheap sampling for costly sinks. */\n sampleRate?: number;\n}\n\n/** A tap receives every emission as a structured {@link CanvasEvent}. */\nexport type Tap = (event: CanvasEvent) => void;\n\n/**\n * Canvas-wide event bus: typed `on`/`emit` for known events, **plus a tap\n * channel** that receives every emission (typed *and* forwarded scoped events) as\n * a structured {@link CanvasEvent}. The tap is the single place telemetry /\n * collaboration observe the whole stream — `bus.tap(e => sink(e))`.\n *\n * Renderer-free: the engine wires pixi pointer events *into* this; the bus knows\n * nothing about pixi.\n */\nexport class CanvasEventBus {\n private readonly emitter = new EventEmitter<CanvasGlobalEvents>();\n private readonly taps = new Set<{ fn: Tap; opts: TapOptions }>();\n private readonly now: () => number;\n private readonly rand: () => number;\n\n constructor(opts?: { now?: () => number; random?: () => number }) {\n this.now = opts?.now ?? (() => Date.now());\n this.rand = opts?.random ?? (() => Math.random());\n }\n\n /** Subscribe to a typed global event. Returns an unsubscribe fn (or use {@link off}). */\n on<K extends keyof CanvasGlobalEvents>(\n type: K,\n listener: Listener<CanvasGlobalEvents[K]>,\n ): () => void {\n return this.emitter.on(type, listener);\n }\n\n /** Remove a previously-registered typed listener (the {@link on} handler by reference). */\n off<K extends keyof CanvasGlobalEvents>(\n type: K,\n listener: Listener<CanvasGlobalEvents[K]>,\n ): void {\n this.emitter.off(type, listener);\n }\n\n /** Emit a typed global event — reaches typed listeners and the tap channel. */\n emit<K extends keyof CanvasGlobalEvents>(\n type: K,\n payload: CanvasGlobalEvents[K],\n source: EventSource = CANVAS_SOURCE,\n ): void {\n this.emitter.emit(type, payload);\n this.toTaps(type as string, payload, source);\n }\n\n /**\n * Forward a **scoped / foreign** event (not in {@link CanvasGlobalEvents}) to the\n * tap channel only — used by {@link SourceEmitter} so a store/layer/behaviour's\n * own events reach the canvas tap without being global-bus types.\n */\n publish(type: string, payload: unknown, source: EventSource): void {\n this.toTaps(type, payload, source);\n }\n\n private toTaps(type: string, payload: unknown, source: EventSource): void {\n if (this.taps.size === 0) return;\n const event: CanvasEvent = { type, timestamp: this.now(), source, payload };\n for (const { fn, opts } of [...this.taps]) {\n if (opts.exclude?.includes(type)) continue;\n if (opts.sampleRate !== undefined && this.rand() > opts.sampleRate) continue;\n fn(event);\n }\n }\n\n /** Subscribe to the whole event stream (structured envelopes). */\n tap(fn: Tap, opts: TapOptions = {}): () => void {\n const entry = { fn, opts };\n this.taps.add(entry);\n return () => this.taps.delete(entry);\n }\n\n clearTaps(): void {\n this.taps.clear();\n }\n\n removeAllListeners(): void {\n this.emitter.removeAllListeners();\n this.taps.clear();\n }\n}\n","import type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { ResolvedTheme, ThemeState } from './types';\n\n/**\n * The default {@link ThemeState} — holds the current {@link ResolvedTheme} and\n * broadcasts `theme:change` on the bus whenever it is {@link set}. Renderer-free;\n * a single publisher (the domain `ThemeBehaviour`) resolves authored config →\n * `ResolvedTheme` and calls {@link set}. Theme-aware layers subscribe to\n * `theme:change` (or read {@link current}) and recolour.\n */\nexport class CanvasThemeState implements ThemeState {\n private _current: ResolvedTheme | null = null;\n\n constructor(private readonly bus: CanvasEventBus) {}\n\n current(): ResolvedTheme | null {\n return this._current;\n }\n\n set(theme: ResolvedTheme): void {\n this._current = theme;\n this.bus.emit('theme:change', theme, { kind: 'store', id: 'theme' });\n }\n}\n","/**\n * Renderer-free **theme state** for the kernel — the fully-**resolved** theme the\n * engine publishes and theme-aware layers recolour from. Relocated from the\n * engine (`@invana/canvas`); roles are plain `string` keys → colour numbers (the\n * named `ColorRole` vocabulary stays in `@invana/graph`).\n *\n * Two distinct things, don't conflate them:\n * - **Authored theme config** (registry / active family / mode / accent) lives in\n * `view.definition.theme` (serialisable, synced).\n * - **The resolved theme** below is the *derived* output a `ThemeBehaviour`\n * computes from that config + mode, and publishes via {@link ThemeState.set}.\n */\n\n/** The concrete kind a theme mode resolves to. */\nexport type ThemeKind = 'light' | 'dark';\n\n/** Mode selector. `'system'` follows the host `prefers-color-scheme`; the rest pin. */\nexport type ThemeMode = 'system' | 'light' | 'dark';\n\n/** A fully-resolved theme — every role already a colour number. Plain JSON; no pixi. */\nexport interface ResolvedTheme {\n readonly kind: ThemeKind;\n /** Opaque family name (`'default'` | `'forest'` | …) — meaningful to the app, not the kernel. */\n readonly name: string;\n /** Role name → `0xRRGGBB`. The engine theme has no role *enum*; roles are strings. */\n readonly palette: Readonly<Record<string, number>>;\n /** Optional fill-by-category ramp (consumed by colour-by-label / minimap). */\n readonly categorical?: readonly number[];\n}\n\n/** The theme channel — read the current resolved theme, or set (and broadcast) a new one. */\nexport interface ThemeState {\n /** The current resolved theme, or `null` before the first {@link set}. */\n current(): ResolvedTheme | null;\n /** Store + broadcast a resolved theme (emits `theme:change`). */\n set(theme: ResolvedTheme): void;\n}\n\n// ─── The `inherit` sentinel ──────────────────────────────────────────────────\n\n/**\n * The **inherit sentinel** — the value a themed colour option carries to mean\n * *\"resolve me from the active theme's palette\"* rather than pinning a colour.\n *\n * It exists because a single-tier option has no other way to say it. An option\n * that is simply absent falls back to a hardcoded default; an option holding a\n * colour pins that colour. `'inherit'` is the third state, and it is the one\n * that should usually be the *default*:\n *\n * | Value | Meaning |\n * |---|---|\n * | `'inherit'` | Follow the palette role the surface declares. Recolours on every `theme:change` |\n * | `0x0f172a` / `'#0f172a'` | Pinned by the author. The theme never touches it |\n *\n * **Config vocabulary, never spec vocabulary.** `'inherit'` is legal in a\n * serialisable *option* and is resolved — via {@link resolveThemed} — at the\n * moment a surface paints. It must never reach a renderer spec: the renderer\n * sees numbers, always.\n *\n * Cascading surfaces don't need it. Where a value already resolves through\n * tiers (a graph node's style: layer template → per-type binding → per-node →\n * state), **absence already means inherit**, exactly as in CSS, and the theme\n * belongs in a tier *below* the author rather than in a sentinel.\n *\n * @see rfc:feat-2026-09-11-a-colour-is-either-themed-or-manual-never-both\n */\nexport const INHERIT = 'inherit';\n\n/** The literal type of {@link INHERIT}. */\nexport type Inherit = typeof INHERIT;\n\n/**\n * A themed option: either a concrete value of `T` (pinned by the author) or\n * {@link INHERIT} (resolved from the palette). Resolve with\n * {@link resolveThemed}.\n */\nexport type Themed<T> = T | Inherit;\n\n/** Narrow a themed option to the {@link INHERIT} sentinel. */\nexport function isInherit(value: unknown): value is Inherit {\n return value === INHERIT;\n}\n\n/**\n * Resolve a themed colour option against a published palette.\n *\n * A concrete value passes through untouched — an author-set colour always wins\n * over the theme, and keeps winning across theme switches. {@link INHERIT}\n * reads the first of `roles` the palette actually carries, falling back to\n * `fallback` when no theme has been published yet or the palette omits every\n * role (which is what the single-layer `ThemeBehaviour` shorthand's empty\n * palette does).\n *\n * @param value The option as authored — a colour, or {@link INHERIT}.\n * @param palette The active `ResolvedTheme.palette`, or `null` before the first publish.\n * @param roles Role name, or names tried in order (e.g. `['divider', 'stroke']`).\n * @param fallback Used when `value` is `'inherit'` and no role resolves.\n *\n * @example\n * ```ts\n * // `backgroundColor` defaults to 'inherit' → follows the theme's `surface`\n * const fill = resolveThemed(opts.backgroundColor, theme?.palette, 'surface', '#f8fafc');\n * ```\n */\nexport function resolveThemed<T>(\n value: Themed<T>,\n palette: Readonly<Record<string, number>> | null | undefined,\n roles: string | readonly string[],\n fallback: T,\n): T | number {\n if (!isInherit(value)) return value;\n if (palette) {\n for (const role of typeof roles === 'string' ? [roles] : roles) {\n const resolved = palette[role];\n if (resolved !== undefined) return resolved;\n }\n }\n return fallback;\n}\n","/**\n * `ColumnStore<TSchema>` — typed-array column store for **bulk hot data** (the\n * kernel's machine-rate **DATA-HOT lane**: node `x`/`y`, flags, bulk attrs).\n *\n * Relocated into `@invana/canvas-store` (decision D1) so the renderer-free kernel\n * owns the data hot path; `@invana/canvas` consumes it (and may re-export for\n * back-compat). Imports **no** drawing library.\n *\n * Designed to scale to millions of items at machine-rate mutation (1000s/sec from\n * external feeds). Where the reactive store (immer) makes per-mutation\n * structural-sharing trade-offs that cap out around 5–10k for hot data,\n * `ColumnStore` mutates typed-array slots in place at ~10 ns per write — so\n * layout churn / position streams **never** touch the reactive/CRDT path.\n *\n * **Mental model:** one id-keyed object `{ id:'n-42', x:100, y:50 }` becomes\n * slot 17 across N parallel typed-array columns. Lookup is id → slot\n * (`Map<string, number>`), then columns are read/written by indexing slot. Slots\n * recycle on remove, so buffers stay compact under churn.\n *\n * @example\n * type NodeSchema = { x: 'f32'; y: 'f32'; flags: 'u8' };\n * const nodes = new ColumnStore<NodeSchema>({ x: 'f32', y: 'f32', flags: 'u8' });\n * nodes.add('n-1', { x: 10, y: 20, flags: 0 });\n * // Renderer / layout fast path — hold refs once, write directly:\n * const xCol = nodes.column('x'); const slot = nodes.slot('n-1')!;\n * xCol[slot] = 40; // ~10 ns\n * nodes.touch(); // bump version after fast-path writes\n */\n\n// ─── Schema ───────────────────────────────────────────────────────────────\n\n/**\n * Numeric type tags for typed-array columns. Each maps to a JS TypedArray ctor.\n * `i8/u8` — bytes (booleans, bitfields, packed enums); `i16/u16` — short ints;\n * `i32/u32` — slot refs / packed colours / hashes; `f32` — coordinates / weights\n * (default); `f64` — only when precision matters.\n */\nexport type ColumnType = 'i8' | 'u8' | 'i16' | 'u16' | 'i32' | 'u32' | 'f32' | 'f64';\n\nexport type ColumnSchema = Record<string, ColumnType>;\n\n// All TypedArray slots round-trip as `number`.\nexport type ColumnValue<T extends ColumnType> = T extends 'f32' | 'f64' ? number : number;\n\n// Map a `ColumnType` tag to its underlying TypedArray.\nexport type ColumnArray<T extends ColumnType> = T extends 'i8'\n ? Int8Array\n : T extends 'u8'\n ? Uint8Array\n : T extends 'i16'\n ? Int16Array\n : T extends 'u16'\n ? Uint16Array\n : T extends 'i32'\n ? Int32Array\n : T extends 'u32'\n ? Uint32Array\n : T extends 'f32'\n ? Float32Array\n : T extends 'f64'\n ? Float64Array\n : never;\n\n/** Shape of a row in `add()` / `addBulk()`: each schema field maps to a number. */\nexport type RowOf<TSchema extends ColumnSchema> = {\n [K in keyof TSchema]: ColumnValue<TSchema[K]>;\n};\n\n// ─── TypedArray ctor lookup ───────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst TYPED_ARRAY_CTOR: Record<ColumnType, new (length: number) => any> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n};\n\n// ─── Options ──────────────────────────────────────────────────────────────\n\nexport interface ColumnStoreOptions {\n /** Initial slot capacity. Doubles on overflow. Default 256. */\n initialCapacity?: number;\n /** Max capacity. Throws on overflow. Default 16_777_216 (~16M). */\n maxCapacity?: number;\n}\n\n// ─── ColumnStore ──────────────────────────────────────────────────────────\n\nexport class ColumnStore<TSchema extends ColumnSchema = ColumnSchema> {\n private readonly schema: TSchema;\n private readonly columnNames: readonly (keyof TSchema)[];\n private readonly maxCapacity: number;\n\n /** id → slot. The only object-keyed lookup on the hot path. */\n private readonly idIndex: Map<string, number> = new Map();\n /** slot → id. Filled slots have a string; recycled holes have `undefined`. */\n private readonly idReverse: (string | undefined)[] = [];\n /** Stack of recycled slots. `add()` pops from here before extending. */\n private readonly freeSlots: number[] = [];\n\n /** TypedArray per column. Replaced on grow (new buffer with copied data). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private columns: Record<keyof TSchema, any>;\n\n /** Current capacity (length of each TypedArray). */\n private _capacity: number;\n /** High-water mark — largest slot index ever assigned + 1. Not necessarily filled. */\n private _highWater = 0;\n\n /** Mutation version. Increments on any add/remove/set or `touch()`. */\n private _version = 0;\n\n constructor(schema: TSchema, opts: ColumnStoreOptions = {}) {\n this.schema = schema;\n this.columnNames = Object.keys(schema) as (keyof TSchema)[];\n this._capacity = Math.max(1, opts.initialCapacity ?? 256);\n this.maxCapacity = opts.maxCapacity ?? 16_777_216;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.columns = {} as Record<keyof TSchema, any>;\n for (const name of this.columnNames) {\n const Ctor = TYPED_ARRAY_CTOR[schema[name]];\n this.columns[name] = new Ctor(this._capacity);\n }\n }\n\n // ─── Read accessors ─────────────────────────────────────────────────────\n\n /** Number of items currently stored. */\n get size(): number {\n return this.idIndex.size;\n }\n\n /** Current allocated capacity. Grows automatically when filled. */\n get capacity(): number {\n return this._capacity;\n }\n\n /** Mutation counter — bumps on any change. Subscribers diff this. */\n get version(): number {\n return this._version;\n }\n\n /** True iff `id` has been added. */\n has(id: string): boolean {\n return this.idIndex.has(id);\n }\n\n /** Returns the slot for `id`, or `undefined`. Useful for the renderer fast path. */\n slot(id: string): number | undefined {\n return this.idIndex.get(id);\n }\n\n /** Returns the id at `slot`, or `undefined` if the slot is free. */\n idAt(slot: number): string | undefined {\n return this.idReverse[slot];\n }\n\n /**\n * Direct access to a column's TypedArray. **Holds a stable reference until the\n * column is grown** (then the buffer is replaced). Use {@link version} to detect\n * grow events. Renderer/layout fast path: cache `column(name)` + `slot(id)` once\n * per frame and write directly, then call {@link touch}.\n */\n column<K extends keyof TSchema>(name: K): ColumnArray<TSchema[K]> {\n return this.columns[name] as ColumnArray<TSchema[K]>;\n }\n\n /** Read a single value. ~50 ns: Map.get + TypedArray read. */\n get<K extends keyof TSchema>(id: string, name: K): ColumnValue<TSchema[K]> | undefined {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return undefined;\n return this.columns[name][slot] as ColumnValue<TSchema[K]>;\n }\n\n /** Materialise a full row by id. Allocates an object — avoid in hot loops. */\n row(id: string): RowOf<TSchema> | undefined {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return undefined;\n const out = {} as RowOf<TSchema>;\n for (const name of this.columnNames) {\n out[name] = this.columns[name][slot];\n }\n return out;\n }\n\n // ─── Mutation ───────────────────────────────────────────────────────────\n\n /** Add a new item. Throws if `id` already exists. Reuses a recycled slot when available. */\n add(id: string, row: RowOf<TSchema>): number {\n if (this.idIndex.has(id)) {\n throw new Error(`ColumnStore: id \"${id}\" already exists`);\n }\n const slot = this.allocSlot();\n this.idIndex.set(id, slot);\n this.idReverse[slot] = id;\n for (const name of this.columnNames) {\n this.columns[name][slot] = row[name];\n }\n this._version++;\n return slot;\n }\n\n /** Bulk add. Grows once if needed (cheaper than N individual grows). Throws on duplicate id. */\n addBulk(items: ReadonlyArray<{ id: string; row: RowOf<TSchema> }>): void {\n if (items.length === 0) return;\n const projected = this.idIndex.size + items.length;\n if (projected > this._capacity) this.grow(projected);\n for (const { id, row } of items) {\n if (this.idIndex.has(id)) {\n throw new Error(`ColumnStore.addBulk: id \"${id}\" already exists`);\n }\n const slot = this.allocSlot();\n this.idIndex.set(id, slot);\n this.idReverse[slot] = id;\n for (const name of this.columnNames) {\n this.columns[name][slot] = row[name];\n }\n }\n this._version++;\n }\n\n /** Set a single field. ~50 ns. No-op if id doesn't exist. */\n set<K extends keyof TSchema>(id: string, name: K, value: ColumnValue<TSchema[K]>): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n this.columns[name][slot] = value;\n this._version++;\n }\n\n /** Update multiple fields of one item in one call (one version bump). */\n update(id: string, partial: Partial<RowOf<TSchema>>): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n for (const name of this.columnNames) {\n if (name in partial) {\n this.columns[name][slot] = partial[name] as number;\n }\n }\n this._version++;\n }\n\n /** Remove an item. Recycles the slot. No-op if id doesn't exist. */\n remove(id: string): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n this.idIndex.delete(id);\n this.idReverse[slot] = undefined;\n this.freeSlots.push(slot);\n this._version++;\n }\n\n /** Bulk remove. */\n removeBulk(ids: readonly string[]): void {\n for (const id of ids) {\n const slot = this.idIndex.get(id);\n if (slot === undefined) continue;\n this.idIndex.delete(id);\n this.idReverse[slot] = undefined;\n this.freeSlots.push(slot);\n }\n this._version++;\n }\n\n /**\n * Mark the store as mutated without an API change — call after batches of\n * fast-path writes via `column(...)[slot] = ...` so version-driven subscribers\n * re-read.\n */\n touch(): void {\n this._version++;\n }\n\n /** Drop all items + recycled slots. Keeps capacity (no shrink). */\n clear(): void {\n this.idIndex.clear();\n this.idReverse.length = 0;\n this.freeSlots.length = 0;\n this._highWater = 0;\n this._version++;\n }\n\n // ─── Iteration ──────────────────────────────────────────────────────────\n\n /** Iterate (id, slot) for currently-live ids. O(size) — does not walk holes. */\n forEach(cb: (id: string, slot: number) => void): void {\n for (const [id, slot] of this.idIndex) cb(id, slot);\n }\n\n /** Iterator over live ids only. */\n ids(): IterableIterator<string> {\n return this.idIndex.keys();\n }\n\n // ─── Internals ──────────────────────────────────────────────────────────\n\n private allocSlot(): number {\n const recycled = this.freeSlots.pop();\n if (recycled !== undefined) return recycled;\n if (this._highWater >= this._capacity) this.grow(this._capacity * 2);\n return this._highWater++;\n }\n\n /** Grow each column to at least `target` (doubling past it). */\n private grow(target: number): void {\n let next = this._capacity;\n while (next < target) next *= 2;\n if (next > this.maxCapacity) {\n throw new Error(`ColumnStore: requested capacity ${target} exceeds max ${this.maxCapacity}`);\n }\n for (const name of this.columnNames) {\n const Ctor = TYPED_ARRAY_CTOR[this.schema[name]];\n const grown = new Ctor(next);\n grown.set(this.columns[name]);\n this.columns[name] = grown;\n }\n this._capacity = next;\n }\n}\n","/**\n * `LayerData` — the **non-reactive** graph data for one source: four record\n * collections (nodes · edges · groups · annotations) with full CRUD, **bulk\n * position updates** (layout output), and **one coalesced `flush` per frame**\n * carrying a per-kind delta. Subscribers (the renderer) rebuild only the delta.\n *\n * **Two lanes (the two physics).** Bulk + machine-rate → it lives *outside* the\n * reactive `view` store:\n * - **COLD** — `Map<id, record>` for human-rate fields (payload/label/style/…).\n * - **HOT** — a typed-array {@link ColumnStore} for node **positions** (`x`/`y`)\n * and a `flags` byte (has-position / pinned / disabled / hidden). A position\n * write is ~10 ns (one `Float32Array` slot), no per-node object, no GC. The\n * layout/renderer fast path holds the column ref and writes slots directly\n * (see {@link positions} + {@link touchPositions}).\n *\n * `node(id)` stitches the two lanes back into one record on read (cold reads are\n * human-rate; the hot path reads the column directly). The `flush` delta shape is\n * **unchanged** by the lane split — `moved` (position-only) stays separate from\n * `changed` (structure), so a move is a transform-only re-render.\n *\n * **When** the coalesced flush fires is the {@link FlushMode} (default `'microtask'`);\n * the engine flips its stores to `'manual'` and drains them from one rAF loop. See\n * `docs/canvas-store-data-event-flow.md` §2.2.\n */\n\nimport { ColumnStore } from './ColumnStore';\nimport { scheduleFlush, type FlushMode } from './flush';\n\nexport interface NodeRecord {\n id: string;\n x?: number;\n y?: number;\n [key: string]: unknown;\n}\nexport interface EdgeRecord {\n id: string;\n source: string;\n target: string;\n [key: string]: unknown;\n}\nexport interface GroupRecord {\n id: string;\n memberIds: string[];\n /** Derived encapsulating geometry (hull / rect / …) — computed by a deriver. */\n geometry?: unknown;\n [key: string]: unknown;\n}\nexport interface AnnotationRecord {\n id: string;\n kind: string;\n [key: string]: unknown;\n}\n\n/** Added / changed / removed ids for one collection. */\nexport interface KindDelta {\n added: string[];\n changed: string[];\n removed: string[];\n}\n/** Nodes also carry `moved` — position-only changes (transform-only re-render). */\nexport interface NodeDelta extends KindDelta {\n /** Ids whose position changed this frame. Empty when {@link movedAll} is set. */\n moved: string[];\n /**\n * Every node moved (a force-sim tick via {@link LayerData.touchPositions}) —\n * `moved` is left **empty** so the kernel doesn't allocate an N-id array each\n * frame; the renderer iterates all positions directly. O(1) per flush.\n */\n movedAll: boolean;\n}\n\n/** The per-frame coalesced delta across all four collections. */\nexport interface LayerFlush {\n nodes: NodeDelta;\n edges: KindDelta;\n groups: KindDelta;\n annotations: KindDelta;\n /** Monotonic version — bumps once per flush. */\n version: number;\n}\n\n/** Bulk seed/replace input. */\nexport interface GraphInput {\n nodes?: readonly NodeRecord[];\n edges?: readonly EdgeRecord[];\n groups?: readonly GroupRecord[];\n annotations?: readonly AnnotationRecord[];\n}\n\n/** The hot-lane schema: positions (`x`/`y`) + a packed `flags` byte. */\nexport type PosSchema = { x: 'f32'; y: 'f32'; flags: 'u8' };\nconst POS_SCHEMA: PosSchema = { x: 'f32', y: 'f32', flags: 'u8' };\n\n/** Bits in the node `flags` column. `HAS_POSITION` distinguishes unset from `(0,0)`. */\nexport const NODE_FLAG = {\n HAS_POSITION: 1,\n PINNED: 2,\n DISABLED: 4,\n HIDDEN: 8,\n} as const;\n\n/** Streaming/ingestion lifecycle for a data source. */\nexport type QueryStatus = 'idle' | 'loading' | 'streaming' | 'error';\n\n/** A named data mutation, recorded for audit / collaboration (distinct from the per-frame flush). */\nexport interface IntentLogEntry {\n action: string;\n ids?: readonly string[];\n ts: number;\n}\n\ninterface KindDirty {\n added: Set<string>;\n changed: Set<string>;\n removed: Set<string>;\n}\nconst newDirty = (): KindDirty => ({ added: new Set(), changed: new Set(), removed: new Set() });\nconst drain = (d: KindDirty): KindDelta => ({\n added: [...d.added],\n changed: [...d.changed],\n removed: [...d.removed],\n});\nconst clearDirty = (d: KindDirty): void => {\n d.added.clear();\n d.changed.clear();\n d.removed.clear();\n};\n\nexport class LayerData {\n /** COLD lane — node records WITHOUT `x`/`y` (positions live in {@link _pos}). */\n private readonly _nodes = new Map<string, NodeRecord>();\n /** HOT lane — typed-array `x`/`y`/`flags` columns, keyed by node id. */\n private readonly _pos = new ColumnStore<PosSchema>(POS_SCHEMA);\n private readonly _edges = new Map<string, EdgeRecord>();\n private readonly _groups = new Map<string, GroupRecord>();\n private readonly _annotations = new Map<string, AnnotationRecord>();\n\n private readonly dNodes = newDirty();\n private readonly dMoved = new Set<string>(); // position-only node changes\n private _movedAll = false; // set by touchPositions() — every node moved (direct-column fast path)\n private readonly dEdges = newDirty();\n private readonly dGroups = newDirty();\n private readonly dAnnotations = newDirty();\n\n private readonly listeners = new Set<(e: LayerFlush) => void>();\n private version = 0;\n private scheduled = false;\n private flushMode: FlushMode = 'microtask';\n private cancel: (() => void) | undefined;\n\n // ── stream / query status (small, human-rate; observable) ──────────────────\n private _status: QueryStatus = 'idle';\n private readonly _intents: IntentLogEntry[] = [];\n private readonly statusListeners = new Set<(status: QueryStatus) => void>();\n\n // ── subscribe ─────────────────────────────────────────────────────────────\n /** Subscribe to coalesced `flush` deltas. Returns an unsubscribe. */\n on(event: 'flush', listener: (e: LayerFlush) => void): () => void {\n void event;\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** {@link DataSource} contract — alias for `on('flush', …)`. */\n onFlush(listener: (e: LayerFlush) => void): () => void {\n return this.on('flush', listener);\n }\n\n /**\n * Choose **when** a flush fires ({@link FlushMode}). `'manual'` disarms any pending\n * auto-flush so only an explicit {@link flush} emits — used when the engine drives\n * every layer's data from one rAF loop.\n */\n setFlushMode(mode: FlushMode): void {\n this.flushMode = mode;\n if (mode === 'manual' && this.scheduled) {\n this.cancel?.();\n this.scheduled = false;\n }\n }\n\n // ── reads ─────────────────────────────────────────────────────────────────\n /** Read a node, **stitching** its cold record with its hot `x`/`y` (when set). */\n node(id: string): NodeRecord | undefined {\n const cold = this._nodes.get(id);\n if (!cold) return undefined;\n const slot = this._pos.slot(id);\n if (slot === undefined) return cold;\n const flags = this._pos.column('flags')[slot] ?? 0;\n if ((flags & NODE_FLAG.HAS_POSITION) === 0) return cold;\n return { ...cold, x: this._pos.column('x')[slot], y: this._pos.column('y')[slot] };\n }\n edge(id: string): EdgeRecord | undefined {\n return this._edges.get(id);\n }\n group(id: string): GroupRecord | undefined {\n return this._groups.get(id);\n }\n annotation(id: string): AnnotationRecord | undefined {\n return this._annotations.get(id);\n }\n nodes(): NodeRecord[] {\n return [...this._nodes.keys()].map((id) => this.node(id)!);\n }\n edges(): EdgeRecord[] {\n return [...this._edges.values()];\n }\n groups(): GroupRecord[] {\n return [...this._groups.values()];\n }\n annotations(): AnnotationRecord[] {\n return [...this._annotations.values()];\n }\n get counts(): { nodes: number; edges: number; groups: number; annotations: number } {\n return {\n nodes: this._nodes.size,\n edges: this._edges.size,\n groups: this._groups.size,\n annotations: this._annotations.size,\n };\n }\n\n // ── hot-lane fast path (layout / renderer) ─────────────────────────────────\n /**\n * Direct access to the typed-array position columns. Hold the ref + a slot once\n * and write in place (~10 ns/slot), then call {@link touchPositions} to emit one\n * coalesced moved flush. `positions.slot(id)` maps id → column index.\n */\n get positions(): ColumnStore<PosSchema> {\n return this._pos;\n }\n\n /**\n * Bulk-apply layout output from an **interleaved** `[x0,y0,x1,y1,…]` buffer —\n * the layout fast path. Skips ids that aren't present; marks each `moved`.\n */\n setPositionsBulk(ids: readonly string[], xy: ArrayLike<number>): void {\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n if (!this._nodes.has(id)) continue;\n this.writePos(id, xy[i * 2], xy[i * 2 + 1], false);\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n }\n this.schedule();\n }\n\n /**\n * After writing position slots directly via {@link positions}, call this to bump\n * the version and emit **one** flush that marks every node `moved` (the per-tick\n * force-sim path — \"everything moved\", transform-only).\n */\n touchPositions(): void {\n this._pos.touch();\n this._movedAll = true;\n this.schedule();\n }\n\n /** Read a node's `flags` byte, or `undefined`. */\n nodeFlags(id: string): number | undefined {\n return this._pos.get(id, 'flags');\n }\n\n /** Toggle a {@link NODE_FLAG} bit (e.g. pinned/disabled) — marks the node `changed`. */\n setNodeFlag(id: string, flag: number, on: boolean): void {\n const cur = this._pos.get(id, 'flags');\n if (cur === undefined) return;\n const next = on ? cur | flag : cur & ~flag;\n if (next === cur) return;\n this._pos.set(id, 'flags', next);\n if (!this.dNodes.added.has(id)) this.dNodes.changed.add(id);\n this.schedule();\n }\n\n // ── stream / query status ──────────────────────────────────────────────────\n /** Current ingestion lifecycle status. */\n get status(): QueryStatus {\n return this._status;\n }\n /** Set the ingestion status; notifies {@link onStatus} listeners on change. */\n setStatus(status: QueryStatus): void {\n if (status === this._status) return;\n this._status = status;\n for (const l of [...this.statusListeners]) l(status);\n }\n /** Subscribe to status changes. Returns an unsubscribe. */\n onStatus(listener: (status: QueryStatus) => void): () => void {\n this.statusListeners.add(listener);\n return () => this.statusListeners.delete(listener);\n }\n /** The data-mutation audit trail (one entry per named action). */\n intents(): readonly IntentLogEntry[] {\n return this._intents;\n }\n /** Record a named data intent (audit / collab). */\n logIntent(action: string, ids?: readonly string[], ts: number = Date.now()): void {\n this._intents.push({ action, ids, ts });\n }\n\n // ── bulk ──────────────────────────────────────────────────────────────────\n /** Replace the whole graph — diffs each collection into the next flush. */\n setData(input: GraphInput): void {\n if (input.nodes) this.replaceNodes(input.nodes);\n if (input.edges) this.replaceKind(this._edges, this.dEdges, input.edges);\n if (input.groups) this.replaceKind(this._groups, this.dGroups, input.groups);\n if (input.annotations) this.replaceKind(this._annotations, this.dAnnotations, input.annotations);\n this.schedule();\n }\n\n /** Bulk-apply layout output (positions) → marks nodes `moved` (transform-only). */\n applyPositions(positions: Iterable<{ id: string; x: number; y: number }>): void {\n for (const { id, x, y } of positions) {\n if (!this._nodes.has(id)) continue;\n this.writePos(id, x, y, false);\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n }\n this.schedule();\n }\n\n // ── nodes ─────────────────────────────────────────────────────────────────\n addNode(n: NodeRecord): void {\n this.upsertNode(n);\n this.schedule();\n }\n updateNode(id: string, patch: Partial<NodeRecord>): void {\n if (!this._nodes.has(id)) return;\n const keys = Object.keys(patch);\n const positionOnly = keys.length > 0 && keys.every((k) => k === 'x' || k === 'y');\n if ('x' in patch || 'y' in patch) {\n this.writePos(id, patch.x as number | undefined, patch.y as number | undefined, false);\n }\n const { x: _x, y: _y, ...rest } = patch;\n if (Object.keys(rest).length > 0) {\n const cur = this._nodes.get(id)!;\n this._nodes.set(id, { ...cur, ...rest } as NodeRecord);\n }\n if (positionOnly) {\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n } else {\n if (!this.dNodes.added.has(id)) this.dNodes.changed.add(id);\n this.dMoved.delete(id);\n }\n this.schedule();\n }\n removeNode(id: string): void {\n if (!this._nodes.has(id)) return;\n this._nodes.delete(id);\n this._pos.remove(id);\n this.dNodes.changed.delete(id);\n this.dMoved.delete(id);\n if (this.dNodes.added.delete(id)) {\n this.schedule();\n return; // added then removed before flush → net no-op\n }\n this.dNodes.removed.add(id);\n this.schedule();\n }\n\n // ── edges ─────────────────────────────────────────────────────────────────\n addEdge(e: EdgeRecord): void {\n this.upsert(this._edges, this.dEdges, e);\n this.schedule();\n }\n updateEdge(id: string, patch: Partial<EdgeRecord>): void {\n if (this.patchRecord(this._edges, this.dEdges, id, patch)) this.schedule();\n }\n removeEdge(id: string): void {\n this.removeFrom(this._edges, this.dEdges, id);\n this.schedule();\n }\n\n // ── groups ────────────────────────────────────────────────────────────────\n addGroup(g: GroupRecord): void {\n this.upsert(this._groups, this.dGroups, g);\n this.schedule();\n }\n updateGroup(id: string, patch: Partial<GroupRecord>): void {\n if (this.patchRecord(this._groups, this.dGroups, id, patch)) this.schedule();\n }\n removeGroup(id: string): void {\n this.removeFrom(this._groups, this.dGroups, id);\n this.schedule();\n }\n\n // ── annotations ───────────────────────────────────────────────────────────\n addAnnotation(a: AnnotationRecord): void {\n this.upsert(this._annotations, this.dAnnotations, a);\n this.schedule();\n }\n updateAnnotation(id: string, patch: Partial<AnnotationRecord>): void {\n if (this.patchRecord(this._annotations, this.dAnnotations, id, patch)) this.schedule();\n }\n removeAnnotation(id: string): void {\n this.removeFrom(this._annotations, this.dAnnotations, id);\n this.schedule();\n }\n\n // ── flush ─────────────────────────────────────────────────────────────────\n /** Emit the pending delta now (the engine calls this once per frame). */\n flush(): void {\n this.scheduled = false;\n const movedAll = this._movedAll;\n this._movedAll = false;\n const hasMoved = movedAll ? this._nodes.size > 0 : this.dMoved.size > 0;\n const empty =\n this.isClean(this.dNodes) &&\n !hasMoved &&\n this.isClean(this.dEdges) &&\n this.isClean(this.dGroups) &&\n this.isClean(this.dAnnotations);\n if (empty) return;\n\n // `movedAll` (force-sim tick) is signalled as a flag — never enumerated — so a\n // full-graph move is O(1) here; the renderer iterates the position column.\n const moved = movedAll ? [] : [...this.dMoved];\n\n const event: LayerFlush = {\n nodes: { ...drain(this.dNodes), moved, movedAll },\n edges: drain(this.dEdges),\n groups: drain(this.dGroups),\n annotations: drain(this.dAnnotations),\n version: ++this.version,\n };\n clearDirty(this.dNodes);\n this.dMoved.clear();\n clearDirty(this.dEdges);\n clearDirty(this.dGroups);\n clearDirty(this.dAnnotations);\n for (const l of [...this.listeners]) l(event);\n }\n\n // ── internals ─────────────────────────────────────────────────────────────\n private schedule(): void {\n if (this.scheduled || this.flushMode === 'manual') return;\n this.scheduled = true;\n this.cancel = scheduleFlush(this.flushMode, () => this.flush());\n }\n\n private isClean(d: KindDirty): boolean {\n return d.added.size === 0 && d.changed.size === 0 && d.removed.size === 0;\n }\n\n /** Insert/replace a node: cold record (minus x/y) + hot position columns. */\n private upsertNode(n: NodeRecord): void {\n const { x, y, ...rest } = n;\n const existed = this._nodes.has(n.id);\n this._nodes.set(n.id, rest as NodeRecord);\n this.writePos(n.id, x, y, true);\n if (existed) {\n this.dNodes.removed.delete(n.id);\n if (!this.dNodes.added.has(n.id)) this.dNodes.changed.add(n.id);\n } else {\n this.dNodes.added.add(n.id);\n this.dNodes.removed.delete(n.id);\n }\n }\n\n /**\n * Write a node's position into the hot column. `replace` (used on full upsert)\n * clears the `HAS_POSITION` bit when no `x`/`y` is supplied; otherwise a partial\n * update keeps the existing coordinate for an omitted axis.\n */\n private writePos(id: string, x: number | undefined, y: number | undefined, replace: boolean): void {\n const has = x !== undefined || y !== undefined;\n if (this._pos.has(id)) {\n if (has) {\n const cx = x ?? this._pos.get(id, 'x') ?? 0;\n const cy = y ?? this._pos.get(id, 'y') ?? 0;\n const flags = (this._pos.get(id, 'flags') ?? 0) | NODE_FLAG.HAS_POSITION;\n this._pos.update(id, { x: cx, y: cy, flags });\n } else if (replace) {\n const flags = (this._pos.get(id, 'flags') ?? 0) & ~NODE_FLAG.HAS_POSITION;\n this._pos.update(id, { x: 0, y: 0, flags });\n }\n } else {\n this._pos.add(id, { x: x ?? 0, y: y ?? 0, flags: has ? NODE_FLAG.HAS_POSITION : 0 });\n }\n }\n\n private replaceNodes(next: readonly NodeRecord[]): void {\n const nextIds = new Set(next.map((r) => r.id));\n for (const id of [...this._nodes.keys()]) {\n if (!nextIds.has(id)) this.removeNode(id);\n }\n for (const r of next) this.upsertNode(r);\n }\n\n private upsert<R extends { id: string }>(map: Map<string, R>, dirty: KindDirty, record: R): void {\n const existed = map.has(record.id);\n map.set(record.id, record);\n if (existed) {\n dirty.removed.delete(record.id);\n if (!dirty.added.has(record.id)) dirty.changed.add(record.id);\n } else {\n dirty.added.add(record.id);\n dirty.removed.delete(record.id);\n }\n }\n\n private patchRecord<R extends { id: string }>(\n map: Map<string, R>,\n dirty: KindDirty,\n id: string,\n patch: Partial<R>,\n ): boolean {\n const cur = map.get(id);\n if (!cur) return false;\n map.set(id, { ...cur, ...patch });\n if (!dirty.added.has(id)) dirty.changed.add(id);\n return true;\n }\n\n private removeFrom<R extends { id: string }>(map: Map<string, R>, dirty: KindDirty, id: string): boolean {\n if (!map.has(id)) return false;\n map.delete(id);\n dirty.changed.delete(id);\n if (dirty.added.delete(id)) return true; // added then removed before flush → net no-op\n dirty.removed.add(id);\n return true;\n }\n\n private replaceKind<R extends { id: string }>(\n map: Map<string, R>,\n dirty: KindDirty,\n next: readonly R[],\n ): void {\n const nextIds = new Set(next.map((r) => r.id));\n for (const id of [...map.keys()]) {\n if (!nextIds.has(id)) this.removeFrom(map, dirty, id);\n }\n for (const r of next) this.upsert(map, dirty, r);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/contracts/SpecProjector.ts","../src/state/events/EventEmitter.ts","../src/state/events/SourceEmitter.ts","../src/state/data/DirtyBatcher.ts","../src/abstracts/Layer.ts","../src/abstracts/Behaviour.ts","../src/abstracts/Layout.ts","../src/abstracts/GestureArbiter.ts","../src/state/port/select.ts","../src/lib/animation/easings.ts","../src/lib/animation/Tween.ts","../src/abstracts/Camera.ts","../src/abstracts/registries/LayerRegistry.ts","../src/abstracts/registries/BehaviourRegistry.ts","../src/abstracts/registries/LayoutRegistry.ts","../src/abstracts/registries/CommandRegistry.ts","../src/specs/geometry.ts","../src/specs/style.ts","../src/specs/shapeGeometry/polygonMath.ts","../src/specs/shapeGeometry/tabbedRect.ts","../src/specs/shapeGeometry/bounds.ts","../src/specs/shapeGeometry/contains.ts","../src/specs/shapeGeometry/index.ts","../src/state/data/flush.ts","../src/specs/SpecStore.ts","../src/headless/HeadlessCameraBinding.ts","../src/headless/HeadlessRenderer.ts","../src/lib/geometry/connectors/anchors/center.ts","../src/lib/geometry/connectors/anchors/boundary.ts","../src/lib/geometry/connectors/anchors/perpendicular.ts","../src/lib/geometry/connectors/anchors/edgePort.ts","../src/lib/geometry/connectors/anchors/silhouettePort.ts","../src/lib/geometry/connectors/routers/straight.ts","../src/lib/geometry/connectors/routers/orth.ts","../src/lib/geometry/connectors/routers/_obstacleGrid.ts","../src/lib/geometry/connectors/routers/_aStar.ts","../src/lib/geometry/connectors/routers/manhattan.ts","../src/lib/geometry/connectors/routers/metro.ts","../src/lib/geometry/connectors/routers/er.ts","../src/lib/geometry/connectors/routers/oneSide.ts","../src/lib/geometry/connectors/pathStyles/normal.ts","../src/lib/geometry/connectors/pathStyles/rounded.ts","../src/lib/geometry/connectors/pathStyles/bezier.ts","../src/lib/geometry/connectors/pathStyles/quadratic.ts","../src/lib/geometry/connectors/pathStyles/bumpRadial.ts","../src/lib/geometry/connectors/pathStyles/bumpHorizontal.ts","../src/lib/geometry/connectors/pathStyles/bumpVertical.ts","../src/lib/geometry/connectors/pathStyles/spline.ts","../src/lib/geometry/connectors/pathStyles/smooth.ts","../src/lib/geometry/connectors/pathStyles/stepRadial.ts","../src/lib/geometry/connectors/pathStyles/bundle.ts","../src/lib/geometry/connectors/pathStyles/loopPolyline.ts","../src/lib/geometry/connectors/pathStyles/loopCurve.ts","../src/lib/geometry/connectors/pathSampling.ts","../src/lib/geometry/badges/placement.ts","../src/lib/geometry/badges/connectorPlacement.ts","../src/lib/geometry/labels/labelScale.ts","../src/lib/animation/animatePositions.ts","../src/lib/svg/markup.ts","../src/lib/svg/pathToSvgD.ts","../src/lib/svg/paint.ts","../src/lib/svg/shapeSpecToSvg.ts","../src/lib/svg/connectorToSvg.ts","../src/state/view/CanvasView.ts","../src/state/view/createActions.ts","../src/state/view/mergeItems.ts","../src/state/events/CanvasEvent.ts","../src/state/events/CanvasEventBus.ts","../src/state/theme/CanvasThemeState.ts","../src/state/theme/types.ts","../src/state/data/ColumnStore.ts","../src/state/data/LayerData.ts"],"names":["reversed","n","len","TAU","resolveAutoSide","DEFAULT_INFLATE","DEFAULT_STUB_LENGTH","DEFAULT_TENSION","DEFAULT_SIDE","sx","sy","DEFAULT_BASE_OFFSET","DEFAULT_RADIUS","sideToAngle","a","b","raf"],"mappings":";AA8CO,IAAM,gBAAN,MAAqE;AAAA,EAI1E,WAAA,CACmB,KAAA,EACA,MAAA,EACA,OAAA,GAAgC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AAK,KAAA,EAAO,EAAE,CAAA;AAAA,IACtD;AACA,IAAA,KAAA,MAAW,KAAK,IAAA,EAAM,IAAA,CAAK,MAAA,CAAO,GAAA,EAAK,OAAO,CAAC,CAAA;AAAA,EACjD;AACF","file":"index.js","sourcesContent":["/**\n * `SpecProjector` — drives a renderer from a {@link SpecStore}.\n *\n * The store holds the visual description; this turns it into mounted elements.\n * Every drawing layer uses the same projector, which is what makes \"the renderer\n * is a projection of state\" true for the whole engine rather than for one layer.\n *\n * Two entry points, and the difference matters:\n *\n * - {@link project} — synchronous, for a layer publishing its own spec. Anything\n * the layer does *after* publishing (attaching a label, a decoration, a badge)\n * needs the element mounted already, so this path cannot wait for a flush.\n * - the **flush subscription** — for every other writer: a behaviour, a tool, a\n * restored session. Ids already projected synchronously in the same frame are\n * skipped so nothing is drawn twice.\n *\n * Shapes and connectors are told apart by **which registry owns the spec's\n * `kind`**, so no discriminator has to be baked into the spec vocabulary.\n *\n * See `docs/renderer-split-design.md` §2 and §4.2b.\n */\n\nimport type { SpecFlush, SpecStore } from '../specs';\nimport type { BaseConnectorSpec, BaseShapeSpec } from '../specs';\n\n/** The slice of a renderer this projector drives. */\nexport interface SpecProjectionTarget {\n readonly shapeKinds: ReadonlySet<string>;\n getShapeKind(id: string): string | undefined;\n hasConnector(id: string): boolean;\n addShape<TSpec extends BaseShapeSpec>(id: string, spec: TSpec): void;\n updateShape<TSpec extends BaseShapeSpec>(id: string, patch: Partial<TSpec>): void;\n removeShape(id: string): void;\n addConnector<TSpec extends BaseConnectorSpec>(id: string, spec: TSpec): void;\n updateConnector<TSpec extends BaseConnectorSpec>(id: string, patch: Partial<TSpec>): void;\n removeConnector(id: string): void;\n}\n\nexport interface SpecProjectorOptions {\n /**\n * Called before an element is removed and re-added because its `kind` changed.\n * A host may be tracking decoration / badge slots that the removal disposes.\n */\n onKindChange?: (id: string) => void;\n}\n\nexport class SpecProjector<TSpec extends BaseShapeSpec | BaseConnectorSpec> {\n private readonly projectedThisFlush = new Set<string>();\n private readonly off: () => void;\n\n constructor(\n private readonly specs: SpecStore<TSpec>,\n private readonly target: SpecProjectionTarget,\n private readonly options: SpecProjectorOptions = {},\n ) {\n this.off = specs.onFlush((delta) => this.applyFlush(delta));\n }\n\n /**\n * Mount / update `id` from the store **now**, and mark it handled so the next\n * flush skips it.\n */\n project(id: string): void {\n this.projectedThisFlush.add(id);\n this.apply(id);\n }\n\n /** Remove whatever the renderer holds for `id`, whichever kind it is. */\n unproject(id: string): void {\n const t = this.target;\n if (t.getShapeKind(id) !== undefined) t.removeShape(id);\n else if (t.hasConnector(id)) t.removeConnector(id);\n }\n\n /** Drop the flush subscription. */\n destroy(): void {\n this.off();\n this.projectedThisFlush.clear();\n }\n\n private applyFlush(delta: SpecFlush): void {\n for (const id of delta.added) if (!this.projectedThisFlush.has(id)) this.apply(id);\n for (const id of delta.changed) if (!this.projectedThisFlush.has(id)) this.apply(id);\n for (const id of delta.removed) this.unproject(id);\n this.projectedThisFlush.clear();\n }\n\n private apply(id: string): void {\n const spec = this.specs.get(id);\n if (!spec) return;\n const t = this.target;\n\n if (t.shapeKinds.has(spec.kind)) {\n const shapeSpec = spec as BaseShapeSpec;\n const currentKind = t.getShapeKind(id);\n if (currentKind === undefined) {\n t.addShape(id, shapeSpec);\n } else if (currentKind === shapeSpec.kind) {\n // Instance-preserving: keeps gfx scale, decorations, badges, effects.\n t.updateShape<BaseShapeSpec>(id, shapeSpec);\n } else {\n // `IShape` is fixed at construction, so a kind change means remount.\n t.removeShape(id);\n this.options.onKindChange?.(id);\n t.addShape(id, shapeSpec);\n }\n return;\n }\n\n const connectorSpec = spec as BaseConnectorSpec;\n if (t.hasConnector(id)) t.updateConnector(id, connectorSpec);\n else t.addConnector(id, connectorSpec);\n }\n}\n","/** A typed listener for one event payload. */\nexport type Listener<P> = (payload: P) => void;\n\n/**\n * A string-keyed event map (`{ eventType: payload }`) — the conventional generic\n * bound for scoped {@link EventEmitter}s (layer / behaviour / domain-store event\n * channels). `EventEmitter`/`SourceEmitter` accept any `object`; this is the\n * portable shape most maps use.\n */\nexport type EventMap = Record<string, unknown>;\n\n/**\n * A small typed event emitter over an event map `M` (`{ eventType: payload }`).\n * Renderer-free; the base for {@link SourceEmitter} and the building block under\n * {@link CanvasEventBus}.\n */\nexport class EventEmitter<M extends object> {\n private readonly map = new Map<keyof M, Set<Listener<unknown>>>();\n\n /** Subscribe; returns an unsubscribe. */\n on<K extends keyof M>(type: K, listener: Listener<M[K]>): () => void {\n let set = this.map.get(type);\n if (!set) {\n set = new Set();\n this.map.set(type, set);\n }\n set.add(listener as Listener<unknown>);\n return () => this.off(type, listener);\n }\n\n /** Subscribe for a single emission. */\n once<K extends keyof M>(type: K, listener: Listener<M[K]>): () => void {\n const off = this.on(type, (payload) => {\n off();\n listener(payload);\n });\n return off;\n }\n\n /** Unsubscribe a listener. */\n off<K extends keyof M>(type: K, listener: Listener<M[K]>): void {\n this.map.get(type)?.delete(listener as Listener<unknown>);\n }\n\n /** Emit to all listeners of `type` (snapshot, so handlers may unsubscribe). */\n emit<K extends keyof M>(type: K, payload: M[K]): void {\n const set = this.map.get(type);\n if (!set) return;\n for (const l of [...set]) (l as Listener<M[K]>)(payload);\n }\n\n removeAllListeners(): void {\n this.map.clear();\n }\n\n listenerCount<K extends keyof M>(type: K): number {\n return this.map.get(type)?.size ?? 0;\n }\n}\n","import type { CanvasEventBus } from './CanvasEventBus';\nimport type { EventSource } from './CanvasEvent';\nimport { EventEmitter } from './EventEmitter';\n\n/**\n * A scoped {@link EventEmitter} stamped with an {@link EventSource}. When connected\n * to a bus via {@link setBus}, every emit is **also** forwarded to the bus tap as a\n * structured envelope — so a store/layer/behaviour's own events reach the\n * canvas-wide tap (telemetry / collaboration) without each one re-plumbing.\n *\n * Local `on(...)` subscribers still get the raw typed payload as usual.\n */\nexport class SourceEmitter<M extends object> extends EventEmitter<M> {\n private bus: CanvasEventBus | null = null;\n\n constructor(public readonly source: EventSource) {\n super();\n }\n\n /** Connect (or disconnect with `null`/`undefined`) this emitter's stream to a bus tap. */\n setBus(bus: CanvasEventBus | null | undefined): void {\n this.bus = bus ?? null;\n }\n\n override emit<K extends keyof M>(type: K, payload: M[K]): void {\n super.emit(type, payload);\n this.bus?.publish(type as string, payload, this.source);\n }\n}\n","/**\n * `DirtyBatcher<TBucket>` — accumulates \"this id changed\" signals between frames,\n * deduplicates them, and hands a per-frame snapshot to a flush callback.\n *\n * Relocated into `@invana/canvas-store` (decision D1) alongside {@link ColumnStore}\n * — the renderer-free machinery behind the kernel's coalesced data flush. Pure;\n * **no rendering, no pixi, no `requestAnimationFrame` of its own** — the owner\n * (the engine's single rAF loop) calls {@link flush} once per tick.\n *\n * **Performance contract:** `mark` O(1) (Map.get + Set.add, no steady-state\n * alloc); `markAll` O(1) (a flag); `flush` O(1) (Map swap, no copy). Per-frame\n * consumer work is proportional to *changed* ids, never total scene size. Sets are\n * reused across frames (double-buffered) — zero GC pressure in steady state.\n *\n * **Double buffering:** `flush()` returns a snapshot of the previous frame's marks\n * and swaps in the empty buffer, so any `mark()` during the consumer's handler\n * lands in the *next* frame — never corrupts the iteration in flight.\n */\n\n/**\n * The snapshot handed to the flush handler. `buckets` is keyed by bucket name →\n * the Set of dirty ids this frame (untouched buckets are absent). `rebuildAll` is\n * the set of buckets flagged via {@link DirtyBatcher.markAll} — for those, iterate\n * the underlying data, not the per-id Set.\n */\nexport interface DirtySnapshot<TBucket extends string = string> {\n readonly buckets: ReadonlyMap<TBucket, ReadonlySet<string>>;\n readonly rebuildAll: ReadonlySet<TBucket>;\n}\n\n/** One side of the double buffer. Internal. */\ninterface BatcherFrame<TBucket extends string> {\n buckets: Map<TBucket, Set<string>>;\n rebuildAll: Set<TBucket>;\n}\n\nexport class DirtyBatcher<TBucket extends string = string> {\n private active: BatcherFrame<TBucket> = makeFrame<TBucket>();\n private buffer: BatcherFrame<TBucket> = makeFrame<TBucket>();\n private _dirty = false;\n\n /** Mark a single id dirty in a bucket. O(1); bucket Sets are created lazily + reused. */\n mark(bucket: TBucket, id: string): void {\n let set = this.active.buckets.get(bucket);\n if (!set) {\n set = new Set<string>();\n this.active.buckets.set(bucket, set);\n }\n set.add(id);\n this._dirty = true;\n }\n\n /** Flag a whole bucket for rebuild (theme change, LOD swap, wholesale replace). */\n markAll(bucket: TBucket): void {\n this.active.rebuildAll.add(bucket);\n this._dirty = true;\n }\n\n /** Cheap check the tick uses to decide whether to call {@link flush}. */\n hasPending(): boolean {\n return this._dirty;\n }\n\n /**\n * Swap buffers and return the previous frame's snapshot. The returned Sets are\n * still owned by the batcher — **do not retain references past the flush call**;\n * the next `flush()` reuses and clears them.\n */\n flush(): DirtySnapshot<TBucket> {\n const outgoing = this.active;\n this.active = this.buffer;\n this.buffer = outgoing;\n this._dirty = false;\n // Pre-clear the new active frame; `outgoing` is cleared on the FOLLOWING flush.\n for (const set of this.active.buckets.values()) set.clear();\n this.active.rebuildAll.clear();\n return outgoing as unknown as DirtySnapshot<TBucket>;\n }\n\n /** Drop both buffers. Call on unmount; usable again afterwards. */\n reset(): void {\n for (const set of this.active.buckets.values()) set.clear();\n for (const set of this.buffer.buckets.values()) set.clear();\n this.active.rebuildAll.clear();\n this.buffer.rebuildAll.clear();\n this._dirty = false;\n }\n\n /** Number of dirty ids in a bucket (0 if never touched). Debug. */\n bucketSize(bucket: TBucket): number {\n return this.active.buckets.get(bucket)?.size ?? 0;\n }\n\n /** True iff the bucket is flagged for rebuild this frame. Debug. */\n isRebuildAll(bucket: TBucket): boolean {\n return this.active.rebuildAll.has(bucket);\n }\n}\n\nfunction makeFrame<TBucket extends string>(): BatcherFrame<TBucket> {\n return {\n buckets: new Map<TBucket, Set<string>>(),\n rebuildAll: new Set<TBucket>(),\n };\n}\n","/**\n * `Layer` — base class for everything composable onto `canvas.layers`.\n *\n * Architecture: see `architecture-proposal.md` §2.1.\n *\n * **What every Layer owns:**\n * - `id` — stable identifier; used by registries, events, telemetry envelopes.\n * - `options` — construction-time, mostly-immutable config.\n * - `state` — UI / interaction state (`ReactiveStore<T>` from the kernel; small,\n * observable, and — because it goes through the port — patch-emitting, so\n * history, telemetry and a future CRDT backend all see it.\n * - `events` — typed `SourceEmitter` that auto-forwards to the canvas tap.\n * - `dirty` — `DirtyBatcher` for per-frame batched flush.\n * - `visible` / `hittable` / `zIndex` / `cullable` — composition flags.\n *\n * **Lifecycle:** `mount(ctx)` → … → `unmount()`. `Canvas` calls these via the\n * `LayerRegistry`. `flush()` is called once per Canvas tick when\n * `dirty.hasPending()` is true.\n *\n * **Bulk hot data (`data`)** is NOT on the base class — it lives on subclasses\n * that need it (e.g. `GraphLayer` ships `GraphNodeStore`). See\n * `architecture-proposal.md` §2.1 for the bifurcated state/data model.\n *\n * **What subclasses provide:**\n * - `createState()` — initial UI state.\n * - `applyDirty(snap)` — translate dirty buckets → renderer commands.\n * - `onMount()` / `onUnmount()` — domain-specific setup/teardown\n * (subscribe to feeds, register decorations, etc.).\n * - `WorldLayer` / `ScreenLayer` add `hitTest(coord, coord)`.\n */\n\nimport type { CanvasContext } from './CanvasContext';\nimport type { EventMap } from '../state/events/EventEmitter';\nimport type { ReactiveStore } from '../state/port/types';\nimport { SourceEmitter } from '../state/events/SourceEmitter';\nimport { DirtyBatcher, type DirtySnapshot } from '../state/data/DirtyBatcher';\n\n// ─── Minimal interface that registries see ─────────────────────────────────\n\n/**\n * The subset of `Layer` the `LayerRegistry` and `Canvas.tick` interact with.\n * Lets the registry stay decoupled from the abstract class implementation.\n */\nexport interface ILayer {\n readonly id: string;\n visible: boolean;\n hittable: boolean;\n zIndex: number;\n cullable: boolean;\n /** `true` between `mount(ctx)` and `unmount()`. Lets the registry skip already-mounted layers. */\n readonly mounted: boolean;\n mount(ctx: CanvasContext): void;\n unmount(): void;\n flush(): void;\n hasPending(): boolean;\n redraw(): void;\n setVisible(visible: boolean): void;\n}\n\n// ─── Constructor options ───────────────────────────────────────────────────\n\nexport interface LayerOptions<TOptions = unknown> {\n id: string;\n options: TOptions;\n visible?: boolean;\n hittable?: boolean;\n zIndex?: number;\n /**\n * Off-screen culling participation. Default `true`. Set `false` for\n * full-canvas effect layers (background gradient, overlay) that should\n * always render regardless of camera visibility.\n */\n cullable?: boolean;\n}\n\n// ─── Layer base class ──────────────────────────────────────────────────────\n\nexport abstract class Layer<\n TOptions = unknown,\n TState extends object = object,\n TEvents extends EventMap = EventMap,\n TDirtyBucket extends string = string,\n> implements ILayer\n{\n readonly id: string;\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'background-layer'`,\n * `'minimap-layer'`). Distinct from {@link id} (the per-instance key): all\n * `BackgroundLayer` instances share `kind: 'background-layer'`. Concrete layers\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n readonly options: TOptions;\n readonly events: SourceEmitter<TEvents>;\n readonly dirty: DirtyBatcher<TDirtyBucket>;\n\n /**\n * Backing field for {@link state}. Created on **first mount** via\n * `ctx.createStateStore` (the engine injects the reactive-store factory — this\n * package is dependency-free and cannot construct one), then kept for the\n * layer's lifetime: a remount reuses the same store, preserving state.\n */\n private _state?: ReactiveStore<TState>;\n\n /**\n * UI / interaction state (`ReactiveStore<TState>`). Because it is built\n * through the injected kernel factory, every write emits patches and history /\n * telemetry / a future CRDT backend all observe it.\n *\n * **Available from `mount()` onward** — accessing it before the first mount\n * throws. (`createState()` is also called at first mount, so it may safely\n * read subclass fields initialised in the subclass constructor.)\n */\n get state(): ReactiveStore<TState> {\n if (!this._state) {\n throw new Error(\n `Layer \"${this.id}\": state is unavailable before the first mount() — ` +\n 'it is created via ctx.createStateStore when the layer mounts.',\n );\n }\n return this._state;\n }\n\n /** Backing field for the `visible` accessor. */\n private _visible: boolean = true;\n hittable: boolean;\n zIndex: number;\n cullable: boolean;\n\n /**\n * Whether this layer renders. Setting `false` hides the layer's pixi\n * container (via `onVisibleChange`, overridden by `WorldLayer` /\n * `ScreenLayer`) and the Canvas tick skips its flush.\n */\n get visible(): boolean {\n return this._visible;\n }\n set visible(value: boolean) {\n if (this._visible === value) return;\n this._visible = value;\n this.onVisibleChange(value);\n }\n\n /**\n * Toggle whole-layer visibility, repaint, and announce it. Unlike assigning\n * `visible` (which only hides the pixi container via {@link onVisibleChange}),\n * this also forces a {@link redraw} and emits `scene:layer:visibilitychange`\n * on the canvas bus so dependent layers (minimap) and the render loop react\n * automatically. No-op if the value is unchanged.\n */\n setVisible(visible: boolean): void {\n if (this._visible === visible) return;\n this.visible = visible; // runs onVisibleChange (container.visible sync)\n // Repaint from current state so a re-shown renderer-backed layer restores\n // its content without waiting for the next mutation.\n if (visible) this.redraw();\n this.ctx?.events.emit('scene:layer:visibilitychange', { id: this.id, visible });\n }\n\n /** Set by `mount(ctx)`; cleared by `unmount()`. */\n protected ctx?: CanvasContext;\n\n /** True between `mount` and `unmount`. */\n get mounted(): boolean {\n return this.ctx !== undefined;\n }\n\n constructor(opts: LayerOptions<TOptions>) {\n this.id = opts.id;\n this.options = opts.options;\n this._visible = opts.visible ?? true;\n this.hittable = opts.hittable ?? true;\n this.zIndex = opts.zIndex ?? 0;\n this.cullable = opts.cullable ?? true;\n\n // State is NOT created here — this package cannot construct a reactive\n // store (the factory is immer/zustand-backed and lives in the kernel).\n // `mount(ctx)` builds it via `ctx.createStateStore` on first mount.\n\n // Events emitter without bus initially; `mount()` attaches it to ctx.events.\n this.events = new SourceEmitter<TEvents>({ kind: 'layer', id: this.id });\n\n this.dirty = new DirtyBatcher<TDirtyBucket>();\n }\n\n // ─── Lifecycle ───────────────────────────────────────────────────────────\n\n mount(ctx: CanvasContext): void {\n if (this.ctx !== undefined) {\n throw new Error(`Layer \"${this.id}\" already mounted`);\n }\n this.ctx = ctx;\n // First mount builds the state store through the engine-injected factory\n // (so layer state rides the same patch-emitting port as every other store);\n // later remounts reuse it, preserving state across unmount/mount cycles.\n this._state ??= ctx.createStateStore<TState>(this.createState());\n this.events.setBus(ctx.events);\n this.onMount(ctx);\n }\n\n unmount(): void {\n if (this.ctx === undefined) return;\n const ctx = this.ctx;\n this.onUnmount(ctx);\n this.events.setBus(null);\n this.dirty.reset();\n this.ctx = undefined;\n }\n\n /** Convenience accessor; throws when called pre-mount. */\n protected get context(): CanvasContext {\n if (!this.ctx) {\n throw new Error(`Layer \"${this.id}\" is not mounted`);\n }\n return this.ctx;\n }\n\n // ─── Per-tick flush ──────────────────────────────────────────────────────\n\n /** Whether `flush()` has work to do this frame. */\n hasPending(): boolean {\n return this.dirty.hasPending();\n }\n\n /**\n * Called by Canvas tick when `hasPending()` is true. Swaps the dirty\n * snapshot, hands it to `applyDirty`. Subclasses normally don't override.\n */\n flush(): void {\n if (!this.dirty.hasPending()) return;\n const snap = this.dirty.flush();\n this.applyDirty(snap);\n }\n\n /**\n * Force a full repaint of this layer from its current state, bypassing the\n * per-frame dirty path. Base implementation is a no-op — only layers that\n * mount a renderer override it (e.g. `GraphLayer.redraw` re-renders every\n * node and edge). Driven by {@link Canvas.redraw}; reach for it after an\n * external change that sidestepped the normal mutate-and-flush path (theme\n * swap, palette change) or to recover from a suspected render desync.\n */\n redraw(): void {\n /* default no-op — renderer-backed layers override this */\n }\n\n // ─── Subclass hooks ──────────────────────────────────────────────────────\n\n /** Build the initial UI / interaction state. Called once in the constructor. */\n protected abstract createState(): TState;\n\n /**\n * Translate a dirty snapshot into renderer / pixi commands.\n * Default: no-op. Override when the layer batches work via `dirty.mark(...)`.\n */\n protected applyDirty(_snap: DirtySnapshot<TDirtyBucket>): void {\n /* default no-op */\n }\n\n /** Domain-specific mount setup (subscribe to peers, attach renderer, etc.). */\n protected onMount(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /** Domain-specific unmount teardown. */\n protected onUnmount(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /**\n * Called whenever `visible` changes (setter only — not on initial\n * construction). Subclasses override to keep their pixi container's\n * `.visible` in sync. Default: no-op.\n */\n protected onVisibleChange(_value: boolean): void {\n /* default no-op */\n }\n}\n","/**\n * `Behaviour` — input subscriber that translates user input into state mutations.\n *\n * Architecture: see `architecture-proposal.md` §2.2.\n *\n * Behaviours own neither rendering output nor source-of-truth data. They\n * subscribe to layer events (`'node:hover'`, `'shape:click'`) or canvas events\n * (`'pointerdown'`) and mutate the appropriate `state` slice.\n *\n * **Default `enabled: false`.** Registration wires the behaviour up; the\n * developer explicitly enables it. Matches the rule that no input behaviour\n * is auto-active (`architecture-proposal.md` §2.2 + repo CLAUDE.md rule 7).\n *\n * **`shortcuts`** is advisory metadata — used by `BehaviourRegistry` to log\n * conflict warnings when two enabled behaviours claim the same gesture\n * (e.g. lasso vs. pan both wanting `'shift+drag'`). The framework warns;\n * it does not enforce — that's the developer's job.\n *\n * **`modes`** ties a behaviour to the canvas's interaction mode\n * (`view.interaction.viewMode` — the modeller \"tool\"). An enabled behaviour with\n * `modes: ['add']` is only *live* while the mode is `'add'`: outside it the base\n * runs {@link Behaviour.onDisable} (cancelling any gesture) and back inside it\n * runs {@link Behaviour.onEnable}. `enabled` stays the developer's flag — a mode\n * switch never changes it, never fires `scene:behaviour:enable`, and never shows\n * up in {@link Behaviour.getOptions}.\n */\n\nimport type { CanvasContext } from './CanvasContext';\nimport type { GestureClaimOptions } from './GestureArbiter';\n\n/** What `BehaviourRegistry` sees. */\nexport interface IBehaviour {\n readonly id: string;\n readonly enabled: boolean;\n /** `true` once `register(ctx)` has run. Lets the registry skip already-wired behaviours. */\n readonly isRegistered: boolean;\n readonly scope: 'layer' | 'canvas';\n readonly targetLayerId?: string;\n readonly shortcuts?: readonly string[];\n register(ctx: CanvasContext): void;\n destroy(): void;\n enable(): void;\n disable(): void;\n /**\n * Merge a serialisable options patch and apply it live. Every behaviour\n * supports this (the base provides a generic implementation) so the engine's\n * `canvas.update({ behaviours })` path can retune any behaviour uniformly.\n */\n setOptions(changes: Record<string, unknown>): void;\n /**\n * Replace the interaction modes this behaviour is live in (`undefined` = all).\n * The engine calls it directly for a `modes` patch, like it routes `enabled`\n * through the registry, because some behaviours override `setOptions`\n * without calling `super`.\n */\n setModes?(modes: readonly string[] | undefined): void;\n}\n\nexport interface BehaviourOptions {\n id: string;\n /**\n * Layer-scoped behaviours target a specific Layer by id. Canvas-scoped\n * behaviours have no `targetLayerId` and `scope: 'canvas'`.\n */\n targetLayerId?: string;\n /** Default `false` — the developer explicitly enables. */\n enabled?: boolean;\n /**\n * Gesture identifiers this behaviour claims. Used by `BehaviourRegistry`\n * for conflict warnings. Format is convention-free (`'shift+drag'`,\n * `'wheel+ctrl'`, `'rclick'`); registries match strings as-is.\n */\n shortcuts?: readonly string[];\n /**\n * Interaction modes (`view.interaction.viewMode` values) this behaviour is live\n * in. Omitted = every mode. An enabled behaviour outside its modes is\n * suspended — its `onDisable` runs, `enabled` is unchanged — and resumes when\n * the mode comes back. E.g. `modes: ['connect']` on an edge-drawing behaviour\n * makes the modeller's Connect tool switch it on and off with no host wiring.\n * A `'!'` entry excludes a mode: `modes: ['!hand']` is live in every mode but\n * `'hand'`. Positive and `'!'` entries combine — listed modes, minus the\n * excluded ones.\n */\n modes?: readonly string[];\n}\n\nexport abstract class Behaviour<TOptions extends BehaviourOptions = BehaviourOptions>\n implements IBehaviour\n{\n readonly id: string;\n readonly targetLayerId?: string;\n readonly shortcuts?: readonly string[];\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'drag-pan'`,\n * `'wheel-zoom'`). Distinct from {@link id} (the per-instance key): all\n * `DragPanBehaviour` instances share `kind: 'drag-pan'`. Concrete behaviours\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n\n /**\n * `'layer'` if `targetLayerId` is set, otherwise `'canvas'`. Set automatically\n * from the constructor — subclasses don't need to re-declare.\n */\n readonly scope: 'layer' | 'canvas';\n\n /**\n * Whether the behaviour is **live**: the developer's flag ({@link enabled})\n * *and* the current interaction mode being one of {@link BehaviourOptions.modes}.\n * Subclasses gate their handlers on this (or {@link isEnabled}); only the base\n * writes it.\n */\n protected _enabled: boolean;\n protected ctx?: CanvasContext;\n\n /** The developer's enable flag — what {@link enabled} reports and snapshots capture. */\n private _wanted: boolean;\n /** `false` while the canvas's mode is outside {@link BehaviourOptions.modes}. */\n private _inMode = true;\n /** Releases the `viewMode` subscription, or `null` when not watching. */\n private _modeUnsub: (() => void) | null = null;\n\n /**\n * The construction options, merged in-place by {@link setOptions}. Named\n * `_options` (not `options`) so subclasses that expose a bespoke\n * `get options()` snapshot don't collide with it. Subclasses read their live\n * config from here (or from fields re-synced in {@link onOptionsChanged}).\n */\n protected _options: TOptions;\n\n /**\n * Release function for this behaviour's live gesture claim, or `null` when it\n * holds none. Held privately (not `protected`) so the only way to end a claim\n * is {@link releaseGesture} — which nulls the field *before* invoking it, so a\n * double release can't happen even under re-entrancy.\n */\n private _gestureRelease: (() => void) | null = null;\n\n constructor(opts: TOptions) {\n this.id = opts.id;\n this.targetLayerId = opts.targetLayerId;\n this.scope = opts.targetLayerId !== undefined ? 'layer' : 'canvas';\n this.shortcuts = opts.shortcuts;\n this._wanted = opts.enabled ?? false;\n this._enabled = this._wanted;\n this._options = opts;\n }\n\n /** The developer's enable flag. A behaviour suspended by its `modes` still reports `true`. */\n get enabled(): boolean {\n return this._wanted;\n }\n\n get isRegistered(): boolean {\n return this.ctx !== undefined;\n }\n\n /** Called by `BehaviourRegistry.register(behaviour)`. Subscribes to inputs. */\n register(ctx: CanvasContext): void {\n if (this.ctx !== undefined) {\n throw new Error(`Behaviour \"${this.id}\" already registered`);\n }\n this.ctx = ctx;\n this.onRegister(ctx);\n this.watchMode();\n this._enabled = this._wanted && this._inMode;\n if (this._enabled) this.onEnable();\n }\n\n /** Called by `BehaviourRegistry.unregister(id)`. Drops subscriptions. */\n destroy(): void {\n if (this.ctx === undefined) return;\n const ctx = this.ctx;\n this._enabled = false;\n this._wanted = false;\n this.unwatchMode();\n this.onDestroy(ctx);\n // Safety net (see `GestureArbiter`): a claim stranded by an unmount would\n // freeze the camera and every other gesture for the life of the canvas.\n this.releaseGesture();\n this.ctx = undefined;\n }\n\n enable(): void {\n if (this._wanted) return;\n this._wanted = true;\n this.syncLive();\n }\n\n disable(): void {\n if (!this._wanted) return;\n this._wanted = false;\n this.syncLive();\n }\n\n /**\n * Bring {@link _enabled} in line with `_wanted && _inMode`, running the\n * matching hook on a change. The single place a behaviour goes live or idle.\n */\n private syncLive(): void {\n const live = this._wanted && this._inMode;\n if (live === this._enabled) return;\n this._enabled = live;\n if (live) {\n this.onEnable();\n } else {\n this.onDisable();\n // Same safety net as `destroy()` — disabling mid-gesture must not strand\n // the claim, even if the subclass forgot to end its drag.\n this.releaseGesture();\n }\n }\n\n /** Is `mode` one this behaviour is live in? */\n private matchesMode(mode: string): boolean {\n const modes = this._options.modes;\n if (modes === undefined) return true;\n if (modes.includes(`!${mode}`)) return false;\n return !modes.some((m) => !m.startsWith('!')) || modes.includes(mode);\n }\n\n /**\n * Follow `view.interaction.viewMode` while registered and `modes` is set;\n * otherwise stop following and count as in-mode. Idempotent — `setOptions`\n * calls it again when `modes` changes.\n */\n private watchMode(): void {\n const ctx = this.ctx;\n if (ctx === undefined || this._options.modes === undefined) {\n this.unwatchMode();\n this._inMode = true;\n return;\n }\n const view = ctx.store.view;\n this._inMode = this.matchesMode(view.getState().interaction.viewMode);\n if (this._modeUnsub !== null) return;\n this._modeUnsub = view.subscribe((state, prev) => {\n if (state.interaction.viewMode === prev.interaction.viewMode) return;\n this._inMode = this.matchesMode(state.interaction.viewMode);\n this.syncLive();\n });\n }\n\n private unwatchMode(): void {\n this._modeUnsub?.();\n this._modeUnsub = null;\n }\n\n /**\n * Merge a serialisable options patch and apply it live. Reflects an `enabled`\n * change by enabling/disabling, then calls {@link onOptionsChanged} so the\n * subclass can apply the rest (re-sync cached fields, re-arm a viewport\n * plugin, recompute). This is the seam the engine's\n * `canvas.update({ behaviours: { [id]: patch } })` path invokes — so a settings\n * editor can retune any behaviour without remounting it.\n *\n * Subclasses with bespoke apply logic (e.g. clearing selection state on a\n * mode change) override this and should call `super.setOptions(changes)` first\n * to keep `_options` — and thus {@link getOptions} — coherent.\n */\n setOptions(changes: Partial<TOptions>): void {\n this._options = { ...this._options, ...changes };\n if ('modes' in changes) this.setModes(changes.modes);\n if (changes.enabled !== undefined) this.applyEnabled(changes.enabled);\n this.onOptionsChanged(changes);\n }\n\n /**\n * Apply an `enabled` option. While this instance is the one mounted under its\n * id, the toggle goes through the registry so `scene:behaviour:enable` /\n * `disable` and the gesture-conflict warning fire — calling {@link enable}\n * directly would leave the registry's own `setEnabled` (the engine's\n * `canvas.update` path) a silent no-op. Unmounted, or superseded by a newer\n * instance under the same id, it toggles itself directly.\n */\n private applyEnabled(enabled: boolean): void {\n const registry = this.ctx?.behaviours;\n if (registry && registry.get(this.id) === this) {\n registry.setEnabled(this.id, enabled);\n } else if (enabled) {\n this.enable();\n } else {\n this.disable();\n }\n }\n\n /**\n * Replace {@link BehaviourOptions.modes} and re-evaluate liveness against the\n * current interaction mode. `undefined` = live in every mode.\n */\n setModes(modes: readonly string[] | undefined): void {\n this._options = { ...this._options, modes };\n this.watchMode();\n this.syncLive();\n }\n\n /**\n * Merge `changes` into the options {@link getOptions} returns — and nothing\n * else: no enable / disable, no mode re-wiring, no {@link onOptionsChanged}.\n *\n * For subclasses that override {@link setOptions} with their own apply logic\n * and don't call `super`: call this first so `getOptions()` (a settings\n * editor's seed, the engine's undo baseline) stays current. Prefer it to\n * `super.setOptions` there: the engine routes `enabled` / `modes` through\n * the registry itself, and the base's direct `enable()` would pre-empt the\n * registry's `scene:behaviour:enable` event.\n */\n protected recordOptions(changes: Partial<TOptions>): void {\n this._options = { ...this._options, ...changes };\n }\n\n /** Snapshot of the current (merged) options — seeds a settings editor. */\n getOptions(): Readonly<TOptions> {\n return this._options;\n }\n\n /**\n * Contribute this behaviour's serialisable config to a canvas-state snapshot\n * (the engine's `DefinitionSerializable` contract). The base implementation\n * captures the explicit `enabled` flag (rule 7). Subclasses with additional\n * JSON-serialisable options should override and spread `super.serializeDefinition()`.\n */\n serializeDefinition(): Record<string, unknown> | undefined {\n const modes = this._options.modes;\n return modes === undefined ? { enabled: this._wanted } : { enabled: this._wanted, modes: [...modes] };\n }\n\n // ─── Subclass hooks ──────────────────────────────────────────────────────\n\n /** Subscribe to events / setup any handler resources. */\n protected abstract onRegister(ctx: CanvasContext): void;\n\n /** Cleanup on destroy. Default no-op. */\n protected onDestroy(_ctx: CanvasContext): void {\n /* default no-op */\n }\n\n /** Hook fired when the developer enables the behaviour. */\n protected onEnable(): void {\n /* default no-op */\n }\n\n /** Hook fired on disable. */\n protected onDisable(): void {\n /* default no-op */\n }\n\n /**\n * Hook fired after {@link setOptions} merges a patch (and after any `enabled`\n * toggle is applied). Default no-op. Override to apply an option change live:\n * a behaviour whose effect is wired in {@link onEnable} (a pixi-viewport\n * plugin, a DOM listener) re-arms here; one that caches option values in\n * fields re-syncs them from `this._options` here. `changes` is the raw patch;\n * `this._options` already holds the merged result.\n */\n protected onOptionsChanged(_changes: Partial<TOptions>): void {\n /* default no-op */\n }\n\n /**\n * Convenience `if (!enabled) return;` for use inside event handlers\n * (without rebinding `this` cost). `false` while suspended by `modes`.\n */\n protected get isEnabled(): boolean {\n return this._enabled;\n }\n\n // ─── Gesture arbitration ─────────────────────────────────────────────────\n\n /**\n * Take exclusive ownership of the pointer gesture for the duration of a drag\n * (`ctx.gestures`, see `input/GestureArbiter.ts`). Returns `false` when\n * another behaviour already owns it — the caller must then **not** start its\n * gesture, because two behaviours steering the same pointer is exactly what\n * the arbiter exists to prevent.\n *\n * Claiming also suspends camera panning: `DragPanBehaviour` watches the\n * arbiter and yields while anybody else owns the gesture. That replaces the\n * old `camera.viewport.plugins.pause('drag')` reach-through, which put a\n * `pixi-viewport` internal in the hands of domain behaviours.\n *\n * Pair every successful claim with {@link releaseGesture} on **every** exit\n * path — pointerup, pointercancel, abort. `disable()` and `destroy()` release\n * automatically as a backstop.\n */\n protected claimGesture(opts?: GestureClaimOptions): boolean {\n const gestures = this.ctx?.gestures;\n if (!gestures) return false;\n const release = gestures.claim(this.id, opts);\n if (release === null) return false;\n this._gestureRelease = release;\n return true;\n }\n\n /**\n * End this behaviour's gesture claim. Safe to call any number of times and\n * when no claim is held — the arbiter identifies claims by token, so a stale\n * release can never evict a later owner.\n */\n protected releaseGesture(): void {\n const release = this._gestureRelease;\n this._gestureRelease = null;\n release?.();\n }\n\n /** Does this behaviour currently hold the gesture? */\n protected get hasGestureClaim(): boolean {\n return this._gestureRelease !== null;\n }\n\n /**\n * Re-run {@link onDisable} then {@link onEnable} when the behaviour is live, so\n * an option change wired at enable-time (a pixi-viewport plugin, a listener\n * bound with the old config) picks up `this._options`. No-op when disabled or\n * unregistered (the next {@link onEnable} will read the fresh options anyway).\n * The idiomatic body of an {@link onOptionsChanged} override for such\n * behaviours.\n */\n protected reArm(): void {\n if (this._enabled && this.ctx !== undefined) {\n this.onDisable();\n this.onEnable();\n }\n }\n}\n","/**\n * `Layout` — function from data to positions.\n *\n * Architecture: see `architecture-proposal.md` §2.3.\n *\n * Per the proposal:\n * - A Layout does NOT register with the canvas.\n * - It does NOT render.\n * - It does NOT subscribe to input.\n * - You instantiate it and call it against a layer.\n *\n * const layout = new D3ForceLayout({ charge: -300 });\n * layout.events.on('end', () => canvas.camera.fitContent(...));\n * await layout.apply(graphLayer);\n *\n * Continuous-running cases (e.g. always-relax force simulation) are handled\n * by a thin wrapper Behaviour that calls `apply()` on a tick — keeps the\n * Layout API clean while supporting the rare continuous case.\n *\n * Whether two layouts conflict is a domain concern (don't apply two layouts\n * to the same data) — not enforced here.\n *\n * ## Lifecycle events\n *\n * Every layout owns a typed `events` emitter and fires three lifecycle\n * events around `apply()`:\n *\n * - `start` — emitted once, synchronously, after the layout has set up\n * its internal state and just before it begins producing positions.\n * - `tick` — emitted whenever the layout writes a fresh batch of positions.\n * One-shot layouts (e.g. ELK) fire it once. Iterative layouts (force\n * sims) fire it on every iteration. High-frequency; subscribe sparingly.\n * - `end` — emitted once when the run terminates. `reason` distinguishes\n * a natural settle from an external `stop()` call.\n *\n * Subscribe to these events to drive camera fits, progress UI, etc. —\n * instead of listening to per-tick `data:changed` on the layer, which\n * conflates \"structure changed\" with \"positions updated\".\n */\n\nimport { EventEmitter } from '../state/events/EventEmitter';\nimport type { Layer } from './Layer';\n\n/**\n * Why the run ended.\n *\n * - `completed` — the layout settled / finished on its own.\n * - `stopped` — `stop()` (or a second `apply()`) cancelled it.\n */\nexport type LayoutEndReason = 'completed' | 'stopped';\n\n/**\n * Lifecycle events fired by every `Layout`.\n *\n * Subclass-specific telemetry (e.g. d3-force's `alpha`) belongs on a\n * subclass-specific event map, not here.\n */\nexport type LayoutEvents = {\n /**\n * Run is about to produce positions. Optional run-size / animation metadata\n * lets a `Canvas.runLayout` bridge forward it onto the canvas bus as\n * `layout:run:start` without reaching into layer internals. Every field is\n * optional — a layout that doesn't know (or care) emits `{}`, and the bridge\n * substitutes `0` / `false`.\n *\n * - `nodeCount` / `edgeCount` — size of the run, for progress UIs / telemetry.\n * - `animate` — whether the run animates its settle (iterative force sims)\n * vs. jumps straight to final positions; render policies branch on it.\n */\n start: { nodeCount?: number; edgeCount?: number; animate?: boolean };\n tick: Record<string, never>;\n /**\n * A position **transition** advanced one frame — a one-shot layout gliding\n * nodes from where they were to where the run put them. `progress` is the\n * **eased** fraction of the glide, `0..1`, and reaches exactly `1` on the\n * last frame (before `end`). A run that snaps emits none.\n *\n * Separate from `tick` on purpose: `tick` means \"the layout placed nodes\",\n * and fitters react to it as such; this is per-frame motion, which a\n * {@link LayoutRunOptions.fitCamera} run follows with the camera.\n */\n transition: { progress: number };\n /**\n * An off-screen solve advanced: `done` of `total` iterations are finished.\n * Emitted by iterative layouts that settle before drawing (d3-force with\n * `animate: false`), so a UI can say why the canvas is still empty.\n *\n * Separate from `tick` on purpose: `tick` means \"positions were written\",\n * and the graph layer reveals nodes on it — progress writes nothing.\n */\n progress: { done: number; total: number };\n end: { reason: LayoutEndReason };\n};\n\n/**\n * How one layout run should behave — passed per call to {@link Layout.apply}\n * (and `Canvas.runLayout`), as opposed to {@link LayoutOptions}, which are the\n * layout's standing configuration.\n *\n * Both fields describe a **re-flow** the user did not ask for directly — e.g.\n * `CollapseExpandBehaviour` re-running the active layout after a group frame\n * opens or closes — where the point is to keep the picture steady.\n */\nexport interface LayoutRunOptions {\n /**\n * Keep this node where it is on screen. The run computes positions as usual,\n * then shifts the whole result so this node's box centre stays where it was;\n * everything else re-flows around it. Honoured by layouts that support it\n * (the one-shot layouts and `D3ForceLayout`); ignored by the rest.\n */\n anchorNodeId?: string;\n /**\n * Leave the camera alone for this run. Fitters that normally re-frame the\n * view when a layout ends (the `fitOnLoad` auto-fitter, the React layout\n * wrappers' `fitPadding`) skip a run carrying this flag.\n */\n preserveCamera?: boolean;\n /**\n * Frame the result, moving the camera **together with** the nodes. While\n * the run's position transition plays, `Canvas.runLayout` blends the camera\n * from where it started toward a fit of the content as it is on that frame\n * (by the transition's eased progress), so the picture stays framed the\n * whole way and ends exactly fitted — no glide under a stale camera\n * followed by a snap. A run that snaps (or a layout that reports no\n * `transition`) gets one fit when it ends. A user pan / zoom mid-run takes\n * the camera and stops the follow.\n *\n * `true` fits with the default padding (80 screen px); `{ padding }` sets\n * it, and `{ maxZoom }` stops the fit zooming in past that scale (`1` keeps\n * a small graph at its drawn size). Fitters that would otherwise frame on `end` (the `fitOnLoad`\n * auto-fitter, the React layout wrappers' `fitPadding`) skip such a run —\n * it already owns the camera. Ignored when {@link preserveCamera} is set.\n */\n fitCamera?: boolean | { padding?: number; maxZoom?: number };\n /**\n * Solve from scratch: ignore the nodes' stored positions as starting points\n * (pinned nodes still hold). For an iterative layout that settles from where\n * the nodes are, a settled graph otherwise falls straight back into the same\n * arrangement, and a graph laid out by another layout keeps that layout's\n * crossings. Honoured by `D3ForceLayout`; a one-shot layout computes from\n * scratch anyway.\n */\n reseed?: boolean;\n}\n\n/** How {@link Layout.setOptions} applies a patch. */\nexport interface LayoutSetOptions {\n /**\n * Re-run a layout that has already run, so the change shows. Default `true`.\n * `false` when the same write is about to run the layout anyway — a canvas\n * passes it for the layout an `activeLayout` write names — so a switch is one\n * run, carrying that run's options.\n */\n rerun?: boolean;\n}\n\n/**\n * How an **active** layout re-runs when its target layer's data changes\n * (nodes added / removed / hidden / shown). Read by the facade that wires the\n * active layout (`GraphCanvas`) each time it re-runs, so assigning\n * {@link Layout.onData} takes effect on the next change.\n */\nexport interface LayoutDataRunOptions {\n /**\n * At most one data-triggered run per this many ms: the first change runs at\n * once, later ones inside the window collapse into one run at its end — so\n * a feed writing every tick doesn't restart the layout every tick. Default\n * `0` (every change runs).\n */\n throttleMs?: number;\n /**\n * Leave the camera alone on data-triggered runs\n * ({@link LayoutRunOptions.preserveCamera}) — the view doesn't re-frame each\n * time the data changes. Default `false`.\n */\n preserveCamera?: boolean;\n}\n\n/** Construction options every layout shares (for the `LayoutRegistry`). */\nexport interface LayoutOptions {\n /** Stable id, used to address the layout in a `LayoutRegistry` / config. Default `'layout'`. */\n id?: string;\n /** The layer this layout is meant to run against. Informational — `apply(layer)` still takes one explicitly. */\n targetLayerId?: string;\n /** How data-triggered re-runs behave while this layout is active. See {@link LayoutDataRunOptions}. */\n onData?: LayoutDataRunOptions;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport abstract class Layout<TLayer extends Layer<any, any, any, any> = Layer<any, any, any, any>> {\n /** Stable id (registry / config key). */\n readonly id: string;\n /** The layer this layout targets, if declared at construction. */\n readonly targetLayerId?: string;\n\n /**\n * Stable **class kind** — a minification-safe discriminator matching the\n * `@invana/canvas-ui` settings-editor registry key (e.g. `'d3-force-layout'`,\n * `'elk-layout'`). Distinct from {@link id} (the per-instance key): all\n * `D3ForceLayout` instances share `kind: 'd3-force-layout'`. Concrete layouts\n * set it as a class field; left `undefined` on any that haven't, so consumers\n * fall back (e.g. to the class name). Lets domain-free tooling resolve an\n * instance's editor without an `instanceof` ladder.\n */\n readonly kind?: string;\n\n /**\n * Lifecycle event bus. See class docs for the event vocabulary.\n * Subclasses with richer telemetry can declare their own typed\n * emitter on top (`override readonly events = new EventEmitter<MyEvents>()`).\n */\n readonly events: EventEmitter<LayoutEvents> = new EventEmitter<LayoutEvents>();\n\n /**\n * Options of the run in flight, or of the last one once it has ended.\n * Implementations record them at the top of {@link apply}, so an `end`\n * listener can tell what kind of run just finished — e.g. a fitter skipping\n * a {@link LayoutRunOptions.preserveCamera} run.\n */\n runOptions: Readonly<LayoutRunOptions> = {};\n\n /**\n * How data-triggered re-runs behave while this layout is active (throttle,\n * keep the camera). Mutable: the wiring reads it on every data change.\n */\n onData: LayoutDataRunOptions;\n\n constructor(opts: LayoutOptions = {}) {\n this.id = opts.id ?? 'layout';\n this.targetLayerId = opts.targetLayerId;\n this.onData = { ...(opts.onData ?? {}) };\n }\n\n /**\n * Live-reconfigure. Called by `Canvas.update({ layouts: { id: patch } })`.\n * Default no-op; layouts override to merge the patch and, unless\n * `opts.rerun` is `false`, re-run so the change shows.\n */\n setOptions(_patch: unknown, _opts?: LayoutSetOptions): void {\n /* default no-op */\n }\n\n /**\n * Contribute this layout's serialisable config to a canvas-state snapshot (the\n * engine's `DefinitionSerializable` contract). The base captures the wiring\n * `targetLayerId`; iterative layouts holding tunable params (e.g. force\n * strengths) should override and spread `super.serializeDefinition()` with a\n * JSON-safe copy of those params.\n */\n serializeDefinition(): Record<string, unknown> | undefined {\n const out: Record<string, unknown> = {};\n if (this.targetLayerId !== undefined) out.targetLayerId = this.targetLayerId;\n if (Object.keys(this.onData).length > 0) out.onData = { ...this.onData };\n return Object.keys(out).length > 0 ? out : undefined;\n }\n\n /**\n * Run the layout against `layer`. Resolves when the run terminates\n * (either a natural settle or an external `stop()`).\n *\n * Calling `apply()` again on the same instance must cancel any in-flight\n * run first, and must record `run` on {@link runOptions} before emitting\n * `start`.\n *\n * @param run How this particular run should behave; see {@link LayoutRunOptions}.\n */\n abstract apply(layer: TLayer, run?: LayoutRunOptions): Promise<void>;\n}\n","/**\n * `GestureArbiter` — who owns the pointer right now.\n *\n * Architecture: see `docs/renderer-split-design.md` §9 (P5).\n *\n * **Why this exists.** Before P5, a behaviour that needed the camera to stop\n * panning during its own gesture reached for `camera.viewport.plugins.pause('drag')`\n * — sixteen calls across six behaviours, every one of them poking at a\n * `pixi-viewport` internal from domain code. The thing they actually wanted was\n * never a camera API: it was *exclusivity*. A node drag, a lasso, a brush, a\n * resize and an edge draw are all mutually exclusive pointer gestures, and the\n * camera pan is simply the lowest-priority one of them.\n *\n * So the arbiter models the real invariant — **at most one owner at a time** —\n * and the camera becomes a subscriber like anything else: `DragPanBehaviour`\n * yields while {@link GestureArbiter.owner} names somebody else. That inverts\n * the old direction (others suspending the camera) into the camera suspending\n * itself, which is what lets the pixi-viewport handle move into the renderer\n * package in P6 without dragging six domain behaviours along with it.\n *\n * **Leak safety is the whole design.** A claim that is never released freezes\n * every gesture *and* the camera, which is worse than the failure it replaces.\n * Three properties defend against that:\n *\n * 1. **Release is token-identified.** The function returned by\n * {@link GestureArbiter.claim} only clears *that* claim. Calling it twice is a\n * no-op, and calling a stale one can never evict a later owner.\n * 2. **A re-claim by the current owner always succeeds.** A behaviour that\n * leaks its own claim can never deadlock *itself* out of its next gesture —\n * the old token is simply invalidated.\n * 3. **`Behaviour` releases on `disable()` and `destroy()`** regardless of what\n * the subclass did (see `Behaviour.claimGesture`), so unmount and mid-gesture\n * teardown can't strand a claim.\n */\n\n/** Options for a single {@link GestureArbiter.claim}. */\nexport interface GestureClaimOptions {\n /**\n * Higher wins. A claim is refused when another owner holds the gesture at an\n * equal or higher priority; a strictly higher priority **pre-empts** the\n * current owner (whose {@link GestureClaimOptions.onRevoke} fires and whose\n * release function goes inert). Default `0` — every built-in behaviour claims\n * at the default, so no pre-emption happens unless a consumer asks for it.\n */\n priority?: number;\n\n /**\n * Called when this claim is pre-empted by a higher-priority owner. The seam\n * a long-running gesture uses to abort cleanly instead of continuing to move\n * things while somebody else drives the pointer. Not called on a normal\n * release, nor when the same owner re-claims.\n */\n onRevoke?: () => void;\n}\n\n/**\n * Arbitrates exclusive ownership of the pointer gesture. Reached as\n * `ctx.gestures`; provided per-`Canvas`.\n */\nexport interface GestureArbiter {\n /**\n * Try to take the gesture for `owner` (by convention the behaviour's `id`).\n * Returns a **release** function on success, or `null` when another owner\n * already holds it at an equal-or-higher priority — in which case the caller\n * should not start its gesture.\n *\n * Release is idempotent and identity-checked: calling it after the claim has\n * already ended (or been pre-empted) does nothing, so it can never clear\n * somebody else's claim.\n */\n claim(owner: string, opts?: GestureClaimOptions): (() => void) | null;\n\n /** The current owner id, or `null` when the gesture is free. */\n readonly owner: string | null;\n\n /**\n * Subscribe to ownership changes — the hook `DragPanBehaviour` uses to\n * suspend and restore camera panning. Fires with the new owner (`null` when\n * released). Returns an unsubscribe function.\n */\n onOwnerChange(listener: (owner: string | null) => void): () => void;\n}\n\n/** The live claim, plus the token that authorises releasing it. */\ninterface ActiveClaim {\n readonly owner: string;\n readonly priority: number;\n /** Identity of this specific claim — what makes release non-transferable. */\n readonly token: symbol;\n readonly onRevoke?: () => void;\n}\n\n/**\n * The default in-memory {@link GestureArbiter}. Renderer-free and DOM-free: it\n * knows nothing about pointers, only about who asked first.\n */\nexport class DefaultGestureArbiter implements GestureArbiter {\n private active: ActiveClaim | null = null;\n private readonly listeners = new Set<(owner: string | null) => void>();\n\n get owner(): string | null {\n return this.active?.owner ?? null;\n }\n\n claim(owner: string, opts?: GestureClaimOptions): (() => void) | null {\n const priority = opts?.priority ?? 0;\n const current = this.active;\n const sameOwner = current?.owner === owner;\n\n // Refuse only a *different* owner that isn't out-prioritised. Letting the\n // current owner re-claim keeps a behaviour that leaked its own release from\n // locking itself out forever (property 2 in the file docblock).\n if (current && !sameOwner && priority <= current.priority) return null;\n\n const token = Symbol(owner);\n this.active = { owner, priority, token, onRevoke: opts?.onRevoke };\n\n // Notify the loser *after* `active` is swapped, so an `onRevoke` that calls\n // its own (now stale) release sees the mismatch and no-ops.\n if (current && !sameOwner) current.onRevoke?.();\n if (!sameOwner) this.emit();\n\n return () => this.release(token);\n }\n\n onOwnerChange(listener: (owner: string | null) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /**\n * Drop the claim identified by `token`. A stale token — from a released or\n * pre-empted claim — is ignored, which is what makes double-release safe.\n */\n private release(token: symbol): void {\n if (this.active?.token !== token) return;\n this.active = null;\n this.emit();\n }\n\n /** Snapshot before iterating: a listener may unsubscribe from inside itself. */\n private emit(): void {\n const owner = this.owner;\n for (const listener of [...this.listeners]) listener(owner);\n }\n}\n","import type { ReactiveStore } from './types';\n\n/** Reference-equality default; selector slices are compared with this. */\nexport function defaultEqual<U>(a: U, b: U): boolean {\n return Object.is(a, b);\n}\n\n/** Shallow-equal for objects/arrays — a common selector equality for derived slices. */\nexport function shallowEqual<U>(a: U, b: U): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) return false;\n const ak = Object.keys(a as Record<string, unknown>);\n const bk = Object.keys(b as Record<string, unknown>);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.is((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k])) return false;\n }\n return true;\n}\n\n/** A subscribable view of one selected slice — what `useSyncExternalStore` binds to. */\nexport interface Selected<U> {\n get(): U;\n subscribe(onChange: () => void): () => void;\n}\n\n/**\n * Project a {@link ReactiveStore} to one slice, re-notifying **only** when that\n * slice changes (by `isEqual`). Selector + equality semantics live here — in our\n * code, not the backend — so they survive a backend swap. The React `useStore`\n * hook (in `@invana/canvas-react`) binds this to `useSyncExternalStore`.\n */\nexport function select<T, U>(\n store: ReactiveStore<T>,\n selector: (state: T) => U,\n isEqual: (a: U, b: U) => boolean = defaultEqual,\n): Selected<U> {\n return {\n get: () => selector(store.getState()),\n subscribe: (onChange) => {\n let current = selector(store.getState());\n return store.subscribe((state) => {\n const next = selector(state);\n if (!isEqual(current, next)) {\n current = next;\n onChange();\n }\n });\n },\n };\n}\n","/**\n * Easing functions consumed by `Tween`. Each is a pure `(t: number) => number`\n * where `t ∈ [0, 1]` is normalised progress and the return value is the eased\n * progress (also typically in `[0, 1]`, though overshoot easings may exceed).\n *\n * Naming follows the standard easing taxonomy (Penner et al). Add new entries\n * here rather than inline-defining easings in effect / decoration code so the\n * set stays consistent across animated primitives.\n */\n\nexport type Easing = (t: number) => number;\n\nexport const linear: Easing = (t) => t;\n\nexport const easeInOutSine: Easing = (t) => -(Math.cos(Math.PI * t) - 1) / 2;\n\nexport const easeOutCubic: Easing = (t) => 1 - Math.pow(1 - t, 3);\n\nexport const easeInOutCubic: Easing = (t) =>\n t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n\nexport const easeOutQuad: Easing = (t) => 1 - (1 - t) * (1 - t);\n\n/**\n * Stable string keys for the built-in easings.\n *\n * Serializable easing handle — use this (not an `Easing` function) anywhere an\n * easing must live in JSON config or bind to a `<select>` / lil-gui dropdown\n * (e.g. a layout's `transitionEase`). Resolve to the function with\n * {@link resolveEasing}.\n */\nexport type EasingName = 'linear' | 'easeInOutSine' | 'easeOutCubic' | 'easeInOutCubic' | 'easeOutQuad';\n\n/** Registry backing {@link resolveEasing}. Keep in sync with {@link EasingName}. */\nconst EASINGS: Record<EasingName, Easing> = {\n linear,\n easeInOutSine,\n easeOutCubic,\n easeInOutCubic,\n easeOutQuad,\n};\n\n/** All built-in easing names — handy for populating a picker. */\nexport const EASING_NAMES = Object.keys(EASINGS) as EasingName[];\n\n/**\n * Resolve an {@link EasingName} (or `undefined`) to its `Easing` function,\n * falling back to `fallback` (default {@link easeOutCubic}) for an unknown or\n * missing name. Lets config carry a serializable easing key while runtime code\n * gets the function.\n */\nexport function resolveEasing(name: EasingName | undefined, fallback: Easing = easeOutCubic): Easing {\n return (name && EASINGS[name]) || fallback;\n}\n","import { linear, type Easing } from './easings';\n\n/**\n * Options for constructing a `Tween`. `from` / `to` / `duration` are required;\n * everything else is optional and falls back to a sensible default.\n *\n * - `easing` defaults to `linear`.\n * - `repeat` is either an integer count (number of additional cycles after the\n * first) or `'forever'`. Defaults to `0` (play once).\n * - `yoyo` reverses direction on each repeat. Only meaningful when `repeat`\n * is non-zero. Defaults to `false`.\n * - `onUpdate(value)` fires every `tick` with the current eased value.\n * - `onComplete()` fires once when the tween retires (final cycle ends).\n * Never fires for `repeat: 'forever'`.\n */\nexport interface TweenOptions {\n readonly from: number;\n readonly to: number;\n readonly duration: number;\n readonly easing?: Easing;\n readonly repeat?: number | 'forever';\n readonly yoyo?: boolean;\n readonly onUpdate?: (value: number) => void;\n readonly onComplete?: () => void;\n}\n\n/**\n * Time-based interpolation primitive. Authors call `tick(deltaMs)` once per\n * frame; the tween advances internal time, applies easing, fires `onUpdate`,\n * and returns `false` when finished so the caller can retire it.\n *\n * The tween itself does no scheduling — it's a pure state machine. Effects\n * and decorations hold a `Tween` and drive it from their own `tick(dt)`.\n *\n * Reusable: call `reset()` to play again from `from`.\n */\nexport class Tween {\n private readonly opts: TweenOptions;\n private readonly easing: Easing;\n private readonly maxRepeat: number;\n private elapsed = 0;\n private cycle = 0;\n private _value: number;\n private _done = false;\n\n constructor(opts: TweenOptions) {\n this.opts = opts;\n this.easing = opts.easing ?? linear;\n this.maxRepeat =\n opts.repeat === 'forever'\n ? Number.POSITIVE_INFINITY\n : (opts.repeat ?? 0);\n this._value = opts.from;\n }\n\n get value(): number {\n return this._value;\n }\n\n get done(): boolean {\n return this._done;\n }\n\n /**\n * Advance by `dt` milliseconds. Returns `false` when the tween has finished\n * its final cycle; callers should remove finished tweens from their tick\n * set. Returns `true` while still running (including indefinitely for\n * `repeat: 'forever'`).\n */\n tick(dt: number): boolean {\n if (this._done) return false;\n\n this.elapsed += dt;\n const { duration, from, to, onUpdate, onComplete } = this.opts;\n const yoyo = this.opts.yoyo ?? false;\n\n // Walk cycles in case `dt` is larger than one cycle (e.g. tab regained focus).\n while (this.elapsed >= duration && this.cycle < this.maxRepeat) {\n this.elapsed -= duration;\n this.cycle += 1;\n }\n\n if (this.cycle >= this.maxRepeat && this.elapsed >= duration) {\n // Final cycle complete — snap to end value and retire.\n const reversed = yoyo && this.maxRepeat % 2 === 1;\n this._value = reversed ? from : to;\n this._done = true;\n onUpdate?.(this._value);\n onComplete?.();\n return false;\n }\n\n const t = this.elapsed / duration;\n const eased = this.easing(t);\n const reversed = yoyo && this.cycle % 2 === 1;\n this._value = reversed ? to + (from - to) * eased : from + (to - from) * eased;\n onUpdate?.(this._value);\n return true;\n }\n\n /** Restart from `from`. Clears `done`. */\n reset(): void {\n this.elapsed = 0;\n this.cycle = 0;\n this._done = false;\n this._value = this.opts.from;\n }\n}\n","/**\n * `Camera` — the engine's pan/zoom/projection facade.\n *\n * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.camera) and\n * §2.6 (camera input is a Behaviour, not a hard-coded gesture).\n *\n * **Design notes**\n *\n * - **No backend type crosses this class.** The concrete viewport lives behind\n * {@link ICameraBinding} — `PixiViewportBinding` today, an orthographic\n * three.js camera later. Camera owns the *semantics* (clamping, anchored zoom,\n * fit-to-rect, bus events, store sync); the binding owns the realisation\n * (`docs/renderer-split-design.md` §9, P5/P6).\n * - The Camera owns no input gestures — those live in opt-in camera-input\n * `Behaviour`s (proposal §2.6). They configure inputs through\n * {@link Camera.configureInput} / {@link Camera.setDragSuspended} /\n * {@link Camera.onDragStart}, described semantically (`percent`, `modifier`),\n * so a behaviour never names a plugin.\n * - The **binding is the single source of truth** for the transform: Camera\n * reads it back rather than caching, so a gesture driven inside the backend\n * and a programmatic `pan()` can't drift apart.\n * - Coordinate model (uniform scale, no rotation):\n *\n * screen.x = world.x * scale + tx\n * screen.y = world.y * scale + ty\n * world.x = (screen.x - tx) / scale\n * world.y = (screen.y - ty) / scale\n *\n * We deliberately keep `scale.x === scale.y` (no anisotropic zoom) and no\n * rotation. Both are enforceable as needed.\n *\n * - Events are emitted on the canvas-wide `CanvasEventBus`:\n * `camera:zoom`, `camera:pan`. They flow through the tap channel so\n * telemetry sees every camera change.\n */\n\nimport { select } from '../state/port/select';\nimport type { CanvasEventBus } from '../state/events/CanvasEventBus';\nimport type { CanvasStore } from '../state/CanvasStore';\nimport { Tween } from '../lib/animation/Tween';\nimport { resolveEasing, type EasingName } from '../lib/animation/easings';\nimport type { Point, Rect } from '../specs/geom';\nimport type {\n CameraInputConfig,\n CameraTransformValue,\n ICameraBinding,\n} from '../contracts/ICameraBinding';\n\nexport type { Point, Rect };\nexport type {\n CameraInputConfig,\n CameraInputModifier,\n DragInputOptions,\n PinchInputOptions,\n WheelInputOptions,\n} from '../contracts/ICameraBinding';\n\n/** An absolute camera transform — world (0,0) at `(x, y)` screen px, uniform `zoom`. */\nexport type CameraTransform = CameraTransformValue;\n\nexport interface CameraOptions {\n /**\n * The renderer's viewport, behind the pixi-free {@link ICameraBinding} seam.\n * Created by the renderer (`Canvas` wires `PixiViewportBinding` today).\n */\n binding: ICameraBinding;\n /** Initial viewport size in CSS pixels. Mirrors the binding's own screen size for projection math. */\n screenWidth: number;\n screenHeight: number;\n /** Optional bus for `input:camera:zoom` / `input:camera:pan` events. */\n bus?: CanvasEventBus;\n /**\n * Optional kernel store. When present, the camera keeps\n * `store.view.interaction.camera` (the abstract `{x,y,zoom}` transform) in sync\n * with the binding **both ways** — gestures/mutators push into the store,\n * and external `actions.camera.*` writes apply to the binding.\n */\n store?: CanvasStore;\n /** Initial uniform scale. Default 1. */\n initialScale?: number;\n /** Initial world-container offset (= where world (0,0) lives in screen pixels). Default (0,0). */\n initialX?: number;\n initialY?: number;\n /** Min / max zoom clamp. Defaults: 0.01 .. 100. */\n minScale?: number;\n maxScale?: number;\n}\n\nexport class Camera {\n /**\n * The renderer's viewport, behind the pixi-free binding seam. **Private** —\n * nothing outside this class reaches the backend, which is what lets P6 move\n * the realisation into `@invana/renderer-pixijs` without a public break.\n */\n private readonly binding: ICameraBinding;\n\n private readonly bus?: CanvasEventBus;\n\n private _screenWidth: number;\n private _screenHeight: number;\n private readonly _minScale: number;\n private readonly _maxScale: number;\n\n /** Kernel store (optional) — the home of the abstract `interaction.camera` transform. */\n private readonly store?: CanvasStore;\n /** Re-entrancy guard so binding↔store sync never ping-pongs. */\n private _syncing = false;\n /** Unsubscribe for the `interaction.camera` slice subscription. */\n private _offStoreCam?: () => void;\n /** Unsubscribe for the binding's backend-driven transform reports. */\n private _offBindingChange?: () => void;\n /** Whether drag-panning is currently yielded to another gesture owner. */\n private _dragSuspended = false;\n /**\n * In-flight {@link animateTo} tween, or `null`. Holds the endpoints and the\n * eased progress; {@link tick} advances it and writes the interpolated\n * transform through {@link binding} directly, bypassing the public mutators\n * so it cannot cancel itself.\n */\n private _fitTween: {\n readonly from: CameraTransform;\n readonly to: CameraTransform;\n readonly tween: Tween;\n readonly onDone?: () => void;\n } | null = null;\n\n constructor(opts: CameraOptions) {\n this.binding = opts.binding;\n this.bus = opts.bus;\n this.store = opts.store;\n this._screenWidth = opts.screenWidth;\n this._screenHeight = opts.screenHeight;\n this._minScale = opts.minScale ?? 0.01;\n this._maxScale = opts.maxScale ?? 100;\n\n this.binding.setTransform({\n x: opts.initialX ?? 0,\n y: opts.initialY ?? 0,\n zoom: this.clampScale(opts.initialScale ?? 1),\n });\n\n // Bridge backend-driven transform changes to the canvas bus. Without this,\n // interactive pan/zoom (drag, wheel, pinch, momentum — all driven inside the\n // backend) never reaches `camera:pan` / `camera:zoom` listeners, because\n // those mutations bypass Camera's typed mutators. Changes Camera itself\n // makes are not reported back, so there's no double-emit.\n this._offBindingChange = this.binding.onTransformChange((kind) => {\n // A user gesture owns the camera from its first frame — drop any glide.\n // Without this an `animateTo` keeps overwriting the gesture until it\n // lands, and drag-pan momentum then inherits the glide's velocity.\n this.cancelAnimation();\n const t = this.binding.getTransform();\n if (kind === 'zoom') {\n this.bus?.emit('input:camera:zoom', {\n scale: t.zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n }\n this.bus?.emit('input:camera:pan', { x: t.x, y: t.y });\n this.pushToStore();\n });\n\n // Bidirectional bind to `store.view.interaction.camera`: seed it from the\n // initial transform, then apply any external `actions.camera.*` write back\n // onto the binding (the `_syncing` guard breaks the feedback loop).\n if (this.store) {\n this.pushToStore();\n const cameraSlice = select(this.store.view, (s) => s.interaction.camera);\n this._offStoreCam = cameraSlice.subscribe(() => this.applyFromStore());\n }\n }\n\n /**\n * Push the current transform into `store.view.interaction.camera`. Called from\n * every camera mutation (gesture + programmatic). No-op when the store already\n * matches or a store→binding apply is in flight.\n */\n private pushToStore(): void {\n if (!this.store || this._syncing) return;\n const { x, y, zoom } = this.binding.getTransform();\n const cur = this.store.view.getState().interaction.camera;\n if (cur.x === x && cur.y === y && cur.zoom === zoom) return;\n this._syncing = true;\n try {\n this.store.actions.camera.set({ x, y, zoom });\n } finally {\n this._syncing = false;\n }\n }\n\n /**\n * Apply `store.view.interaction.camera` onto the binding — realises an external\n * `actions.camera.*` write. No-op when the binding already matches or a\n * binding→store push is in flight.\n */\n private applyFromStore(): void {\n if (!this.store || this._syncing) return;\n const c = this.store.view.getState().interaction.camera;\n const cur = this.binding.getTransform();\n if (cur.x === c.x && cur.y === c.y && cur.zoom === c.zoom) return;\n this._syncing = true;\n try {\n this.binding.setTransform({ x: c.x, y: c.y, zoom: this.clampScale(c.zoom) });\n } finally {\n this._syncing = false;\n }\n }\n\n // ─── Read accessors ──────────────────────────────────────────────────────\n\n /** Current uniform scale. */\n get scale(): number {\n return this.binding.getTransform().zoom;\n }\n\n /** Current world-container x in screen pixels. (Where world (0,0) sits.) */\n get x(): number {\n return this.binding.getTransform().x;\n }\n\n get y(): number {\n return this.binding.getTransform().y;\n }\n\n get screenWidth(): number {\n return this._screenWidth;\n }\n\n get screenHeight(): number {\n return this._screenHeight;\n }\n\n // ─── Mutators ────────────────────────────────────────────────────────────\n\n /**\n * Set absolute world-container offset. `(x, y)` is where world (0,0) lives\n * in screen pixels. Most consumers want `pan(dx, dy)` instead.\n */\n setPosition(x: number, y: number): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const cur = this.binding.getTransform();\n if (x === cur.x && y === cur.y) return;\n this.binding.setTransform({ x, y, zoom: cur.zoom });\n this.bus?.emit('input:camera:pan', { x, y });\n this.pushToStore();\n }\n\n /** Pan by `(dx, dy)` screen pixels. */\n pan(dx: number, dy: number): void {\n if (dx === 0 && dy === 0) return;\n this.setPosition(this.x + dx, this.y + dy);\n }\n\n /**\n * Write an absolute `{ x, y, zoom }` transform in one step — the seam for a\n * layer mirroring an **external** camera authority (a MapLibre basemap, a\n * remote collaborator's viewport, a replayed session).\n *\n * Unlike `setZoom` + `setPosition`, this re-anchors nothing: the transform\n * lands exactly as given, because the external authority has already solved\n * for it and any re-anchoring here would desync the two views. `zoom` is\n * emitted only when it actually changed — most mirrored gestures are pan-only\n * and the `input:camera:zoom` listeners are O(N) over their tracked elements.\n *\n * @param t The transform to apply.\n * @param opts.clamp Apply the camera's min/max zoom clamp. Default `true`.\n * Pass `false` when mirroring an authority with its own scale range — a web\n * mercator basemap runs to `2 ** 22`, far past the camera's default ceiling\n * of 100, and clamping would silently peg the canvas away from the map.\n */\n setTransform(t: CameraTransform, opts?: { clamp?: boolean }): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const zoom = opts?.clamp === false ? t.zoom : this.clampScale(t.zoom);\n const cur = this.binding.getTransform();\n const zoomChanged = zoom !== cur.zoom;\n if (!zoomChanged && t.x === cur.x && t.y === cur.y) return;\n\n this.binding.setTransform({ x: t.x, y: t.y, zoom });\n\n if (zoomChanged) {\n this.bus?.emit('input:camera:zoom', {\n scale: zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n }\n this.bus?.emit('input:camera:pan', { x: t.x, y: t.y });\n this.pushToStore();\n }\n\n /**\n * Set absolute scale, anchored at the viewport centre. The world point at\n * the centre stays put. For zoom-around-an-arbitrary-point semantics use\n * `zoomAt`.\n */\n setZoom(scale: number): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const next = this.clampScale(scale);\n if (next === this.scale) return;\n this.binding.zoomToCentre(next);\n this.bus?.emit('input:camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x: this.x, y: this.y });\n this.pushToStore();\n }\n\n /**\n * Multiply scale by `factor`, holding the world point under the screen\n * cursor `(centerX, centerY)` in place. Default centre = viewport centre.\n *\n * Bindings offer only centre-anchored zoom, so the arbitrary-anchor math is\n * done here: project the anchor to world, change scale, then translate so the\n * same world point lands at the same screen point.\n */\n zoomAt(\n factor: number,\n centerX: number = this._screenWidth / 2,\n centerY: number = this._screenHeight / 2,\n ): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n const before = this.toWorld(centerX, centerY);\n const nextScale = this.clampScale(this.scale * factor);\n if (nextScale === this.scale) return;\n this.binding.setTransform({\n x: centerX - before.x * nextScale,\n y: centerY - before.y * nextScale,\n zoom: nextScale,\n });\n this.bus?.emit('input:camera:zoom', { scale: nextScale, centerX, centerY });\n this.bus?.emit('input:camera:pan', { x: this.x, y: this.y });\n this.pushToStore();\n }\n\n /**\n * Fit a world-space rectangle into the viewport. Scales so the whole rect\n * is visible (limited by the smaller axis), centres it. `padding` is in\n * screen pixels around the rect.\n */\n fitContent(worldRect: Rect | null | undefined, padding = 24): void {\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n // `null` means \"nothing to measure\" — an empty graph, or a layer whose\n // renderer hasn't mounted. Fitting to a zero rect would produce a nonsense\n // camera, so the honest response is to leave the view alone. Accepting it\n // here keeps the null-check out of every call site\n // (`docs/renderer-split-design.md` D3).\n if (!worldRect) return;\n const availW = Math.max(1, this._screenWidth - padding * 2);\n const availH = Math.max(1, this._screenHeight - padding * 2);\n const scaleX = availW / Math.max(1, worldRect.width);\n const scaleY = availH / Math.max(1, worldRect.height);\n const next = this.clampScale(Math.min(scaleX, scaleY));\n\n const cx = worldRect.x + worldRect.width / 2;\n const cy = worldRect.y + worldRect.height / 2;\n const tx = this._screenWidth / 2 - cx * next;\n const ty = this._screenHeight / 2 - cy * next;\n\n this.binding.setTransform({ x: tx, y: ty, zoom: next });\n\n this.bus?.emit('input:camera:zoom', {\n scale: next,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x: tx, y: ty });\n this.pushToStore();\n }\n\n /**\n * Centre the viewport on a world-space point — pan so `(worldX, worldY)`\n * maps to the screen centre, keeping the current zoom. The pan-only\n * counterpart to {@link fitContent}: use it for \"focus\" / \"go to\" actions\n * that should locate a target without rescaling the view.\n *\n * By default the pan is applied at once. Pass a positive `durationMs` to\n * glide there instead — the move then runs through {@link animateTo}, so it\n * follows the same rules: eased, and cancelled by any other camera write.\n *\n * @param durationMs Length of the glide. Absent or `<= 0` pans immediately.\n * @param easing Named curve for the glide; defaults to `'easeOutCubic'`.\n * @param onDone Called once the camera is on target (immediately when\n * not gliding; never when a glide is cancelled).\n */\n centerOn(\n worldX: number,\n worldY: number,\n { durationMs = 0, easing, onDone }:\n { durationMs?: number; easing?: EasingName; onDone?: () => void } = {},\n ): void {\n const scale = this.scale;\n const tx = this._screenWidth / 2 - worldX * scale;\n const ty = this._screenHeight / 2 - worldY * scale;\n if (durationMs > 0) {\n this.animateTo(\n { x: tx, y: ty, zoom: scale },\n { durationMs, ...(easing ? { easing } : {}), ...(onDone ? { onDone } : {}) },\n );\n return;\n }\n // Whoever writes the transform last owns the camera — drop any glide.\n this.cancelAnimation();\n this.binding.setTransform({ x: tx, y: ty, zoom: scale });\n this.bus?.emit('input:camera:pan', { x: tx, y: ty });\n this.pushToStore();\n onDone?.();\n }\n\n /** Update on viewport resize. Forwarded so the binding's own math stays correct. */\n resize(screenWidth: number, screenHeight: number): void {\n this._screenWidth = screenWidth;\n this._screenHeight = screenHeight;\n this.binding.resize(screenWidth, screenHeight);\n }\n\n // ─── Projection ──────────────────────────────────────────────────────────\n\n /** Screen → world. */\n toWorld(screenX: number, screenY: number): Point {\n return this.binding.toWorld(screenX, screenY);\n }\n\n /** World → screen. */\n toScreen(worldX: number, worldY: number): Point {\n return this.binding.toScreen(worldX, worldY);\n }\n\n /**\n * The world-space rectangle currently visible. Used by viewport culling\n * (per `decorations-plan.md` §11.6) and minimap layers.\n */\n getVisibleBounds(): Rect {\n return this.binding.getVisibleBounds();\n }\n\n // ─── Input configuration ─────────────────────────────────────────────────\n\n /**\n * Configure the camera's own pan / zoom inputs. This is the seam camera-input\n * behaviours use instead of naming a backend plugin: the options are described\n * semantically (`percent`, `modifier`) and the realisation lives in the\n * binding, so `DragPanBehaviour` / `WheelZoomBehaviour` / `PinchZoomBehaviour`\n * survive the renderer swap unchanged.\n *\n * Patch semantics — an omitted key is left alone, `null` removes that input:\n *\n * ```ts\n * camera.configureInput({ wheel: { percent: 0.2, modifier: 'control' } });\n * camera.configureInput({ wheel: null }); // wheel zoom off, pinch untouched\n * ```\n *\n * Re-configuring an already-installed input replaces it, because the\n * underlying inputs read their config only at install time.\n */\n configureInput(config: CameraInputConfig): void {\n if (config.drag !== undefined) this._dragSuspended = false;\n this.binding.configureInput(config);\n }\n\n /**\n * Suspend / restore drag-panning without tearing the input down. This is how\n * gesture arbitration yields the camera: while another behaviour owns the\n * pointer (a node drag, a lasso, a resize) panning is suspended, and it\n * resumes when that gesture releases.\n *\n * Momentum is deliberately left running, so an in-flight glide finishes as it\n * always has. Edge-triggered — restoring resets the underlying input, so a\n * repeated call in the same state is a no-op.\n */\n setDragSuspended(suspended: boolean): void {\n if (suspended === this._dragSuspended) return;\n this._dragSuspended = suspended;\n this.binding.setDragSuspended(suspended);\n }\n\n /**\n * Subscribe to the start of a drag-pan gesture — fired once the pointer has\n * actually moved enough to pan. `DragPanBehaviour` uses it as the cursor\n * fallback for the `space` modifier, which can't be read off a pointer event.\n *\n * @returns an unsubscribe function.\n */\n onDragStart(fn: () => void): () => void {\n return this.binding.onDragStart(fn);\n }\n\n // ─── Internal ────────────────────────────────────────────────────────────\n\n /**\n * Ease the camera to an absolute transform over `durationMs`, instead of\n * snapping to it.\n *\n * The animated counterpart of {@link setTransform}, and the mechanism behind\n * `CanvasConfig.fitAnimation`: the first auto-fit of a canvas can glide into\n * frame rather than cutting. `x`, `y` and `zoom` are interpolated together on\n * one eased curve, so the move reads as a single gesture.\n *\n * **Any other camera write cancels it.** A user who pans or zooms mid-glide\n * owns the camera from that moment — an animation that fought back would be\n * the `fitOnResize` mistake in a different costume (`D7`). The tween is also\n * dropped, not finished, so `onDone` does not fire.\n *\n * Requires {@link tick} to be called each frame, which `Canvas.tickOnce` does.\n *\n * @param to Target transform. `zoom` is clamped like any other write.\n * @param durationMs Length of the glide. `<= 0` applies `to` immediately.\n * @param easing Named curve; defaults to `'easeOutCubic'`.\n * @param onDone Called once the glide completes naturally.\n */\n animateTo(\n to: CameraTransform,\n { durationMs = 400, easing, onDone }:\n { durationMs?: number; easing?: EasingName; onDone?: () => void } = {},\n ): void {\n const target: CameraTransform = { x: to.x, y: to.y, zoom: this.clampScale(to.zoom) };\n if (durationMs <= 0) {\n this.setTransform(target);\n onDone?.();\n return;\n }\n // Cancel any glide already running before reading `from`, so a second call\n // starts from where the camera actually is rather than compounding.\n this._fitTween = null;\n const from = this.binding.getTransform();\n this._fitTween = {\n from: { x: from.x, y: from.y, zoom: from.zoom },\n to: target,\n tween: new Tween({ from: 0, to: 1, duration: durationMs, easing: resolveEasing(easing) }),\n ...(onDone ? { onDone } : {}),\n };\n }\n\n /**\n * Drop an in-flight {@link animateTo} without finishing it. Called by every\n * public transform mutator, so whoever writes last owns the camera.\n */\n cancelAnimation(): void {\n this._fitTween = null;\n }\n\n /** Whether an {@link animateTo} glide is currently running. */\n get isAnimating(): boolean {\n return this._fitTween !== null;\n }\n\n /**\n * Advance time-based input animation (momentum, snap). Called by\n * `Canvas.tickOnce()` every frame — the engine owns the only clock (G3).\n * No-op until a camera-input behaviour enables an input that animates.\n */\n tick(dt: number): void {\n this.binding.tick(dt);\n this.advanceAnimation(dt);\n }\n\n /**\n * Step an {@link animateTo} glide. Writes through {@link binding} rather than\n * the public mutators — those cancel the tween, which would end the glide on\n * its own first frame.\n */\n private advanceAnimation(dt: number): void {\n const anim = this._fitTween;\n if (!anim) return;\n const running = anim.tween.tick(dt);\n const t = anim.tween.value;\n const x = anim.from.x + (anim.to.x - anim.from.x) * t;\n const y = anim.from.y + (anim.to.y - anim.from.y) * t;\n const zoom = anim.from.zoom + (anim.to.zoom - anim.from.zoom) * t;\n this.binding.setTransform({ x, y, zoom });\n this.bus?.emit('input:camera:zoom', {\n scale: zoom,\n centerX: this._screenWidth / 2,\n centerY: this._screenHeight / 2,\n });\n this.bus?.emit('input:camera:pan', { x, y });\n this.pushToStore();\n if (running) return;\n // Land exactly on the target — an eased curve can finish a hair short.\n this._fitTween = null;\n this.setTransform(anim.to);\n anim.onDone?.();\n }\n\n /** Tear down subscriptions. Called by `Canvas.destroy`. */\n dispose(): void {\n this._offStoreCam?.();\n this._offStoreCam = undefined;\n this._offBindingChange?.();\n this._offBindingChange = undefined;\n }\n\n private clampScale(scale: number): number {\n if (scale < this._minScale) return this._minScale;\n if (scale > this._maxScale) return this._maxScale;\n return scale;\n }\n}\n","/**\n * `LayerRegistry` — stores the Layers added to a Canvas.\n *\n * Architecture: see `architecture-proposal.md` §2.4 (CanvasContext.layers).\n *\n * **Responsibilities**\n * - Add / remove (with mount / unmount lifecycle).\n * - Typed `get<T>(id)`.\n * - `byZOrder()` iteration — used by the Canvas tick.\n * - Fires `'scene:layer:add'` / `'scene:layer:remove'` on the bus.\n *\n * **Lifecycle wiring**\n *\n * The registry doesn't itself construct the `CanvasContext` — it would be\n * circular (the registry is a field of the context). Instead the Canvas\n * passes a `getContext()` thunk; `add(layer)` resolves it at the moment of\n * mount. This keeps the registry decoupled from the context's full shape.\n */\n\nimport type { CanvasContext } from '../CanvasContext';\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { ILayer } from '../Layer';\n\nexport interface LayerRegistryOptions {\n /**\n * Resolves the `CanvasContext` at the moment of mount, or `undefined` before\n * the Canvas is initialised. Layers added pre-init are stored and mounted\n * later by `mountAll()`.\n */\n getContext: () => CanvasContext | undefined;\n /** Bus for `layer:added` / `layer:removed` events. */\n bus: CanvasEventBus;\n}\n\nexport class LayerRegistry {\n private readonly layers: Map<string, ILayer> = new Map();\n private readonly getContext: () => CanvasContext | undefined;\n private readonly bus: CanvasEventBus;\n\n /** Cached z-sorted view; invalidated on add/remove/setZIndex. */\n private zOrderCache: ILayer[] | null = null;\n\n constructor(opts: LayerRegistryOptions) {\n this.getContext = opts.getContext;\n this.bus = opts.bus;\n }\n\n /** Number of registered layers. */\n get size(): number {\n return this.layers.size;\n }\n\n /**\n * Add a Layer to the canvas. Mounts immediately if the Canvas is initialised;\n * otherwise the layer waits for `mountAll()` (called by `Canvas.init`). Fires\n * `layer:added`. Throws if `id` is already registered.\n */\n add(layer: ILayer): void {\n if (this.layers.has(layer.id)) {\n throw new Error(`LayerRegistry: layer \"${layer.id}\" already registered`);\n }\n this.layers.set(layer.id, layer);\n this.zOrderCache = null;\n const ctx = this.getContext();\n if (ctx) layer.mount(ctx);\n this.bus.emit('scene:layer:add', { id: layer.id });\n }\n\n /** Mount every not-yet-mounted layer. Called by `Canvas.init` once the context exists. */\n mountAll(): void {\n const ctx = this.getContext();\n if (!ctx) return;\n for (const layer of this.layers.values()) {\n if (!layer.mounted) layer.mount(ctx);\n }\n }\n\n /**\n * Remove a Layer. Calls `layer.unmount()` and fires `layer:removed`.\n * No-op if `id` isn't registered.\n */\n remove(id: string): void {\n const layer = this.layers.get(id);\n if (!layer) return;\n this.layers.delete(id);\n this.zOrderCache = null;\n layer.unmount();\n this.bus.emit('scene:layer:remove', { id });\n }\n\n /** Typed get by id. Returns `undefined` if not found. */\n get<T extends ILayer = ILayer>(id: string): T | undefined {\n return this.layers.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.layers.has(id);\n }\n\n /** Snapshot of all layers in insertion order. */\n list(): readonly ILayer[] {\n return Array.from(this.layers.values());\n }\n\n /**\n * Iterate layers in z-order (low → high). The Canvas tick walks layers in\n * z-order to flush dirty work; rendering order is then determined by\n * pixi's child order (handled by `SurfaceManager.setWorldLayerZ`).\n *\n * The result is cached and reused until `add` / `remove` / `setZIndex` invalidates.\n */\n byZOrder(): readonly ILayer[] {\n if (this.zOrderCache !== null) return this.zOrderCache;\n const arr = Array.from(this.layers.values());\n arr.sort((a, b) => a.zIndex - b.zIndex);\n this.zOrderCache = arr;\n return arr;\n }\n\n /**\n * Update a layer's `zIndex` and propagate to surfaces. Invalidates the\n * z-order cache. No-op if the layer isn't registered.\n */\n setZIndex(id: string, zIndex: number): void {\n const layer = this.layers.get(id);\n if (!layer) return;\n layer.zIndex = zIndex;\n this.zOrderCache = null;\n // Surface z-order is handled by the layer's mount path (it knows whether\n // it's a WorldLayer or ScreenLayer). For now we just update the field;\n // visual reordering happens on the next render pass by the layer's hook.\n }\n\n /**\n * Tear down every registered layer. Called on Canvas destroy.\n * Iteration is over a snapshot so unmount-triggered side effects don't\n * corrupt the loop.\n */\n clear(): void {\n for (const id of [...this.layers.keys()]) this.remove(id);\n }\n}\n","/**\n * `BehaviourRegistry` — stores Behaviours and toggles their enabled state.\n *\n * Architecture: see `architecture-proposal.md` §2.2.\n *\n * **Responsibilities**\n * - `register` / `unregister` (with register / destroy lifecycle; fires\n * `'scene:behaviour:register'` / `'scene:behaviour:unregister'`).\n * - `setEnabled(id, enabled)` — toggles + fires `'scene:behaviour:enable'` /\n * `'scene:behaviour:disable'`.\n * - Typed `get<T>(id)`.\n * - **Gesture-conflict warning**: when two enabled behaviours claim the same\n * `shortcut`, log a `console.warn`. Doesn't enforce — the developer\n * decides whether two behaviours can coexist on the same gesture.\n */\n\nimport type { CanvasContext } from '../CanvasContext';\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { IBehaviour } from '../Behaviour';\n\nexport interface BehaviourRegistryOptions {\n getContext: () => CanvasContext | undefined;\n bus: CanvasEventBus;\n}\n\nexport class BehaviourRegistry {\n private readonly behaviours: Map<string, IBehaviour> = new Map();\n private readonly getContext: () => CanvasContext | undefined;\n private readonly bus: CanvasEventBus;\n\n constructor(opts: BehaviourRegistryOptions) {\n this.getContext = opts.getContext;\n this.bus = opts.bus;\n }\n\n get size(): number {\n return this.behaviours.size;\n }\n\n /**\n * Register a Behaviour. Wires it (`behaviour.register(ctx)` + events) now if\n * the Canvas is initialised; otherwise it's stored and wired later by\n * `registerAll()` (called by `Canvas.init`). Throws on duplicate id.\n *\n * When wiring throws (the behaviour rejects its context — a missing target\n * layer, a second instance of a one-per-layer kind), the entry is removed\n * before the error propagates, so a rejected behaviour never shows up in\n * {@link list} and its id stays free.\n */\n register(behaviour: IBehaviour): void {\n if (this.behaviours.has(behaviour.id)) {\n throw new Error(`BehaviourRegistry: behaviour \"${behaviour.id}\" already registered`);\n }\n this.behaviours.set(behaviour.id, behaviour);\n const ctx = this.getContext();\n if (!ctx) return;\n try {\n this.wire(behaviour, ctx);\n } catch (err) {\n this.behaviours.delete(behaviour.id);\n throw err;\n }\n }\n\n /** Wire every not-yet-registered behaviour. Called by `Canvas.init` (after layers mount). */\n registerAll(): void {\n const ctx = this.getContext();\n if (!ctx) return;\n for (const behaviour of [...this.behaviours.values()]) {\n if (behaviour.isRegistered) continue;\n try {\n this.wire(behaviour, ctx);\n } catch (err) {\n // Same rollback as `register`: a rejected behaviour leaves no entry.\n this.behaviours.delete(behaviour.id);\n throw err;\n }\n }\n }\n\n /** `behaviour.register(ctx)` + the registered/enabled events. */\n private wire(behaviour: IBehaviour, ctx: CanvasContext): void {\n behaviour.register(ctx);\n this.bus.emit('scene:behaviour:register', { id: behaviour.id });\n if (behaviour.enabled) {\n this.bus.emit('scene:behaviour:enable', { id: behaviour.id });\n this.warnOnShortcutConflict(behaviour);\n }\n }\n\n /**\n * Remove a behaviour. Calls `destroy()`, then fires\n * `'scene:behaviour:unregister'` (after `'scene:behaviour:disable'` when it\n * was enabled). No-op if not registered.\n */\n unregister(id: string): void {\n const b = this.behaviours.get(id);\n if (!b) return;\n if (b.enabled) {\n b.disable();\n this.bus.emit('scene:behaviour:disable', { id });\n }\n this.behaviours.delete(id);\n b.destroy();\n this.bus.emit('scene:behaviour:unregister', { id });\n }\n\n /** Enable / disable a behaviour. Fires the corresponding bus event. */\n setEnabled(id: string, enabled: boolean): void {\n const b = this.behaviours.get(id);\n if (!b) return;\n if (b.enabled === enabled) return;\n if (enabled) {\n b.enable();\n this.bus.emit('scene:behaviour:enable', { id });\n this.warnOnShortcutConflict(b);\n } else {\n b.disable();\n this.bus.emit('scene:behaviour:disable', { id });\n }\n }\n\n get<T extends IBehaviour = IBehaviour>(id: string): T | undefined {\n return this.behaviours.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.behaviours.has(id);\n }\n\n list(): readonly IBehaviour[] {\n return Array.from(this.behaviours.values());\n }\n\n /** Tear down all behaviours. Called on Canvas destroy. */\n clear(): void {\n for (const id of [...this.behaviours.keys()]) this.unregister(id);\n }\n\n // ─── Conflict detection ──────────────────────────────────────────────────\n\n private warnOnShortcutConflict(b: IBehaviour): void {\n if (!b.shortcuts || b.shortcuts.length === 0) return;\n for (const peer of this.behaviours.values()) {\n if (peer === b) continue;\n if (!peer.enabled || !peer.shortcuts) continue;\n for (const gesture of b.shortcuts) {\n if (peer.shortcuts.includes(gesture)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[canvas] Behaviour \"${b.id}\" claims gesture \"${gesture}\" already used by enabled behaviour \"${peer.id}\". Disable one before enabling the other.`,\n );\n }\n }\n }\n }\n}\n","/**\n * `LayoutRegistry` — stores the Layouts registered on a Canvas, addressed by id.\n *\n * Simpler than `LayerRegistry` / `BehaviourRegistry`: layouts aren't mounted,\n * z-ordered, or wired to input — they're held so `Canvas.update()` can push\n * config to them by id and consumers can fetch + `apply()` them. A graph runs\n * one layout at a time, but several may be registered (e.g. a layout picker).\n */\n\nimport type { CanvasEventBus } from '../../state/events/CanvasEventBus';\nimport type { Layout } from '../Layout';\n\nexport interface LayoutRegistryOptions {\n bus: CanvasEventBus;\n}\n\nexport class LayoutRegistry {\n private readonly layouts: Map<string, Layout> = new Map();\n private readonly bus: CanvasEventBus;\n\n constructor(opts: LayoutRegistryOptions) {\n this.bus = opts.bus;\n }\n\n get size(): number {\n return this.layouts.size;\n }\n\n /** Register a layout. Fires `layout:added`. Throws on duplicate id. */\n add(layout: Layout): void {\n if (this.layouts.has(layout.id)) {\n throw new Error(`LayoutRegistry: layout \"${layout.id}\" already registered`);\n }\n this.layouts.set(layout.id, layout);\n this.bus.emit('scene:layout:add', { id: layout.id });\n }\n\n /** Remove a layout, stopping it first if it exposes `stop()`. Fires `layout:removed`. */\n remove(id: string): void {\n const layout = this.layouts.get(id);\n if (!layout) return;\n (layout as { stop?: () => void }).stop?.();\n this.layouts.delete(id);\n this.bus.emit('scene:layout:remove', { id });\n }\n\n get<T extends Layout = Layout>(id: string): T | undefined {\n return this.layouts.get(id) as T | undefined;\n }\n\n has(id: string): boolean {\n return this.layouts.has(id);\n }\n\n list(): readonly Layout[] {\n return Array.from(this.layouts.values());\n }\n\n /** Stop + drop every layout. Called on Canvas destroy. */\n clear(): void {\n for (const layout of this.layouts.values()) (layout as { stop?: () => void }).stop?.();\n this.layouts.clear();\n }\n}\n","/**\n * `CommandRegistry` — named, serialisable-by-reference actions.\n *\n * Serialisable UI (toolbars today; shortcuts and menus later) can't hold\n * closures, so it names what it does — `'camera.fit'`, `'view.lock'` — and this\n * registry resolves the name to behaviour at run time. Names are\n * `namespace.verb`; the engine registers its built-ins, a domain package or an\n * app adds its own.\n *\n * Generic over the context `C` a command runs against (the engine binds it to\n * its `Canvas`), so the kernel stays free of any engine type.\n */\n\n/** One option of a pick-one command (see {@link CanvasCommand.options}). */\nexport interface CommandOption {\n /** The value passed back to `run` as `args.value` when picked. */\n value: string;\n /** Human label. */\n label: string;\n /** Icon name, resolved by the UI kit's icon registry. */\n icon?: string;\n /** Offered but not pickable now. A control shows it dimmed, with {@link description} as the reason. */\n disabled?: boolean;\n /** One line under the label — for a disabled option, why it is off. */\n description?: string;\n}\n\n/**\n * The value kinds a {@link CommandArgSpec} can describe. The first five are\n * plain JSON values; `layer` / `behaviour` / `layout` are the **id** of a\n * registered instance (an editor offers the live registry as choices); `json`\n * is any JSON value the editor can only take as text (maps, number lists).\n */\nexport type CommandArgKind =\n | 'string'\n | 'number'\n | 'boolean'\n | 'enum'\n | 'strings'\n | 'layer'\n | 'behaviour'\n | 'layout'\n | 'json';\n\n/**\n * Describes one key of a command's `args` bag — plain data, so the kernel stays\n * UI-free; the UI kit maps it to a form field. Optional on every command: an\n * undescribed command (or key) is still editable as raw JSON.\n */\nexport interface CommandArgSpec {\n /** The value's kind. */\n kind: CommandArgKind;\n /** Field label. Default: the key. */\n label?: string;\n /** One-line help shown under the field. */\n description?: string;\n /** The value the command uses when the key is absent — shown as a hint, never written. */\n default?: unknown;\n /** The allowed values, for `kind: 'enum'`. */\n options?: readonly CommandOption[];\n /**\n * The key a **pick-one** control supplies itself (`value` — see\n * {@link CanvasCommand.value}). An editor hides it on a `choice` item, where\n * picking sets it, and shows it on a button / toggle, where it's fixed.\n */\n pick?: boolean;\n /**\n * The command can't run without this key (`behaviour.toggle`'s `id`). A\n * surface that runs commands bare — the palette — leaves such commands out.\n * Default `false`: an absent key falls back to {@link default} or the\n * command's own behaviour.\n */\n required?: boolean;\n}\n\n/**\n * A **command map**: command name → the type of its `args` bag. A package\n * exports its commands' map as a type (`EngineCommandMap` in `@invana/canvas`,\n * `GraphCommandMap` in `@invana/graph`) and a registry typed with it\n * (`CommandRegistry<C, M>`) checks the args of those names at compile time —\n * types only, nothing at runtime. Any other name still takes `unknown` args, so\n * app-registered commands keep working. Merge maps with `&`.\n */\nexport type CommandMap = object;\n\n/** A command name: one of `M`'s (offered for completion), or any other string. */\nexport type CommandName<M extends CommandMap> = (keyof M & string) | (string & {});\n\n/**\n * The `args` type of command `K` in map `M` — `unknown` for a name `M` doesn't\n * list. An indexed access, not a conditional type, so a registry stays\n * covariant in its map: a `CommandRegistry<C, Wider>` is a\n * `CommandRegistry<C, Narrower>` (a subclass can widen `commands`' map).\n */\nexport type CommandArgsOf<M extends CommandMap, K extends string> = (M & Record<string, unknown>)[K];\n\n/**\n * A named command, run against a context `C`. `args` is whatever the caller's\n * spec carried (JSON); `A` narrows it for a command whose map entry is known.\n *\n * Its `isEnabled` / `isActive` / `value` / `options` may read anything; a bound\n * control re-reads them on view-store writes and on the registry's\n * {@link CommandRegistry.subscribe} signal. State outside the store needs an\n * owner-side {@link CommandRegistry.invalidate} bridge — see there.\n */\nexport interface CanvasCommand<C, A = unknown> {\n /** Human label — a default tooltip when a spec doesn't give one. */\n label?: string;\n /**\n * Group a command palette / menu lists it under (`'Camera'`, `'Edit'`,\n * `'Layout'`, …). Data only — the kernel never reads it.\n */\n category?: string;\n /** Extra search terms a command palette matches besides the label and name. Data only. */\n keywords?: readonly string[];\n /**\n * The keys `args` may carry, described for editors (the Studio's toolbar\n * editor draws a field per key). In dev builds {@link CommandRegistry.run}\n * checks a described key's value against its `kind` and warns (never throws)\n * on a mismatch — see {@link CommandRegistryOptions.validateArgs}. Keys it\n * doesn't name still pass through unchecked.\n */\n args?: Readonly<Record<string, CommandArgSpec>>;\n /**\n * Perform the command. A command whose work finishes later (a layout run)\n * returns its promise, so {@link CommandRegistry.runAsync} can wait for it;\n * {@link CommandRegistry.run} ignores it.\n */\n run(ctx: C, args?: A): void | Promise<void>;\n /** Toggle state for toggle-style controls. Absent ⇒ never active. */\n isActive?(ctx: C, args?: A): boolean;\n /** Whether the command can run now. Absent ⇒ always enabled. */\n isEnabled?(ctx: C, args?: A): boolean;\n /**\n * Current value, for a **pick-one** command (select mode, edge type, active\n * layout). Picking an option runs the command with `{ ...args, value }`.\n * `null` when nothing is picked.\n */\n value?(ctx: C, args?: A): string | null;\n /** The options a pick-one command offers. A spec's own `options` take precedence. */\n options?(ctx: C, args?: A): CommandOption[];\n}\n\n/** Options for {@link CommandRegistry}. */\nexport interface CommandRegistryOptions<C> {\n /** The context every command runs against (resolved lazily, per call). */\n getContext: () => C;\n /**\n * Check `args` against each command's {@link CanvasCommand.args} descriptors\n * in {@link CommandRegistry.run}, warning once per (command, key, problem) on\n * a mismatch. Never throws, never blocks the run. Default: on in dev builds\n * (`process.env.NODE_ENV !== 'production'`), off in production bundles.\n */\n validateArgs?: boolean;\n}\n\n/**\n * Whether this is a dev build. Written as the literal `process.env.NODE_ENV`\n * so consumer bundlers substitute it (and drop the validator in production);\n * where `process` doesn't exist at all (an unbundled browser) it's `false`.\n */\nfunction isDevBuild(): boolean {\n try {\n // `process` isn't declared in this dependency-free package.\n return (process as { env: { NODE_ENV?: string } }).env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n\ndeclare const process: unknown;\n\n/** Why `value` doesn't fit `spec`, or `null` when it does. */\nfunction argProblem(spec: CommandArgSpec, value: unknown): string | null {\n switch (spec.kind) {\n case 'string':\n case 'layer':\n case 'behaviour':\n case 'layout':\n return typeof value === 'string' ? null : `expected a string (${spec.kind}), got ${describe(value)}`;\n case 'number': {\n if (typeof value === 'number' && Number.isFinite(value)) return null;\n // A picker hands its pick back as a string (`camera.zoomTo`'s `value`).\n if (spec.pick && typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return null;\n return `expected a finite number, got ${describe(value)}`;\n }\n case 'boolean':\n return typeof value === 'boolean' ? null : `expected a boolean, got ${describe(value)}`;\n case 'enum': {\n const allowed = (spec.options ?? []).map((o) => o.value);\n return typeof value === 'string' && allowed.includes(value)\n ? null\n : `expected one of ${allowed.map((v) => JSON.stringify(v)).join(', ')}, got ${describe(value)}`;\n }\n case 'strings':\n return Array.isArray(value) && value.every((v) => typeof v === 'string')\n ? null\n : `expected an array of strings, got ${describe(value)}`;\n case 'json':\n return null;\n }\n}\n\nfunction describe(value: unknown): string {\n if (Array.isArray(value)) return 'an array';\n if (value === null) return 'null';\n return typeof value === 'string' ? JSON.stringify(value) : typeof value;\n}\n\n/**\n * Holds {@link CanvasCommand}s by name and runs them against a bound context.\n *\n * `M` ({@link CommandMap}) types the args of the names it lists — `register`\n * (the handler's `args`), `run`, `isEnabled`, `isActive`, `value`, `options` —\n * while every other name takes `unknown` args. Unset, nothing is typed, and a\n * typed registry still passes where a `CommandRegistry<C>` is expected. Types\n * only: the registry behaves the same for any `M`.\n *\n * Registrations **stack** per name: registering a name that already exists\n * overrides it (a provider upgrading `graph.clear` to its undoable form, an app\n * replacing a built-in), and disposing an override restores whatever is\n * underneath — in any disposal order. {@link subscribe} listeners hear every\n * register / unregister and every {@link invalidate}, so a UI can re-read\n * command state.\n */\nexport class CommandRegistry<C, M extends CommandMap = Record<never, never>> {\n /** Per name, the registrations oldest → newest; the last one is live. */\n private readonly stacks = new Map<string, Array<{ command: CanvasCommand<C> }>>();\n private readonly listeners = new Set<() => void>();\n /** Bumped on every {@link subscribe} signal — see {@link version}. */\n private _version = 0;\n private readonly getContext: () => C;\n private readonly validateArgs: boolean;\n /** `command|key|problem` already warned about, so a bound button doesn't flood the console. */\n private readonly warned = new Set<string>();\n\n constructor(opts: CommandRegistryOptions<C>) {\n this.getContext = opts.getContext;\n this.validateArgs = opts.validateArgs ?? isDevBuild();\n }\n\n /**\n * Register `name`, overriding any existing registration. Returns a disposer\n * that removes **this** registration only: if it is live, the one underneath\n * becomes live again; if it was already overridden, the override stays.\n */\n register<K extends CommandName<M>>(name: K, command: CanvasCommand<C, CommandArgsOf<M, K>>): () => void {\n // A fresh wrapper per call, so registering the same command twice still\n // yields two independently disposable entries.\n const entry = { command };\n const stack = this.stacks.get(name) ?? [];\n stack.push(entry);\n this.stacks.set(name, stack);\n this.notify();\n return () => {\n const current = this.stacks.get(name);\n const i = current?.indexOf(entry) ?? -1;\n if (!current || i < 0) return;\n current.splice(i, 1);\n if (current.length === 0) this.stacks.delete(name);\n this.notify();\n };\n }\n\n /** Remove every registration of `name`. No-op when absent. */\n unregister(name: string): void {\n if (this.stacks.delete(name)) this.notify();\n }\n\n has(name: string): boolean {\n return this.stacks.has(name);\n }\n\n /** The live (most recent) registration of `name`. */\n get(name: string): CanvasCommand<C> | undefined {\n const stack = this.stacks.get(name);\n return stack?.[stack.length - 1]?.command;\n }\n\n /** Registered command names, in first-registration order. */\n list(): string[] {\n return [...this.stacks.keys()];\n }\n\n /**\n * Run `name` with `args`. Returns `false` (and does nothing) when the command\n * is missing or disabled. With `validateArgs` on, first warns about any\n * described key whose value doesn't fit its descriptor — the run proceeds\n * regardless.\n */\n run<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n if (!cmd) return false;\n if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);\n const ctx = this.getContext();\n if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;\n void cmd.run(ctx, args);\n return true;\n }\n\n /**\n * {@link run}, awaiting the command's work: resolves once the promise a\n * command's `run` returned settles (`layout.run` resolves when the layout\n * run ends). Resolves `false` — without running anything — when the command\n * is missing or disabled; a synchronous command resolves `true` at once. A\n * playbook step's `do` verbs go through here, so each finishes before the\n * next starts.\n */\n async runAsync<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): Promise<boolean> {\n const cmd = this.get(name);\n if (!cmd) return false;\n if (this.validateArgs && cmd.args) this.checkArgs(name, cmd.args, args);\n const ctx = this.getContext();\n if (cmd.isEnabled && !cmd.isEnabled(ctx, args)) return false;\n await cmd.run(ctx, args);\n return true;\n }\n\n /** `isActive` of `name`; `false` when missing or not a toggle. */\n isActive<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n return cmd?.isActive ? cmd.isActive(this.getContext(), args) : false;\n }\n\n /** `isEnabled` of `name`; `false` when missing, `true` when it declares no check. */\n isEnabled<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): boolean {\n const cmd = this.get(name);\n if (!cmd) return false;\n return cmd.isEnabled ? cmd.isEnabled(this.getContext(), args) : true;\n }\n\n /** `value` of a pick-one command; `null` when missing or not a picker. */\n value<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): string | null {\n const cmd = this.get(name);\n return cmd?.value ? cmd.value(this.getContext(), args) : null;\n }\n\n /** `options` of a pick-one command; `[]` when missing or it declares none. */\n options<K extends CommandName<M>>(name: K, args?: CommandArgsOf<M, K>): CommandOption[] {\n const cmd = this.get(name);\n return cmd?.options ? cmd.options(this.getContext(), args) : [];\n }\n\n /**\n * Tell subscribers that command state changed **outside** the view store (a\n * history stack, a clipboard buffer, a layer's edge defaults, a registry), so\n * a bound control re-reads `isEnabled` / `isActive` / `value` / `options`.\n *\n * Call it from the state's **owner** — a bridge from the owner's own change\n * signal, set up once (the engine bridges the registries, layer visibility and\n * `canvas.history`; `GraphCanvas` its layers' edge templates; a provider its\n * own history / clipboard) — never from the write sites, where another\n * writer would forget it. A command whose state lives in the view store\n * needs none.\n */\n invalidate(): void {\n this.notify();\n }\n\n /**\n * A counter bumped on every {@link subscribe} signal (register, unregister,\n * dispose, {@link invalidate}, {@link clear}) — and only then. Use it as a\n * `useSyncExternalStore` snapshot when a UI must re-read *everything* on a\n * signal: a snapshot derived from `list()` stays equal when only a command's\n * `options` / state changed, and React would skip the re-render.\n */\n get version(): number {\n return this._version;\n }\n\n /** Hear every register / unregister / {@link invalidate}. Returns an unsubscribe. */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** Drop every command and listener. */\n clear(): void {\n this.stacks.clear();\n this.notify();\n this.listeners.clear();\n }\n\n /** Warn (once each) about `args` values that don't fit `specs`. */\n private checkArgs(name: string, specs: Readonly<Record<string, CommandArgSpec>>, args: unknown): void {\n if (args === undefined || args === null) return;\n if (typeof args !== 'object' || Array.isArray(args)) {\n this.warn(name, '', `args should be an object, got ${describe(args)}`);\n return;\n }\n for (const [key, spec] of Object.entries(specs)) {\n const value = (args as Record<string, unknown>)[key];\n if (value === undefined) continue;\n const problem = argProblem(spec, value);\n if (problem) this.warn(name, key, problem);\n }\n }\n\n private warn(name: string, key: string, problem: string): void {\n const id = `${name}|${key}|${problem}`;\n if (this.warned.has(id)) return;\n this.warned.add(id);\n console.warn(`[canvas] command \"${name}\"${key ? ` arg \"${key}\"` : ''}: ${problem}`);\n }\n\n private notify(): void {\n this._version++;\n for (const l of [...this.listeners]) l();\n }\n}\n","/**\n * Pure geometry — points, rectangles, polylines, paths, and the router / pathStyle\n * function contracts that operate on them. No drawing library appears here.\n *\n * Part of the pixi-free spec vocabulary — see `docs/renderer-split-design.md`.\n */\n\n// ─── Geometry primitives ───────────────────────────────────────────────────\n\n// Defined once, in the kernel's geometry vocabulary, and re-exported here so the\n// spec surface stays self-describing. Do not redeclare them — `../geom` is\n// the single home (see the RFC that merged the two definitions:\n// `docs/rfcs/fix/2026-08-10-zustand-imported-outside-canvas-store.md` §4.4).\nexport type { Point, Vec2, Rect, Size } from './geom';\n\nimport type { Point, Vec2, Rect } from './geom';\n\n/** Endpoint anchor a router consumes — point + optional outgoing tangent. */\n\nexport interface Endpoint {\n readonly x: number;\n readonly y: number;\n readonly tangent?: Vec2;\n}\n\n// ─── Polyline (router output, pathStyle input) ─────────────────────────────\n\n/**\n * Flat ordered list of points. Output of a `Router`; input to a `PathStyle`.\n * Also used as the densified form of a `Path` for hit-testing\n * (`samplePath(path)`).\n */\n\nexport type Polyline = ReadonlyArray<Point>;\n\n// ─── Path (pathStyle output, connector input) ──────────────────────────────\n\n/**\n * One step of a `Path`. Mirrors SVG path commands one-for-one:\n * - `M` move to absolute (x, y) — must be the first command of any Path.\n * - `L` line to (x, y) from the current point.\n * - `Q` quadratic Bézier with one control point.\n * - `C` cubic Bézier with two control points.\n *\n * No relative variants, no arcs, no shorthand — pathStyles emit one of these\n * four. Connector renders by walking the path and dispatching to Pixi's\n * `moveTo` / `lineTo` / `quadraticCurveTo` / `bezierCurveTo`.\n */\n\nexport type PathCommand =\n | { readonly kind: 'M'; readonly x: number; readonly y: number }\n | { readonly kind: 'L'; readonly x: number; readonly y: number }\n | { readonly kind: 'Q'; readonly cx: number; readonly cy: number; readonly x: number; readonly y: number }\n | { readonly kind: 'C'; readonly c1x: number; readonly c1y: number; readonly c2x: number; readonly c2y: number; readonly x: number; readonly y: number };\n\nexport type Path = ReadonlyArray<PathCommand>;\n\n/**\n * Read-only scene context handed to routers that need awareness of other\n * shapes — primarily for obstacle-avoidance routing (`manhattan` and\n * friends). Simple geometric routers (`straight`, `orth`) ignore it.\n *\n * `obstacles` are world-space `Rect`s the router should not cross. Each\n * obstacle may also expose `containsInflated` for pixel-accurate silhouette\n * testing (e.g. circles route around their tangent, not their AABB).\n * The renderer auto-collects these from `shapeInstances` (excluding the\n * source/target shapes); callers can override or opt out via\n * `routerOpts.obstacles`.\n */\n\nexport interface RouterCtx {\n readonly obstacles: ReadonlyArray<Obstacle>;\n}\n\n/**\n * Obstacle handed to obstacle-aware routers. `Obstacle extends Rect` so any\n * `Rect[]` is assignable; the optional `containsInflated` callback unlocks\n * silhouette-tight routing for non-rect shapes (circles, polygons, paths).\n */\n\nexport interface Obstacle extends Rect {\n /**\n * Optional silhouette obstacle-test in world coordinates. Returns `true`\n * when `(worldX, worldY)` lies inside the obstacle's silhouette OR within\n * `inflate` world units of it.\n *\n * Routers use this for pixel-accurate marking — when present, the grid\n * blocks only cells that pass this test (in addition to the cheap AABB\n * pre-filter). When absent, the inflated AABB is the source of truth.\n *\n * Shapes opt in by overriding `IShape.obstacleTest`.\n */\n readonly containsInflated?: (worldX: number, worldY: number, inflate: number) => boolean;\n}\n\n/**\n * Router: a pure function `(source, target, waypoints?, opts?, ctx?) → Polyline`.\n *\n * Routers decide path **topology** — where bends sit. They emit a flat\n * polyline (Point[]); the visual style of segments between bend points is\n * decided by the downstream `PathStyle`. Routers never touch pixi.\n *\n * `waypoints` are intermediate user-supplied points the router should respect.\n * Built-in `straight` passes them through verbatim; topological routers\n * (orth, manhattan, …) anchor stair / corner segments to them.\n *\n * `ctx` is optional — only obstacle-aware routers consume it. The renderer\n * always passes a `RouterCtx`; routers that ignore it lose nothing.\n */\n\nexport type IRouter = (\n source: Endpoint,\n target: Endpoint,\n waypoints?: ReadonlyArray<Point>,\n opts?: Record<string, unknown>,\n ctx?: RouterCtx,\n) => Polyline;\n\n/**\n * Anchor-resolved endpoints handed to a pathStyle alongside the polyline.\n *\n * Tangent-aware pathStyles (`bump-horizontal`, …) read `source.tangent` /\n * `target.tangent` to place their Bézier handles along each shape's outward\n * surface normal, so the curve leaves and arrives flush with the silhouette\n * instead of in a hard-coded direction. Tangent-agnostic pathStyles (`normal`,\n * `rounded`, …) simply ignore the argument — it's optional and additive.\n */\n\nexport interface PathStyleEndpoints {\n readonly source: Endpoint;\n readonly target: Endpoint;\n}\n\n/**\n * PathStyle: a pure function `(polyline, opts?, endpoints?) → Path`.\n *\n * PathStyles decide visual **style** — how segments between polyline points\n * are drawn (sharp, rounded fillets, bezier-smoothed, single bezier A→B).\n * They never see the connector spec or shape context; pure geometric\n * transform.\n *\n * `endpoints` carries the anchor-resolved source/target (with `tangent`) so\n * tangent-aware styles can align Bézier handles with each shape's outward\n * normal. Optional — styles that don't need it ignore the argument and a\n * direct unit-test invocation (`bumpHorizontal(polyline)`) keeps working.\n *\n * Built-ins: `normal` (sharp), `rounded` (quadratic fillets at corners),\n * `smooth` (Catmull-Rom → cubic), `bezier` (single cubic with auto controls).\n */\n\nexport type IPathStyle = (\n polyline: Polyline,\n opts?: Record<string, unknown>,\n endpoints?: PathStyleEndpoints,\n) => Path;\n\n// ─── Fill ──────────────────────────────────────────────────────────────────\n\n/**\n * Anchor positions for inset content layers (`glyph`, `svg`, `svg-url`).\n * Defaults to `'center'`. Use `'top-right'` etc. for corner-badge\n * composition.\n */\n\n/**\n * Stable key of a connector spec with paint removed — geometry only.\n *\n * Two specs with the same key route to the same path, so a caller can skip a\n * re-route when only `stroke` changed. Pure: it reads the spec and nothing\n * else, which is why it lives here rather than on a renderer.\n */\nexport function connectorGeometryKey(spec: object): string {\n const { stroke: _stroke, ...geometry } = spec as { stroke?: unknown };\n return JSON.stringify(geometry);\n}\n","/**\n * Fill, stroke and paint-override vocabulary. Values are plain numbers and enums —\n * a colour is `0xRRGGBB`, never a backend colour object.\n *\n * Part of the pixi-free spec vocabulary — see `docs/renderer-split-design.md`.\n */\n\nexport type InsetAnchor =\n | 'center'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\n/**\n * One layer of a shape's fill. Layers split by role:\n *\n * - **Silhouette fillers** (`solid`, `image`) — paint into the silhouette\n * via Pixi's `g.fill()`. Multiple silhouette layers stack via alpha;\n * each is re-traced before painting. Image fills always render the\n * texture cover-fitted to the silhouette (uniform scale, may crop) —\n * the engine intentionally does not expose CSS-style `background-size`\n * / `background-repeat` knobs on raster fills.\n * - **Inset content** (`glyph`, `svg`, `svg-url`) — mounted as Container\n * children of the shape's `gfx`. Sized by `sizeRatio` (fraction of the\n * smaller bounds dimension) and positioned by `anchor` (default\n * `'center'`).\n *\n * The engine has no dedicated \"icon\" kind — icon-library specifics (Font\n * Awesome glyphs, Lucide SVGs, Fluent icons, …) are produced by developer\n * code and dropped into a `glyph` or `svg` layer directly.\n */\n\nexport type ShapeFillLayer =\n | { readonly kind: 'solid'; readonly color: number; readonly alpha?: number }\n | {\n /**\n * Raster image painted into the host silhouette.\n *\n * Two orthogonal knobs control sizing:\n *\n * - `fit` (default `'cover'`) — how the texture's aspect maps to\n * the silhouette's AABB. `'cover'` scales by `max(...)`, fully\n * covers, may crop on the cross-axis. `'contain'` scales by\n * `min(...)`, fully fits, leaves the cross-axis margin\n * transparent (the underlying fill layer reads through; the\n * engine pins the texture sampler to `clamp-to-edge` so the\n * margin doesn't tile).\n *\n * - `padding` (default `0`) — pixel inset on the silhouette\n * *before* fit math runs. The silhouette itself is re-traced at\n * that inset for this layer only, so the gap between the\n * full-size silhouette and the inset silhouette is painted by\n * layers underneath (typically a `solid` `bgFill`). Use this\n * when the host silhouette is more restrictive than its AABB\n * (circle, polygon, star, arc) and the texture corners would\n * otherwise clip against the curve.\n *\n * Tile patterns, repeat modes, and inset-Sprite badge placement\n * aren't on the engine surface — stack a `glyph` / `svg` /\n * `svg-url` layer for icon-shaped content.\n */\n readonly kind: 'image';\n readonly url: string;\n readonly alpha?: number;\n readonly fit?: 'cover' | 'contain';\n readonly padding?: number;\n }\n | {\n /** Font-rendered character (icon-font codepoint, Unicode symbol, emoji). */\n readonly kind: 'glyph';\n readonly char: string;\n /** Required for icon-font glyphs; optional for system-font Unicode. */\n readonly fontFamily?: string;\n /**\n * Font weight (CSS value, e.g. `400`, `900`, `'bold'`). Required for\n * icon fonts that pack different glyph sets per weight.\n */\n readonly fontWeight?: number | string;\n readonly fontStyle?: 'normal' | 'italic';\n /** Glyph color. Default `0xffffff`. */\n readonly color?: number;\n readonly alpha?: number;\n /** Size as fraction of the shape's smaller bounds dimension. Default `0.6`. */\n readonly sizeRatio?: number;\n /** Anchor relative to the shape's bounds. Default `'center'`. */\n readonly anchor?: InsetAnchor;\n /**\n * Rotation of the inset about its own centre, in **radians, clockwise from\n * up** (a compass course in radians). Default `0`. Applied without\n * rebuilding the inset, so it is cheap to change per frame; the shape's\n * label and silhouette are not rotated.\n */\n readonly rotation?: number;\n }\n | {\n /** SVG path-d. Multiple subpaths (`M...M...`) are supported. */\n readonly kind: 'svg';\n readonly pathD: string;\n /** Viewport the path was authored in. Default `{ width: 24, height: 24 }`. */\n readonly viewBox?: { readonly width: number; readonly height: number };\n /** Stroke width when rendering. Default `2`. */\n readonly strokeWidth?: number;\n readonly color?: number;\n readonly alpha?: number;\n readonly sizeRatio?: number;\n readonly anchor?: InsetAnchor;\n /**\n * Rotation of the inset about its own centre, in **radians, clockwise from\n * up** (a compass course in radians). Default `0`. Applied without\n * rebuilding the inset, so it is cheap to change per frame; the shape's\n * label and silhouette are not rotated.\n */\n readonly rotation?: number;\n }\n | {\n /**\n * Vector SVG icon fetched from a URL. The engine fetches the SVG,\n * extracts every drawing primitive (`path` / `ellipse` / `circle` /\n * `rect` / `line` / `polyline` / `polygon`) into a single concatenated\n * `pathD`, and renders it as a Pixi Graphics path. Fetched lazily on\n * first use; the resulting `pathD` is cached globally per URL.\n *\n * Use this when a consumer wants to point at their own remote SVG\n * (logo, custom diagram, sample artwork). For curated icon-library\n * usage, prefer an icon-font glyph via `kind: 'glyph'` — the\n * library is icon-vendor-agnostic and intentionally has no\n * vendor-specific fetch glue.\n */\n readonly kind: 'svg-url';\n readonly url: string;\n readonly viewBox?: { readonly width: number; readonly height: number };\n readonly strokeWidth?: number;\n readonly color?: number;\n readonly alpha?: number;\n readonly sizeRatio?: number;\n readonly anchor?: InsetAnchor;\n /**\n * Rotation of the inset about its own centre, in **radians, clockwise from\n * up** (a compass course in radians). Default `0`. Applied without\n * rebuilding the inset, so it is cheap to change per frame; the shape's\n * label and silhouette are not rotated.\n */\n readonly rotation?: number;\n };\n\n/**\n * A shape's fill. Either a single layer, an array of layers (painted\n * bottom-up — first array entry sits underneath), or the `number` shorthand\n * for a solid color.\n */\n\nexport type ShapeFill =\n | number\n | ShapeFillLayer\n | ReadonlyArray<ShapeFillLayer>;\n\n/**\n * The **inset-content** half of {@link ShapeFillLayer} — the layer kinds a\n * backend mounts *inside* the silhouette as a child rather than painting\n * *into* it. Named here (not only where it is mounted) because it is part of\n * the vocabulary: a `CompositePart` of kind `'icon'` carries one, so the spec\n * types must be able to reference it without reaching into a renderer.\n */\nexport type InsetFillLayer = Extract<\n ShapeFillLayer,\n { kind: 'glyph' | 'svg' | 'svg-url' }\n>;\n\n/**\n * Does this fill paint the **silhouette** — i.e. would a backend emit a fill\n * for it? True for the `number` shorthand and for any `solid` / `image` layer;\n * false for `undefined` and for a fill made only of inset content\n * ({@link InsetFillLayer}), which mounts a child instead of filling.\n *\n * Load-bearing for hit-testing: a shape with no silhouette fill is **hollow**\n * — only its stroke band answers a containment test, exactly as pixi's\n * `Graphics.containsPoint` behaves (it consults a `fill` instruction that was\n * never emitted). See `containsSpec` in `specs/shapeGeometry/`.\n */\nexport function hasSilhouetteFill(fill: ShapeFill | undefined): boolean {\n if (fill === undefined) return false;\n if (typeof fill === 'number') return true;\n const layers = Array.isArray(fill) ? fill : [fill as ShapeFillLayer];\n return layers.some((l) => l.kind === 'solid' || l.kind === 'image');\n}\n\n// ─── Stroke (border) ───────────────────────────────────────────────────────\n\nexport interface ShapeStroke {\n readonly color: number;\n readonly alpha?: number;\n readonly width?: number;\n /** Default `'center'`. */\n readonly alignment?: 'inside' | 'center' | 'outside';\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n}\n\n// ─── Paint styles (decoration → primitive override) ────────────────────────\n\n/**\n * Decoration entry-point override on `IShape.paintInto`. When supplied, the\n * shape ignores `spec.fill` / `spec.stroke` and paints with these values\n * instead. Decorations like glow widen `strokeWidth` and reduce `alpha` to\n * paint a halo; decorations like marching-ants supply `dashArray` /\n * `dashOffset` to render a dashed silhouette; decorations like ring/halo\n * with non-zero `inset` ask the shape to trace a parallel-offset version of\n * its own silhouette.\n */\n\nexport interface ShapePaintStyle {\n readonly color?: number;\n readonly alpha?: number;\n readonly strokeWidth?: number;\n /**\n * Stroke alignment relative to the silhouette. Default `'outside'` —\n * decorations almost always want their geometry painted outside the\n * host body (halo, glow, ring), so the inner band doesn't eat into the\n * fill. Override per-call when a decoration genuinely wants to bleed\n * inward (e.g. an \"inset border\" effect).\n */\n readonly alignment?: 'inside' | 'center' | 'outside';\n /** Default `false` — decorations almost always stroke without filling. */\n readonly fill?: boolean;\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n /** Positive = inside the silhouette, negative = outside. Default `0`. */\n readonly inset?: number;\n}\n\n/** Mirror of `ShapePaintStyle` for connectors. No `inset` (connectors are 1D). */\n\nexport interface ConnectorPaintStyle {\n readonly color?: number;\n readonly alpha?: number;\n readonly strokeWidth?: number;\n readonly dashArray?: readonly [number, number];\n readonly dashOffset?: number;\n readonly cap?: 'butt' | 'round' | 'square';\n readonly join?: 'miter' | 'round' | 'bevel';\n /**\n * When `true`, markers paint with `color` / `alpha` instead of their own\n * spec colors. Glow / halo decorations use this so the decoration covers\n * path + markers as a unified silhouette; marching-ants leaves it\n * undefined so markers stay normal-colored over the dashed line.\n */\n readonly tintMarkers?: boolean;\n /**\n * When `true`, `paintInto` paints only the body (no source / target\n * markers). Useful for decorations that handle markers separately or\n * want to leave them untouched. `markerHalo` is preferred for glow /\n * halo coverage; reach for `skipMarkers` only when even outlined\n * markers would be wrong.\n */\n readonly skipMarkers?: boolean;\n /**\n * When `true`, markers paint as **outlines** at `style.strokeWidth`\n * (using `style.color` / `style.alpha`) instead of as filled silhouettes.\n * Marker geometry continues to size off the host connector's spec\n * stroke width — the halo width affects only the outline stroke, never\n * the marker's tip-to-base / wing-spread dimensions. Combined with the\n * widening-stroke / decreasing-alpha pattern of a glow decoration,\n * this produces a halo around the marker that matches the body halo.\n */\n readonly markerHalo?: boolean;\n}\n\n// ─── Spec types ────────────────────────────────────────────────────────────\n\n/**\n * Ordered paint stripe. Earlier entries paint **below** later ones, and a stripe\n * always wins over `zIndex`: `plane` picks the stripe, `zIndex` orders *within*\n * it. Independent of the scene graph — a shape keeps its logical parent (and so\n * its transform); only its render order moves.\n *\n * `'backdrop'` is the only stripe below the connectors, which is what makes a\n * group frame able to sit under the edges between its own members — see\n * `docs/rfcs/fix/2026-08-05-group-frame-occludes-edges.md`.\n *\n * @remarks\n * The design of record (`docs/render-planes-and-emphasis-plan.md` §4.1) defines\n * five stripes — `backdrop` · `background` · `content` · `foreground` ·\n * `overlay`. Two are implemented: `'backdrop'` and the default `'content'`. The\n * remaining three are served today by the renderer's built-in connector / shape\n * / overlay ordering; widening this union later is additive.\n */\n","/**\n * Polygon maths shared by every spec kind whose silhouette is (or densifies\n * to) a closed vertex ring — `polygon`, `regular-polygon`, `star`,\n * `tabbed-rect`, `path`, and the sampled `arc` fallback.\n *\n * Pure functions over plain `{x, y}` arrays in shape-local space. No drawing\n * library, and nothing from `primitives/` — this file is what lets picking and\n * bounds be answered with no GPU (see `docs/renderer-split-design.md` §4.5,\n * \"what stays engine-side\").\n *\n * Convention: all vertex arrays here are **centre-relative** — the silhouette\n * is traced around the origin so that `boundaryIntersect` (which receives\n * centre-relative input) works without an extra translation step. The one\n * exception is `tabbed-rect`, whose outline is AABB-origin-relative; it says so\n * at its own call sites.\n */\n\nimport type { Point, Rect } from '../geometry';\n\n/** Tight axis-aligned bounding box around the vertex list. */\nexport function polygonBounds(vertices: ReadonlyArray<Point>): Rect {\n if (vertices.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n let minX = vertices[0]!.x;\n let maxX = minX;\n let minY = vertices[0]!.y;\n let maxY = minY;\n for (let i = 1; i < vertices.length; i++) {\n const v = vertices[i]!;\n if (v.x < minX) minX = v.x;\n else if (v.x > maxX) maxX = v.x;\n if (v.y < minY) minY = v.y;\n else if (v.y > maxY) maxY = v.y;\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/**\n * Even-odd ray-cast point-in-polygon test. Handles convex and concave\n * silhouettes. Treats the polygon as closed (last vertex implicitly\n * connects to first).\n */\nexport function pointInPolygon(\n localX: number,\n localY: number,\n vertices: ReadonlyArray<Point>,\n): boolean {\n const n = vertices.length;\n if (n < 3) return false;\n let inside = false;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const vi = vertices[i]!;\n const vj = vertices[j]!;\n const intersects =\n vi.y > localY !== vj.y > localY &&\n localX < ((vj.x - vi.x) * (localY - vi.y)) / (vj.y - vi.y) + vi.x;\n if (intersects) inside = !inside;\n }\n return inside;\n}\n\n/** Squared distance from `(px, py)` to the segment `(x1, y1) → (x2, y2)`. */\nexport function distanceToSegmentSq(\n px: number,\n py: number,\n x1: number,\n y1: number,\n x2: number,\n y2: number,\n): number {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const lenSq = dx * dx + dy * dy;\n // Degenerate segment (both endpoints coincide) — fall back to point distance.\n let t = lenSq === 0 ? 0 : ((px - x1) * dx + (py - y1) * dy) / lenSq;\n t = t < 0 ? 0 : t > 1 ? 1 : t;\n const ex = x1 + t * dx - px;\n const ey = y1 + t * dy - py;\n return ex * ex + ey * ey;\n}\n\n/**\n * Squared distance from `(x, y)` to the nearest **edge** of a vertex ring.\n * `closed` includes the wrap-around edge (last → first); an open run omits it,\n * which is what a `path` spec with `closed: false` draws.\n */\nexport function distanceToOutlineSq(\n x: number,\n y: number,\n vertices: ReadonlyArray<Point>,\n closed = true,\n): number {\n const n = vertices.length;\n if (n === 0) return Infinity;\n if (n === 1) {\n const v = vertices[0]!;\n return (x - v.x) * (x - v.x) + (y - v.y) * (y - v.y);\n }\n const edges = closed ? n : n - 1;\n let best = Infinity;\n for (let i = 0; i < edges; i++) {\n const a = vertices[i]!;\n const b = vertices[(i + 1) % n]!;\n const d = distanceToSegmentSq(x, y, a.x, a.y, b.x, b.y);\n if (d < best) best = d;\n }\n return best;\n}\n\n/**\n * Containment against a vertex ring **grown (or shrunk) by `pad`**.\n *\n * - `pad > 0` — inside the ring *or* within `pad` of its outline. This is the\n * region a centred stroke of half-width `pad` covers, and it is exactly the\n * union pixi's `Graphics.containsPoint` reports for a filled + stroked\n * polygon (`Polygon.contains` ∪ `Polygon.strokeContains`).\n * - `pad < 0` — inside the ring *and* further than `|pad|` from its outline:\n * the silhouette eroded inward, used to punch the hole out of a\n * fill-less shape so only its stroke band answers `true`.\n *\n * The offset is a true distance offset (round joins at convex corners), not a\n * miter offset, so a spike's tip grows by `pad` rather than by `pad / sin(θ/2)`\n * — the same approximation pixi makes.\n */\nexport function polygonContainsInflated(\n x: number,\n y: number,\n vertices: ReadonlyArray<Point>,\n pad = 0,\n closed = true,\n): boolean {\n const inside = closed && pointInPolygon(x, y, vertices);\n if (pad === 0) return inside;\n const nearOutline = distanceToOutlineSq(x, y, vertices, closed) <= pad * pad;\n return pad > 0 ? inside || nearOutline : inside && !nearOutline;\n}\n\n/**\n * Parallel-offset a closed polygon by `distance` along each edge's inward\n * normal. Positive `distance` shrinks (inset); negative grows (outset).\n *\n * Each vertex is moved along the **bisector** of its two adjacent edge\n * normals, scaled so the perpendicular offset along the edges equals\n * `distance`. Sufficient for convex and mildly concave silhouettes — the\n * regular-polygon and star convenience kinds always produce well-behaved\n * shapes, free-form polygon insets are best-effort and may self-intersect at\n * extreme concavities.\n */\nexport function offsetPolygon(\n vertices: ReadonlyArray<Point>,\n distance: number,\n): Point[] {\n const n = vertices.length;\n if (n < 3 || distance === 0) return vertices.map((v) => ({ x: v.x, y: v.y }));\n\n // Inward normal of edge (a → b) for a clockwise polygon is (dy, -dx)/len;\n // for counter-clockwise it's (-dy, dx)/len. We don't know orientation up\n // front, so compute the signed area and flip accordingly.\n const ccw = signedArea(vertices) > 0;\n\n const out: Point[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const prev = vertices[(i + n - 1) % n]!;\n const curr = vertices[i]!;\n const next = vertices[(i + 1) % n]!;\n\n const e1 = unitNormal(prev, curr, ccw);\n const e2 = unitNormal(curr, next, ccw);\n\n // Bisector = sum of the two edge normals. Scale to preserve perpendicular\n // distance: divide by (1 + n1·n2) / |n1+n2|² … which simplifies to\n // distance / (1 + n1·n2) when |n1| = |n2| = 1 (both unit normals).\n const bx = e1.x + e2.x;\n const by = e1.y + e2.y;\n const dot = e1.x * e2.x + e1.y * e2.y;\n const denom = 1 + dot;\n // `denom` collapses to ~0 at a 180° spike — fall back to the edge normal\n // to avoid blowing up the offset vertex.\n if (Math.abs(denom) < 1e-6) {\n out[i] = { x: curr.x + e1.x * distance, y: curr.y + e1.y * distance };\n } else {\n const k = distance / denom;\n out[i] = { x: curr.x + bx * k, y: curr.y + by * k };\n }\n }\n return out;\n}\n\n/**\n * Vertices of a regular polygon with `sides` sides and circum-radius\n * `radius`, centred at the origin. `rotationRad` is added to the base angle.\n *\n * Base placement: first vertex at angle `-π/2 + rotationRad` (straight up).\n * So with `rotation = 0`: triangle (sides=3) points up, pentagon points up,\n * hexagon has a vertex at the top (pointy-top). For a flat-top hexagon, pass\n * `rotation = Math.PI / 6`.\n */\nexport function regularPolygonVertices(\n sides: number,\n radius: number,\n rotationRad: number,\n): Point[] {\n const n = Math.max(3, Math.floor(sides));\n const out: Point[] = new Array(n);\n const base = -Math.PI / 2 + rotationRad;\n const step = (Math.PI * 2) / n;\n for (let i = 0; i < n; i++) {\n const a = base + i * step;\n out[i] = { x: Math.cos(a) * radius, y: Math.sin(a) * radius };\n }\n return out;\n}\n\n/**\n * Vertices of a star with `points` outer points, alternating outer\n * (`outerRadius`) and inner (`innerRadius`) vertices around the origin.\n * `rotationRad` is added to the base angle.\n *\n * Base placement: first outer vertex at angle `-π/2 + rotationRad` (up).\n */\nexport function starVertices(\n points: number,\n innerRadius: number,\n outerRadius: number,\n rotationRad: number,\n): Point[] {\n const p = Math.max(3, Math.floor(points));\n const total = p * 2;\n const out: Point[] = new Array(total);\n const base = -Math.PI / 2 + rotationRad;\n const step = Math.PI / p; // half of full angular step\n for (let i = 0; i < total; i++) {\n const r = i % 2 === 0 ? outerRadius : innerRadius;\n const a = base + i * step;\n out[i] = { x: Math.cos(a) * r, y: Math.sin(a) * r };\n }\n return out;\n}\n\n/**\n * Ray from the origin toward `localFromCenter`, intersected with the polygon\n * silhouette. Returns the farthest hit (i.e. where the ray exits the\n * polygon) as a centre-relative point, or `null` if the ray doesn't cross\n * any edge.\n *\n * Used by `boundaryIntersect` to snap connector anchors to the exact\n * perimeter of polygonal shapes.\n */\nexport function rayPolygonIntersection(\n localFromCenter: Point,\n vertices: ReadonlyArray<Point>,\n): Point | null {\n const n = vertices.length;\n if (n < 2) return null;\n const dx = localFromCenter.x;\n const dy = localFromCenter.y;\n if (dx === 0 && dy === 0) return null;\n\n let bestT = -Infinity;\n let hit: Point | null = null;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const a = vertices[j]!;\n const b = vertices[i]!;\n const ex = b.x - a.x;\n const ey = b.y - a.y;\n // Solve [dx -ex] [t] = [a.x]\n // [dy -ey] [u] [a.y]\n const denom = dx * -ey - dy * -ex;\n if (denom === 0) continue;\n const t = (a.x * -ey - a.y * -ex) / denom;\n const u = (dx * a.y - dy * a.x) / denom;\n if (t >= 0 && u >= 0 && u <= 1 && t > bestT) {\n bestT = t;\n hit = { x: dx * t, y: dy * t };\n }\n }\n return hit;\n}\n\n/**\n * One vertex of a {@link roundedPolygonOutline} input ring: a corner point\n * plus the fillet radius to apply there. `r <= 0` keeps the corner sharp.\n */\nexport interface RoundedCorner extends Point {\n readonly r: number;\n}\n\n/**\n * Densify a closed corner ring into a polyline, replacing each corner that\n * carries `r > 0` with a tangent circular fillet.\n *\n * Works for **convex and concave** corners alike — the fillet centre is\n * placed along the corner's interior bisector, which flips side with the\n * corner's turn direction automatically. That's what lets a silhouette with\n * re-entrant corners (a folder's tab shoulder, a callout's notch) round its\n * outer corners while leaving the re-entrant ones sharp.\n *\n * The requested radius is clamped so a fillet can never consume more than\n * half of either adjacent edge, so authored radii larger than the geometry\n * degrade gracefully instead of self-intersecting. Arcs are sampled at\n * roughly one vertex per 2 px of arc length (min 2 segments), matching the\n * density the rounded-rect outline sampler uses.\n *\n * Output winds in the same direction as the input ring, starting at the\n * first corner (or the start of its fillet when it has one).\n */\nexport function roundedPolygonOutline(\n corners: ReadonlyArray<RoundedCorner>,\n): Point[] {\n const n = corners.length;\n if (n < 3) return corners.map((c) => ({ x: c.x, y: c.y }));\n\n const out: Point[] = [];\n for (let i = 0; i < n; i++) {\n const p = corners[i]!;\n const prev = corners[(i + n - 1) % n]!;\n const next = corners[(i + 1) % n]!;\n\n // Unit vectors from the corner toward each neighbour.\n const v1x = prev.x - p.x;\n const v1y = prev.y - p.y;\n const v2x = next.x - p.x;\n const v2y = next.y - p.y;\n const l1 = Math.hypot(v1x, v1y);\n const l2 = Math.hypot(v2x, v2y);\n if (p.r <= 0 || l1 < 1e-9 || l2 < 1e-9) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n const u1x = v1x / l1;\n const u1y = v1y / l1;\n const u2x = v2x / l2;\n const u2y = v2y / l2;\n\n // Interior half-angle at the corner. Collinear neighbours (θ ≈ π, a\n // straight run) and 180° spikes (θ ≈ 0) have no well-defined fillet.\n const cosT = Math.max(-1, Math.min(1, u1x * u2x + u1y * u2y));\n const theta = Math.acos(cosT);\n if (theta < 1e-6 || Math.PI - theta < 1e-6) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n const half = theta / 2;\n\n // Tangent distance from the corner, clamped to half of each adjacent\n // edge so neighbouring fillets can't overlap. The effective radius is\n // recovered from the clamped distance.\n const tangent = Math.min(p.r / Math.tan(half), l1 / 2, l2 / 2);\n const radius = tangent * Math.tan(half);\n if (radius < 1e-6) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n\n // Fillet centre sits along the bisector at `radius / sin(half)`.\n let bx = u1x + u2x;\n let by = u1y + u2y;\n const bl = Math.hypot(bx, by);\n if (bl < 1e-9) {\n out.push({ x: p.x, y: p.y });\n continue;\n }\n bx /= bl;\n by /= bl;\n const cx = p.x + bx * (radius / Math.sin(half));\n const cy = p.y + by * (radius / Math.sin(half));\n\n const a1 = Math.atan2(p.y + u1y * tangent - cy, p.x + u1x * tangent - cx);\n const a2 = Math.atan2(p.y + u2y * tangent - cy, p.x + u2x * tangent - cx);\n // Take the minor arc — the fillet never sweeps more than π.\n let delta = a2 - a1;\n while (delta > Math.PI) delta -= 2 * Math.PI;\n while (delta < -Math.PI) delta += 2 * Math.PI;\n\n const steps = Math.max(2, Math.ceil((Math.abs(delta) * radius) / 2));\n for (let s = 0; s <= steps; s++) {\n const a = a1 + delta * (s / steps);\n out.push({ x: cx + Math.cos(a) * radius, y: cy + Math.sin(a) * radius });\n }\n }\n return out;\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\nfunction signedArea(vertices: ReadonlyArray<Point>): number {\n let sum = 0;\n const n = vertices.length;\n for (let i = 0, j = n - 1; i < n; j = i++) {\n const a = vertices[j]!;\n const b = vertices[i]!;\n sum += (b.x - a.x) * (b.y + a.y);\n }\n // Shoelace's signed area is half this sum, with sign flipped for screen\n // coordinates (y grows down). Positive return = counter-clockwise in\n // screen space.\n return -sum * 0.5;\n}\n\nfunction unitNormal(a: Point, b: Point, ccw: boolean): Point {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy) || 1;\n // Inward-facing perpendicular: rotate the edge vector by ±90°.\n // CCW polygon (screen space): inward = rotate edge left → (-dy, dx).\n // CW polygon: inward = rotate edge right → (dy, -dx).\n return ccw ? { x: -dy / len, y: dx / len } : { x: dy / len, y: -dx / len };\n}\n","/**\n * The `tabbed-rect` (manila folder) silhouette, as pure maths.\n *\n * Every edge coordinate the outline, fold line, label box, bounds and hit test\n * are built from is resolved here, from the spec alone. It lives in `specs/`\n * rather than beside the renderer because the folder's footprint is a genuine\n * property of the *description* — a layout asking how big a container frame is,\n * an SVG export tracing it, and a headless hit-test all need the same answer\n * without a GPU (`docs/renderer-split-design.md` §4.5).\n *\n * Coordinates are **AABB-origin-relative**: `(0, 0)` is the top-left of the\n * full silhouette, which is the tab band's top-left when the tab is flush left.\n */\n\nimport type { Point, Rect } from '../geometry';\nimport type { TabbedRectSpec } from '../shape';\nimport { roundedPolygonOutline, type RoundedCorner } from './polygonMath';\n\n/** A tabbed-rect spec with its world position removed — geometry only. */\nexport type TabbedRectGeometrySpec = Omit<TabbedRectSpec, 'x' | 'y'>;\n\n/**\n * Every edge coordinate the silhouette, fold line and label box are built\n * from, resolved once against `inset`. `null` when the inset has collapsed the\n * geometry to nothing.\n *\n * The inset is applied analytically per edge rather than via a polygon offset:\n * the re-entrant shoulder corners make a bisector offset unstable, and all but\n * the slanted edges are axis-aligned, so the exact answer is one addition.\n */\nexport interface TabbedRectGeometry {\n left: number;\n right: number;\n bottom: number;\n /** Top of the tab — the silhouette's topmost edge. */\n tabTop: number;\n /** Where the tab meets the body; the fold line's y. */\n shoulder: number;\n /** Tab extent at its **base**, where it meets the body. */\n tabLeft: number;\n tabRight: number;\n /** Tab extent at its **top**, narrowed by the slant on whichever side leans. */\n tabTopLeft: number;\n tabTopRight: number;\n flushLeft: boolean;\n flushRight: boolean;\n /**\n * `true` when `spec.height <= 0` and the silhouette is the tab alone — the\n * closed folder. `left` / `right` / `bottom` describe the tab, and there is\n * no fold line. See {@link bodylessGeometryOf}.\n */\n bodyless: boolean;\n}\n\n/**\n * Resolved tab width: the declared {@link TabbedRectSpec.tabWidth}, falling\n * back to the body's width when it's left unset (a full-width tab).\n *\n * Clamped to the body while there is one — a tab can't outgrow the rectangle\n * it sits on. A bodyless folder's tab *is* the silhouette, so it sizes freely.\n */\nexport function tabbedRectTabWidth(spec: TabbedRectGeometrySpec): number {\n const declared = spec.tabWidth ?? spec.width;\n return spec.height <= 0 ? declared : Math.min(declared, spec.width);\n}\n\n/**\n * AABB of the folder.\n *\n * Bodyless (`height <= 0`): the tab *is* the silhouette, so it's also the\n * footprint — the declared body width describes a rectangle that isn't being\n * drawn. Everything positioned against the AABB (the label box, decorations,\n * edge anchors) therefore lands on the tab.\n */\nexport function tabbedRectBounds(spec: TabbedRectGeometrySpec): Rect {\n if (spec.height <= 0) {\n return { x: 0, y: 0, width: tabbedRectTabWidth(spec), height: spec.tabHeight };\n }\n return { x: 0, y: 0, width: spec.width, height: spec.tabHeight + spec.height };\n}\n\n/**\n * The folder, closed: body gone, tab kept. `width` is deliberately left alone —\n * {@link tabbedRectBounds} already reports the tab as the footprint once the\n * body is gone, so rewriting it would double-apply.\n */\nexport function collapsedTabbedRect(\n _spec: TabbedRectGeometrySpec,\n): Partial<TabbedRectSpec> {\n return { height: 0 };\n}\n\n/**\n * Size the tab to the content it carries — the title.\n *\n * The taper eats into the tab's top edge, so the slant's run is added on top of\n * the text budget; otherwise leaning the tab would push the title into the\n * taper. A centred tab leans on both sides.\n *\n * The clamp to `width` applies **only while there's a body**: a tab can't\n * outgrow the rectangle it sits on, but a closed folder is nothing *but* its\n * tab, so it sizes to the whole title rather than ellipsising it. Returns\n * nothing when {@link TabbedRectSpec.tabWidth} is pinned.\n */\nexport function fitTabbedRectToContent(\n spec: TabbedRectGeometrySpec,\n content: { readonly width: number; readonly height: number },\n): Partial<TabbedRectSpec> {\n if (spec.tabWidth !== undefined) return {};\n const pad = spec.tabPadding ?? 10;\n const slantSides = (spec.tabAlign ?? 'left') === 'center' ? 2 : 1;\n const fitted = content.width + 2 * pad + (spec.tabSkew ?? 0) * slantSides;\n return { tabWidth: spec.height <= 0 ? fitted : Math.min(spec.width, fitted) };\n}\n\n/** Uniform scale of every length the folder carries. */\nexport function scaleTabbedRect(\n spec: TabbedRectGeometrySpec,\n factor: number,\n): Partial<TabbedRectSpec> {\n return {\n width: spec.width * factor,\n height: spec.height * factor,\n tabHeight: spec.tabHeight * factor,\n ...(spec.tabWidth !== undefined ? { tabWidth: spec.tabWidth * factor } : {}),\n ...(spec.tabPadding !== undefined ? { tabPadding: spec.tabPadding * factor } : {}),\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius * factor } : {}),\n ...(spec.tabCornerRadius !== undefined\n ? { tabCornerRadius: spec.tabCornerRadius * factor }\n : {}),\n ...(spec.tabOffset !== undefined ? { tabOffset: spec.tabOffset * factor } : {}),\n ...(spec.tabSkew !== undefined ? { tabSkew: spec.tabSkew * factor } : {}),\n };\n}\n\n/**\n * Trace the folder silhouette into a polyline, inset by `inset` on every side.\n * Winds clockwise from the tab's top-left corner.\n *\n * The two re-entrant shoulders stay sharp; the convex corners take a fillet.\n * Rounding a shoulder reads as a dent rather than a fold.\n */\nexport function tabbedRectOutline(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): Point[] {\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo) return [];\n const { left, right, bottom, tabTop, shoulder, tabLeft, tabRight } = geo;\n\n const r = Math.max(0, (spec.cornerRadius ?? 0) - inset);\n const tr = Math.max(0, (spec.tabCornerRadius ?? spec.cornerRadius ?? 0) - inset);\n\n const corners: RoundedCorner[] = [];\n corners.push({ x: geo.tabTopLeft, y: tabTop, r: tr });\n corners.push({ x: geo.tabTopRight, y: tabTop, r: tr });\n // Closed folder — the tab's base closes the outline, so there are no\n // shoulders to turn and the body's fillet applies to its two bottom corners.\n if (geo.bodyless) {\n corners.push({ x: tabRight, y: bottom, r });\n corners.push({ x: tabLeft, y: bottom, r });\n return roundedPolygonOutline(corners);\n }\n if (geo.flushRight) {\n // Tab reaches the body's right edge — the tab's leaning (or vertical)\n // side runs straight into the body's side, one convex bend.\n corners.push({ x: right, y: shoulder, r });\n } else {\n corners.push({ x: tabRight, y: shoulder, r: 0 });\n corners.push({ x: right, y: shoulder, r });\n }\n corners.push({ x: right, y: bottom, r });\n corners.push({ x: left, y: bottom, r });\n if (!geo.flushLeft) {\n corners.push({ x: left, y: shoulder, r });\n corners.push({ x: tabLeft, y: shoulder, r: 0 });\n }\n return roundedPolygonOutline(corners);\n}\n\n/**\n * The tab's bottom border — the fold where the tab meets the body — as a\n * two-point segment, or `undefined` when `tabDivider` is off or the geometry\n * has collapsed. Spans the tab's **base**, so with a flush tab it starts on the\n * body's own edge and the two borders meet cleanly.\n */\nexport function tabbedRectFoldLine(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): [Point, Point] | undefined {\n if (spec.tabDivider === false) return undefined;\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo || geo.bodyless) return undefined;\n return [\n { x: geo.tabLeft, y: geo.shoulder },\n { x: geo.tabRight, y: geo.shoulder },\n ];\n}\n\n/**\n * The tab's **upright** box — its full-height portion, with the slant excluded\n * on whichever side is angled. This is where the folder's own label belongs:\n * the body interior belongs to whatever the frame contains, so a title centred\n * against this box stays put no matter how large the body grows.\n */\nexport function tabbedRectTabBox(\n spec: TabbedRectGeometrySpec,\n inset = 0,\n): Rect | undefined {\n const geo = tabbedRectGeometry(spec, inset);\n if (!geo) return undefined;\n return {\n x: geo.tabTopLeft,\n y: geo.tabTop,\n width: Math.max(0, geo.tabTopRight - geo.tabTopLeft),\n height: geo.shoulder - geo.tabTop,\n };\n}\n\n/** Resolve every edge coordinate of the folder against `inset`. */\nexport function tabbedRectGeometry(\n spec: TabbedRectGeometrySpec,\n inset: number,\n): TabbedRectGeometry | null {\n if (spec.height <= 0) return bodylessGeometryOf(spec, inset);\n const totalH = spec.tabHeight + spec.height;\n const left = inset;\n const right = spec.width - inset;\n const bottom = totalH - inset;\n const tabTop = inset;\n const shoulder = spec.tabHeight + inset;\n if (right <= left || bottom <= shoulder) return null;\n\n const x0 = tabXOf(spec);\n const tabLeft = Math.max(left, x0 + inset);\n const tabRight = Math.min(right, x0 + tabbedRectTabWidth(spec) - inset);\n if (tabRight <= tabLeft) return null;\n\n // The tab leans away from the side it hugs, so the angled edge is always\n // the one facing the rest of the frame. A centred tab leans both ways.\n const align = spec.tabAlign ?? 'left';\n const flushLeft = tabLeft - left < 1e-6;\n const flushRight = right - tabRight < 1e-6;\n // A side flush with the body's edge merges into it and can't lean.\n const slantLeft = (align === 'right' || align === 'center') && !flushLeft;\n const slantRight = (align === 'left' || align === 'center') && !flushRight;\n\n const sides = (slantLeft ? 1 : 0) + (slantRight ? 1 : 0);\n // Clamp so the slants can never eat more than half the tab — an over-large\n // skew degrades to a triangle-ish tab instead of inverting the top edge.\n const skew =\n sides === 0\n ? 0\n : Math.max(0, Math.min(spec.tabSkew ?? 0, (tabRight - tabLeft) / (2 * sides)));\n\n return {\n left,\n right,\n bottom,\n tabTop,\n shoulder,\n tabLeft,\n tabRight,\n tabTopLeft: tabLeft + (slantLeft ? skew : 0),\n tabTopRight: tabRight - (slantRight ? skew : 0),\n flushLeft,\n flushRight,\n bodyless: false,\n };\n}\n\n/**\n * Geometry for a **bodyless** spec (`height <= 0`) — the closed folder: the\n * silhouette is the tab and nothing else.\n *\n * Two things flip relative to {@link tabbedRectGeometry}'s main path, both\n * because the tab's base stops being an interior fold and becomes the outline's\n * bottom edge:\n *\n * - The inset pulls that edge **up** (`tabHeight − inset`) instead of pushing\n * the body's top edge down, so a decoration borrowing this silhouette insets\n * uniformly rather than growing downward.\n * - The tab may **lean on either side regardless of flushness**. In the main\n * path a side flush with the body's edge can't slant (it merges into it);\n * with no body there's nothing to merge with, so a tab spanning the full\n * declared width still gets its taper — which is what keeps a collapsed\n * frame reading as a folder rather than a plain rounded rect.\n */\nfunction bodylessGeometryOf(\n spec: TabbedRectGeometrySpec,\n inset: number,\n): TabbedRectGeometry | null {\n const tabTop = inset;\n const base = spec.tabHeight - inset;\n const tabLeft = inset;\n const tabRight = tabbedRectTabWidth(spec) - inset;\n if (base <= tabTop || tabRight <= tabLeft) return null;\n\n const align = spec.tabAlign ?? 'left';\n const slantLeft = align === 'right' || align === 'center';\n const slantRight = align === 'left' || align === 'center';\n const sides = (slantLeft ? 1 : 0) + (slantRight ? 1 : 0);\n const skew =\n sides === 0\n ? 0\n : Math.max(0, Math.min(spec.tabSkew ?? 0, (tabRight - tabLeft) / (2 * sides)));\n\n return {\n left: tabLeft,\n right: tabRight,\n bottom: base,\n tabTop,\n // No fold to sit on: the shoulder *is* the outline's bottom edge, which\n // keeps the label box (tabTop → shoulder) spanning the whole tab.\n shoulder: base,\n tabLeft,\n tabRight,\n tabTopLeft: tabLeft + (slantLeft ? skew : 0),\n tabTopRight: tabRight - (slantRight ? skew : 0),\n flushLeft: true,\n flushRight: true,\n bodyless: true,\n };\n}\n\n/** Left edge of the tab's base in shape-local space, resolved from `tabAlign`. */\nfunction tabXOf(spec: TabbedRectGeometrySpec): number {\n // Bodyless: the tab is the whole footprint, so it starts at the origin —\n // there's no body left for it to be aligned against or offset from.\n if (spec.height <= 0) return 0;\n const tabW = tabbedRectTabWidth(spec);\n const offset = spec.tabOffset ?? 0;\n switch (spec.tabAlign ?? 'left') {\n case 'center':\n return (spec.width - tabW) / 2;\n case 'right':\n return Math.max(0, spec.width - tabW - offset);\n default:\n return Math.min(offset, Math.max(0, spec.width - tabW));\n }\n}\n","/**\n * Per-kind spec measurement: **bounds**, **uniform scale**, **collapse** and\n * **fit-to-content**, as pure functions of the spec.\n *\n * These four used to live as `static` methods on the renderer-side shape\n * classes. They are not drawing — they are properties of the description, and\n * a layout, an exporter or a headless test needs them with no GPU in the\n * process. The shape classes now delegate here, so there is one implementation\n * per kind (`docs/renderer-split-design.md` §9, P4).\n *\n * Every function takes the spec **without** `x` / `y`: bounds are local, so the\n * world position is the caller's business.\n */\n\nimport type { Point, Rect } from '../geometry';\nimport type {\n ArcSpec,\n CircleSpec,\n CompositeRootSpec,\n CompositeSpec,\n EllipseSpec,\n PathSpec,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n StarSpec,\n} from '../shape';\nimport {\n polygonBounds,\n regularPolygonVertices,\n starVertices,\n} from './polygonMath';\n\n/** A spec of kind `K` with its world position removed — geometry only. */\nexport type LocalSpec<T> = Omit<T, 'x' | 'y'>;\n\nconst TAU = Math.PI * 2;\n\n// ─── circle ────────────────────────────────────────────────────────────────\n\nexport function boundsOfCircle(spec: LocalSpec<CircleSpec>): Rect {\n const r = spec.radius;\n return { x: -r, y: -r, width: r * 2, height: r * 2 };\n}\n\nexport function scaleCircle(\n spec: LocalSpec<CircleSpec>,\n factor: number,\n): Partial<CircleSpec> {\n return { radius: spec.radius * factor };\n}\n\n// ─── ellipse ───────────────────────────────────────────────────────────────\n\nexport function boundsOfEllipse(spec: LocalSpec<EllipseSpec>): Rect {\n return {\n x: -spec.radiusX,\n y: -spec.radiusY,\n width: spec.radiusX * 2,\n height: spec.radiusY * 2,\n };\n}\n\nexport function scaleEllipse(\n spec: LocalSpec<EllipseSpec>,\n factor: number,\n): Partial<EllipseSpec> {\n return { radiusX: spec.radiusX * factor, radiusY: spec.radiusY * factor };\n}\n\n// ─── rect ──────────────────────────────────────────────────────────────────\n\n/** Anchored top-left, so the local box starts at the origin. */\nexport function boundsOfRect(spec: LocalSpec<RectSpec>): Rect {\n return { x: 0, y: 0, width: spec.width, height: spec.height };\n}\n\nexport function scaleRect(\n spec: LocalSpec<RectSpec>,\n factor: number,\n): Partial<RectSpec> {\n return {\n width: spec.width * factor,\n height: spec.height * factor,\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius * factor } : {}),\n };\n}\n\n// ─── polygon ───────────────────────────────────────────────────────────────\n\nexport function boundsOfPolygon(spec: LocalSpec<PolygonSpec>): Rect {\n return polygonBounds(spec.vertices);\n}\n\nexport function scalePolygon(\n spec: LocalSpec<PolygonSpec>,\n factor: number,\n): Partial<PolygonSpec> {\n return { vertices: spec.vertices.map((v) => ({ x: v.x * factor, y: v.y * factor })) };\n}\n\n// ─── regular-polygon ───────────────────────────────────────────────────────\n\n/** The n-gon's vertices at its authored size, centred on the origin. */\nexport function verticesOfRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n): Point[] {\n return regularPolygonVertices(spec.sides, spec.radius, spec.rotation ?? 0);\n}\n\nexport function boundsOfRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n): Rect {\n return polygonBounds(verticesOfRegularPolygon(spec));\n}\n\nexport function scaleRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n factor: number,\n): Partial<RegularPolygonSpec> {\n return { radius: spec.radius * factor };\n}\n\n// ─── star ──────────────────────────────────────────────────────────────────\n\n/** The star's alternating outer / inner vertices, centred on the origin. */\nexport function verticesOfStar(spec: LocalSpec<StarSpec>): Point[] {\n return starVertices(spec.points, spec.innerRadius, spec.outerRadius, spec.rotation ?? 0);\n}\n\nexport function boundsOfStar(spec: LocalSpec<StarSpec>): Rect {\n return polygonBounds(verticesOfStar(spec));\n}\n\nexport function scaleStar(\n spec: LocalSpec<StarSpec>,\n factor: number,\n): Partial<StarSpec> {\n return {\n innerRadius: spec.innerRadius * factor,\n outerRadius: spec.outerRadius * factor,\n };\n}\n\n// ─── arc ───────────────────────────────────────────────────────────────────\n\n/**\n * Axis-aligned bounding box for an annular sector. The extreme points are\n * either on the four sector corners (a0/inner, a0/outer, a1/inner, a1/outer)\n * or at the cardinal angles (0, π/2, π, 3π/2) on the outer radius if those\n * angles fall inside the sweep — those produce the (±outerR, 0) / (0, ±outerR)\n * extents.\n */\nexport function boundsOfArc(spec: LocalSpec<ArcSpec>): Rect {\n const { innerR, outerR, startAngle: a0, endAngle: a1 } = spec;\n if (a1 <= a0 || outerR <= 0) return { x: 0, y: 0, width: 0, height: 0 };\n\n // Corners always contribute.\n const corners: Point[] = [\n { x: Math.cos(a0) * innerR, y: Math.sin(a0) * innerR },\n { x: Math.cos(a0) * outerR, y: Math.sin(a0) * outerR },\n { x: Math.cos(a1) * innerR, y: Math.sin(a1) * innerR },\n { x: Math.cos(a1) * outerR, y: Math.sin(a1) * outerR },\n ];\n\n // Add the cardinal-angle extents on the outer radius if the sweep crosses\n // them. Normalise everything into a single circle's worth of revolutions so\n // sweeps that wrap past 2π still pick up all four cardinals.\n const sweep = a1 - a0;\n for (const k of [0, 1, 2, 3]) {\n const cardinal = (k * Math.PI) / 2;\n // First multiple of 2π that lands `cardinal` at or after a0.\n let n = Math.ceil((a0 - cardinal) / TAU);\n if (cardinal + n * TAU < a0) n++;\n const angle = cardinal + n * TAU;\n if (angle <= a1 || sweep >= TAU) {\n corners.push({ x: Math.cos(angle) * outerR, y: Math.sin(angle) * outerR });\n }\n }\n\n return polygonBounds(corners);\n}\n\nexport function scaleArc(\n spec: LocalSpec<ArcSpec>,\n factor: number,\n): Partial<ArcSpec> {\n return { innerR: spec.innerR * factor, outerR: spec.outerR * factor };\n}\n\n// ─── path ──────────────────────────────────────────────────────────────────\n\nexport function boundsOfPath(spec: LocalSpec<PathSpec>): Rect {\n return polygonBounds(spec.points);\n}\n\nexport function scalePath(\n spec: LocalSpec<PathSpec>,\n factor: number,\n): Partial<PathSpec> {\n return { points: spec.points.map((p) => ({ x: p.x * factor, y: p.y * factor })) };\n}\n\n// ─── composite ─────────────────────────────────────────────────────────────\n\n/**\n * The composite's silhouette fills its declared box (like a rect), whatever\n * root shape it borrows — the root is centred and sized to that box. Layouts\n * (ELK et al.) read node dimensions through this; without it every card falls\n * back to the layout's default size and they overlap.\n */\nexport function boundsOfComposite(\n spec: Pick<CompositeSpec, 'width' | 'height'>,\n): Rect {\n return { x: 0, y: 0, width: spec.width, height: spec.height };\n}\n\n/**\n * The composite's effective root spec: the explicit\n * {@link CompositeSpec.root}, or the default rounded rect built from\n * `cornerRadius` + the inherited `fill` / `stroke`.\n */\nexport function resolveCompositeRoot(spec: CompositeSpec): CompositeRootSpec {\n if (spec.root) return spec.root;\n return {\n kind: 'rect',\n x: 0,\n y: 0,\n width: spec.width,\n height: spec.height,\n ...(spec.cornerRadius !== undefined ? { cornerRadius: spec.cornerRadius } : {}),\n ...(spec.fill !== undefined ? { fill: spec.fill } : {}),\n ...(spec.stroke !== undefined ? { stroke: spec.stroke } : {}),\n };\n}\n\n/** Local bounds of whichever shape a composite borrows for its silhouette. */\nexport function boundsOfCompositeRoot(root: CompositeRootSpec): Rect {\n switch (root.kind) {\n case 'circle':\n return boundsOfCircle(root);\n case 'ellipse':\n return boundsOfEllipse(root);\n case 'polygon':\n return boundsOfPolygon(root);\n case 'regular-polygon':\n return boundsOfRegularPolygon(root);\n case 'star':\n return boundsOfStar(root);\n case 'arc':\n return boundsOfArc(root);\n default:\n return boundsOfRect(root);\n }\n}\n\n/**\n * Translation from the composite's top-left origin to the borrowed root's own\n * local origin — the offset that centres the root in the `width × height` box.\n *\n * Origin-agnostic by construction: it works off the root's *bounding-box*\n * centre, so a rect (top-left origin) and a circle (centred origin) both land\n * in the middle of the card. The renderer applies exactly this before tracing\n * the root, which is why hit-testing has to apply it too.\n */\nexport function compositeRootOffset(spec: CompositeSpec): Point {\n const b = boundsOfCompositeRoot(resolveCompositeRoot(spec));\n return {\n x: spec.width / 2 - (b.x + b.width / 2),\n y: spec.height / 2 - (b.y + b.height / 2),\n };\n}\n","/**\n * Pure geometric containment, per spec kind — the engine's hit-test narrow\n * phase with no GPU in it.\n *\n * ## Why this exists\n *\n * Picking used to ask the backend: `bodyGfx.containsPoint(...)`, i.e. pixi\n * walked the instructions it had recorded while painting. That made the answer\n * depend on a display object existing, so picking could not be tested headlessly\n * and would have left the engine with the renderer under the P6 extraction\n * (`docs/renderer-split-design.md` §5 — \"geometry answers must not require the\n * backend\"). Here the answer comes from the spec alone, so every backend agrees\n * by construction.\n *\n * ## Matching pixi\n *\n * `Graphics.containsPoint` is a **union over painted instructions**: a `fill`\n * instruction answers `shape.contains`, a `stroke` instruction answers\n * `shape.strokeContains`. Two consequences are reproduced here deliberately:\n *\n * 1. **A shape with no silhouette fill is hollow.** No fill was painted, so only\n * the stroke band answers `true` — clicking the middle of an outline-only\n * contour misses it, exactly as it does today.\n * 2. **The stroke widens the region by its alignment split**: `'center'`\n * (default) puts half the width outside and half inside, `'outside'` puts all\n * of it outside, `'inside'` all of it inside. That mirrors pixi's\n * `outerWidth = (1 - alignment) * width`.\n *\n * Coordinates are **shape-local** — `(0, 0)` is the shape's own origin (centre\n * for circle / ellipse / polygon / star / arc, top-left for rect / tabbed-rect /\n * composite), i.e. the caller has already subtracted `spec.x` / `spec.y` and\n * divided out any renderer-applied scale.\n */\n\nimport type {\n ArcSpec,\n BaseShapeSpec,\n CircleSpec,\n CompositeRootSpec,\n CompositeSpec,\n EllipseSpec,\n PathSpec,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n StarSpec,\n TabbedRectSpec,\n} from '../shape';\nimport { hasSilhouetteFill, type ShapeStroke } from '../style';\nimport {\n compositeRootOffset,\n resolveCompositeRoot,\n verticesOfRegularPolygon,\n verticesOfStar,\n type LocalSpec,\n} from './bounds';\nimport {\n distanceToSegmentSq,\n polygonContainsInflated,\n} from './polygonMath';\nimport { tabbedRectOutline } from './tabbedRect';\n\nconst TAU = Math.PI * 2;\n\n/**\n * How far a stroke pushes the hit region past the silhouette (`outer`) and how\n * far it reaches back inside it (`inner`).\n *\n * Mirrors pixi's split: `outer = (1 - alignment) * width`, `inner = width -\n * outer`, with the engine's `'inside' | 'center' | 'outside'` mapping to\n * pixi's `1 | 0.5 | 0` alignment. A missing or non-positive width paints\n * nothing, so it widens nothing.\n */\nexport function strokeBandOf(stroke: ShapeStroke | undefined): {\n outer: number;\n inner: number;\n} {\n const width = stroke?.width ?? (stroke ? 1 : 0);\n if (!stroke || width <= 0) return { outer: 0, inner: 0 };\n const alignment = stroke.alignment === 'inside' ? 1 : stroke.alignment === 'outside' ? 0 : 0.5;\n const outer = (1 - alignment) * width;\n return { outer, inner: width - outer };\n}\n\n// ─── Per-kind containment ──────────────────────────────────────────────────\n//\n// Each takes a `pad`: positive grows the silhouette, negative erodes it. That\n// one parameter expresses both halves of the stroke band, so the fill-less\n// \"hollow\" case is `grown && !eroded` rather than a second family of functions.\n\nexport function containsCircle(\n spec: LocalSpec<CircleSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const r = spec.radius + pad;\n if (r <= 0) return false;\n return localX * localX + localY * localY <= r * r;\n}\n\nexport function containsEllipse(\n spec: LocalSpec<EllipseSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n // Padding an ellipse by its radii is not a true parallel offset (the exact\n // offset curve isn't an ellipse), but it is precisely what pixi's\n // `Ellipse.strokeContains` does, so picking stays consistent with what the\n // user sees highlighted.\n const rx = spec.radiusX + pad;\n const ry = spec.radiusY + pad;\n if (rx <= 0 || ry <= 0) return false;\n const nx = localX / rx;\n const ny = localY / ry;\n return nx * nx + ny * ny <= 1;\n}\n\nexport function containsRect(\n spec: LocalSpec<RectSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const w = spec.width + pad * 2;\n const h = spec.height + pad * 2;\n if (w <= 0 || h <= 0) return false;\n const left = -pad;\n const top = -pad;\n if (localX < left || localX > left + w || localY < top || localY > top + h) return false;\n\n const r = Math.min(Math.max(0, (spec.cornerRadius ?? 0) + pad), w / 2, h / 2);\n if (r <= 0) return true;\n // Outside the four corner discs = outside the rounded rect. Clamping the\n // point into the inner \"core\" rectangle finds the nearest corner centre in\n // one step (pixi's `RoundedRectangle.contains` does the same).\n const cx = clamp(localX, left + r, left + w - r);\n const cy = clamp(localY, top + r, top + h - r);\n const dx = localX - cx;\n const dy = localY - cy;\n return dx * dx + dy * dy <= r * r;\n}\n\nexport function containsPolygon(\n spec: LocalSpec<PolygonSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, spec.vertices, pad);\n}\n\nexport function containsRegularPolygon(\n spec: LocalSpec<RegularPolygonSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, verticesOfRegularPolygon(spec), pad);\n}\n\nexport function containsStar(\n spec: LocalSpec<StarSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n return polygonContainsInflated(localX, localY, verticesOfStar(spec), pad);\n}\n\nexport function containsTabbedRect(\n spec: LocalSpec<TabbedRectSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n // The outline is already densified through its fillets, so the generic\n // polygon test covers the rounded corners and the re-entrant shoulders alike.\n // The fold line is interior geometry and never part of the silhouette.\n return polygonContainsInflated(localX, localY, tabbedRectOutline(spec, 0), pad);\n}\n\n/**\n * An open path is tested against its **run**, not a phantom closed area: only a\n * `closed` (or `smooth`, which implies closed) path has an interior, matching\n * the paint path, which fills only when closed. So an unfilled contour line\n * answers `true` along its stroke and nowhere else.\n *\n * `smooth` paths are approximated by the control polygon rather than the\n * quadratic spline it generates. The spline passes through the segment\n * midpoints and bulges toward each control point, so the two differ by at most\n * half a segment's sagitta — a fraction of a pixel at contour densities.\n */\nexport function containsPath(\n spec: LocalSpec<PathSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const closed = spec.closed === true || spec.smooth === true;\n return polygonContainsInflated(localX, localY, spec.points, pad, closed);\n}\n\n/**\n * Annular sector, tested analytically rather than against a sampled outline:\n * radius inside `[innerR, outerR]` and angle inside the sweep, each relaxed by\n * `pad`. Outside the sweep the nearest point of the sector lies on one of the\n * two straight radial edges, so the padded test falls back to a distance check\n * against those two segments.\n */\nexport function containsArc(\n spec: LocalSpec<ArcSpec>,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const { startAngle: a0, endAngle: a1 } = spec;\n const innerR = Math.max(0, spec.innerR - pad);\n const outerR = spec.outerR + pad;\n if (a1 <= a0 || outerR <= 0) return false;\n\n const rSq = localX * localX + localY * localY;\n const inRadial = rSq >= innerR * innerR && rSq <= outerR * outerR;\n const inSweep = a1 - a0 >= TAU || angleWithin(Math.atan2(localY, localX), a0, a1);\n if (inSweep && inRadial) {\n if (pad >= 0) return true;\n // Eroding: also stay clear of the two radial edges, or the band along them\n // would be reported as interior.\n return distanceToRadialEdgesSq(spec, localX, localY) > pad * pad;\n }\n if (pad <= 0 || a1 - a0 >= TAU) return false;\n // Outside the sweep but possibly within `pad` of a radial edge.\n return distanceToRadialEdgesSq(spec, localX, localY) <= pad * pad;\n}\n\n/**\n * A composite is its **root silhouette** (centred in the card box) plus every\n * geometric part painted on top of it. Parts are included because they are\n * painted into the same `Graphics` the backend hit-tests today: a part that\n * pokes outside the root — an accent bar on an unclipped card — is clickable,\n * and stays clickable here.\n *\n * `label` parts are excluded: they are mounted as text children, not painted\n * into the body, so they never contributed a hit region.\n */\nexport function containsComposite(\n spec: CompositeSpec,\n localX: number,\n localY: number,\n pad = 0,\n): boolean {\n const off = compositeRootOffset(spec);\n const root = resolveCompositeRoot(spec);\n if (containsRootSpec(root, localX - off.x, localY - off.y, pad)) return true;\n\n for (const p of spec.parts) {\n if (p.part === 'rect') {\n if (p.fill === undefined && !p.stroke) continue;\n const box: LocalSpec<RectSpec> = {\n kind: 'rect',\n width: p.width,\n height: p.height,\n ...(p.cornerRadius !== undefined ? { cornerRadius: p.cornerRadius } : {}),\n };\n const half = partHalfStroke(p.stroke);\n if (\n withHollowRule(\n (q) => containsRect(box, localX - p.x, localY - p.y, q),\n p.fill !== undefined,\n pad + half,\n half,\n )\n ) {\n return true;\n }\n } else if (p.part === 'circle') {\n if (p.fill === undefined && !p.stroke) continue;\n const disc: LocalSpec<CircleSpec> = { kind: 'circle', radius: p.radius };\n const half = partHalfStroke(p.stroke);\n if (\n withHollowRule(\n (q) => containsCircle(disc, localX - p.x, localY - p.y, q),\n p.fill !== undefined,\n pad + half,\n half,\n )\n ) {\n return true;\n }\n } else if (p.part === 'line') {\n // Stroke-only geometry: a band of half the stroke width around the run.\n const tol = pad + partHalfStroke(p.stroke);\n if (tol > 0 && distanceToSegmentSq(localX, localY, p.x, p.y, p.x2, p.y2) <= tol * tol) {\n return true;\n }\n } else if (p.part === 'icon' && p.background) {\n // The chip behind the glyph is a filled rect; the glyph itself is a child.\n const chip: LocalSpec<RectSpec> = {\n kind: 'rect',\n width: p.size,\n height: p.size,\n ...(p.background.cornerRadius !== undefined\n ? { cornerRadius: p.background.cornerRadius }\n : {}),\n };\n if (containsRect(chip, localX - p.x, localY - p.y, pad)) return true;\n }\n }\n return false;\n}\n\n// ─── Dispatcher ────────────────────────────────────────────────────────────\n\n/**\n * Does `(localX, localY)` fall inside the region this spec paints?\n *\n * `strokeTolerance` overrides the widening the spec's own stroke would imply\n * (both inward and outward). Omit it and the band is derived from\n * `spec.stroke` — width and alignment — which is what the renderer wants: the\n * hit region then tracks whatever the shape actually draws.\n *\n * Returns `undefined` for a kind this module doesn't know. That is not a\n * failure: `registerShape` admits third-party kinds, and the caller falls back\n * to asking the instance (`IShape.getHitArea`). Distinguishing \"not contained\"\n * from \"cannot answer\" is the whole point of the `boolean | undefined` return.\n */\nexport function containsSpec(\n spec: BaseShapeSpec,\n localX: number,\n localY: number,\n strokeTolerance?: number,\n): boolean | undefined {\n const fn = CONTAINS[spec.kind];\n if (!fn) return undefined;\n\n // A composite resolves fill and stroke per borrowed root and per part — its\n // own `stroke` is already folded into the default root — so it owns the\n // hollow rule internally and takes only the caller's extra padding.\n if (spec.kind === 'composite') return fn(spec as never, localX, localY, strokeTolerance ?? 0);\n\n const band =\n strokeTolerance !== undefined\n ? { outer: strokeTolerance, inner: strokeTolerance }\n : strokeBandOf(spec.stroke);\n\n return withHollowRule(\n (pad) => fn(spec as never, localX, localY, pad),\n hasSilhouetteFill(spec.fill),\n band.outer,\n band.inner,\n );\n}\n\n/**\n * Kinds this module can answer for. Keyed by the same string the shape registry\n * uses, so a kind is answerable here exactly when the engine ships geometry for\n * it — third-party kinds are absent by design (see {@link containsSpec}).\n */\nconst CONTAINS: Record<\n string,\n (spec: never, x: number, y: number, pad: number) => boolean\n> = {\n circle: containsCircle as never,\n ellipse: containsEllipse as never,\n rect: containsRect as never,\n 'tabbed-rect': containsTabbedRect as never,\n polygon: containsPolygon as never,\n 'regular-polygon': containsRegularPolygon as never,\n star: containsStar as never,\n arc: containsArc as never,\n path: containsPath as never,\n composite: containsComposite as never,\n};\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\n/** Containment against whichever shape a composite borrows for its silhouette. */\nfunction containsRootSpec(\n root: CompositeRootSpec,\n x: number,\n y: number,\n pad: number,\n): boolean {\n const band = strokeBandOf(root.stroke);\n const test = (p: number): boolean => {\n switch (root.kind) {\n case 'circle':\n return containsCircle(root, x, y, p);\n case 'ellipse':\n return containsEllipse(root, x, y, p);\n case 'polygon':\n return containsPolygon(root, x, y, p);\n case 'regular-polygon':\n return containsRegularPolygon(root, x, y, p);\n case 'star':\n return containsStar(root, x, y, p);\n case 'arc':\n return containsArc(root, x, y, p);\n default:\n return containsRect(root, x, y, p);\n }\n };\n return withHollowRule(test, hasSilhouetteFill(root.fill), pad + band.outer, band.inner);\n}\n\n/**\n * Apply the fill-less **hollow** rule to a padded containment test: filled\n * geometry answers for its whole grown silhouette; unfilled geometry answers\n * only inside the stroke band, i.e. grown-by-`outer` minus eroded-by-`inner`.\n */\nfunction withHollowRule(\n test: (pad: number) => boolean,\n filled: boolean,\n outer: number,\n inner: number,\n): boolean {\n if (filled) return test(outer);\n if (outer <= 0 && inner <= 0) return false;\n return test(outer) && !test(-inner);\n}\n\n/**\n * Half-width of a composite part's stroke — the distance it reaches past the\n * traced path. Parts are stroked with the backend's default centred alignment,\n * so half the width falls outside; an absent stroke reaches nowhere.\n */\nfunction partHalfStroke(stroke: { readonly width?: number } | undefined): number {\n if (!stroke) return 0;\n return Math.max(0, stroke.width ?? 1) / 2;\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n return v < lo ? lo : v > hi ? hi : v;\n}\n\n/** Is `theta` inside `[a0, a1]`, allowing for sweeps that wrap past 2π? */\nfunction angleWithin(theta: number, a0: number, a1: number): boolean {\n // Bring θ into the same revolution as a0 so the comparison is unambiguous\n // across the 2π wrap (e.g. a sweep from 3π/2 to 5π/2 hitting θ ≈ 0.1).\n let n = Math.ceil((a0 - theta) / TAU);\n if (theta + n * TAU < a0) n++;\n const t = theta + n * TAU;\n return t >= a0 && t <= a1;\n}\n\n/** Squared distance to the sector's two straight radial edges. */\nfunction distanceToRadialEdgesSq(\n spec: LocalSpec<ArcSpec>,\n x: number,\n y: number,\n): number {\n const edge = (a: number): number => {\n const c = Math.cos(a);\n const s = Math.sin(a);\n return distanceToSegmentSq(\n x,\n y,\n c * spec.innerR,\n s * spec.innerR,\n c * spec.outerR,\n s * spec.outerR,\n );\n };\n return Math.min(edge(spec.startAngle), edge(spec.endAngle));\n}\n","/**\n * Spec geometry — bounds, scale, collapse, fit and containment, computed from a\n * spec and nothing else.\n *\n * This is the half of the old shape classes that was never really drawing: the\n * `static boundsOf` / `scaleSpec` / `collapsedOf` / `fitToContent` methods, plus\n * the new `contains`. They live here so a layout can size a node, an exporter\n * can trace a silhouette and a test can pick a shape with no backend mounted —\n * and so they stay in `@invana/canvas` when the pixi renderer is extracted\n * (`docs/renderer-split-design.md` §9, P4).\n *\n * The renderer-side shape classes now delegate to these functions; the maths\n * exists once.\n */\n\nexport * from './polygonMath';\nexport * from './tabbedRect';\nexport * from './bounds';\nexport * from './contains';\n\nimport type { Rect } from '../geometry';\nimport type { BaseShapeSpec } from '../shape';\nimport {\n boundsOfArc,\n boundsOfCircle,\n boundsOfComposite,\n boundsOfEllipse,\n boundsOfPath,\n boundsOfPolygon,\n boundsOfRect,\n boundsOfRegularPolygon,\n boundsOfStar,\n scaleArc,\n scaleCircle,\n scaleEllipse,\n scalePath,\n scalePolygon,\n scaleRect,\n scaleRegularPolygon,\n scaleStar,\n} from './bounds';\nimport {\n collapsedTabbedRect,\n fitTabbedRectToContent,\n scaleTabbedRect,\n tabbedRectBounds,\n} from './tabbedRect';\n\n/**\n * Local bounds of any built-in spec kind, or `undefined` for a kind this module\n * doesn't know.\n *\n * `undefined` is a real answer, not a failure: `registerShape` admits\n * third-party kinds, so callers that must cover those ask the registry (which\n * consults the class's `static boundsOf`) and fall back to a default box.\n */\nexport function boundsOfSpec(spec: BaseShapeSpec): Rect | undefined {\n switch (spec.kind) {\n case 'circle':\n return boundsOfCircle(spec as never);\n case 'ellipse':\n return boundsOfEllipse(spec as never);\n case 'rect':\n return boundsOfRect(spec as never);\n case 'tabbed-rect':\n return tabbedRectBounds(spec as never);\n case 'polygon':\n return boundsOfPolygon(spec as never);\n case 'regular-polygon':\n return boundsOfRegularPolygon(spec as never);\n case 'star':\n return boundsOfStar(spec as never);\n case 'arc':\n return boundsOfArc(spec as never);\n case 'path':\n return boundsOfPath(spec as never);\n case 'composite':\n return boundsOfComposite(spec as never);\n default:\n return undefined;\n }\n}\n\n/**\n * Uniformly scale a spec's geometry by `factor`, as a partial patch to merge\n * onto it. Paint is untouched — only lengths.\n *\n * The contract: `boundsOfSpec(scaleSpec(spec, k)).width === boundsOfSpec(spec).width * k`\n * (likewise height). `undefined` for kinds with no meaningful uniform scale\n * (`composite` sizes off its box and its parts, so scaling it needs the layer's\n * intent, not a geometric rule).\n */\nexport function scaleSpec(\n spec: BaseShapeSpec,\n factor: number,\n): Record<string, unknown> | undefined {\n switch (spec.kind) {\n case 'circle':\n return scaleCircle(spec as never, factor);\n case 'ellipse':\n return scaleEllipse(spec as never, factor);\n case 'rect':\n return scaleRect(spec as never, factor);\n case 'tabbed-rect':\n return scaleTabbedRect(spec as never, factor);\n case 'polygon':\n return scalePolygon(spec as never, factor);\n case 'regular-polygon':\n return scaleRegularPolygon(spec as never, factor);\n case 'star':\n return scaleStar(spec as never, factor);\n case 'arc':\n return scaleArc(spec as never, factor);\n case 'path':\n return scalePath(spec as never, factor);\n default:\n return undefined;\n }\n}\n\n/**\n * The spec \"as small as it goes\" — what a collapsed container renders as.\n * Purely geometric: the kind decides what collapsing means to it. `undefined`\n * when the kind has no collapsed form, and callers then keep the spec as is.\n */\nexport function collapsedSpec(\n spec: BaseShapeSpec,\n): Record<string, unknown> | undefined {\n return spec.kind === 'tabbed-rect' ? collapsedTabbedRect(spec as never) : undefined;\n}\n\n/**\n * Size the spec's geometry to a measured block of content (a title, a label).\n * The caller measures — text metrics belong to the backend — and the kind turns\n * that size into geometry. `undefined` when the kind doesn't size to content.\n */\nexport function fitSpecToContent(\n spec: BaseShapeSpec,\n content: { readonly width: number; readonly height: number },\n): Record<string, unknown> | undefined {\n return spec.kind === 'tabbed-rect'\n ? fitTabbedRectToContent(spec as never, content)\n : undefined;\n}\n","/**\n * Flush scheduling for the **non-reactive** data stores ({@link DataStore} /\n * {@link LayerData}). A write marks a dirty delta and *arms* a deferred flush; the\n * mode decides **when** that flush fires. The store never notifies per write — it\n * coalesces a whole batch into **one** flush (see `docs/canvas-store-data-event-flow.md` §2).\n */\n\n/** When a coalesced data flush fires. */\nexport type FlushMode =\n /** Next animation frame (browser). Falls back to `microtask` where no rAF exists (node/tests). */\n | 'frame'\n /** End of the current JS task — the kernel default (no DOM assumption, deterministic). */\n | 'microtask'\n /** Never auto-fires; the owner (e.g. the engine's single rAF loop) calls `flush()`. */\n | 'manual';\n\n// Feature-detect rAF so the renderer-free kernel makes no hard DOM assumption.\nconst raf: typeof requestAnimationFrame | undefined =\n typeof requestAnimationFrame === 'function' ? requestAnimationFrame : undefined;\nconst caf: typeof cancelAnimationFrame | undefined =\n typeof cancelAnimationFrame === 'function' ? cancelAnimationFrame : undefined;\n\n/**\n * Arm a deferred flush per `mode`, returning a **cancel** function (a no-op once the\n * callback has run or for modes that can't be cancelled). `'manual'` arms nothing.\n */\nexport function scheduleFlush(mode: FlushMode, cb: () => void): () => void {\n if (mode === 'manual') return () => {};\n if (mode === 'frame' && raf && caf) {\n const handle = raf(() => cb());\n return () => caf(handle);\n }\n // microtask — and the `frame` fallback when no rAF is present (node / tests)\n let cancelled = false;\n queueMicrotask(() => {\n if (!cancelled) cb();\n });\n return () => {\n cancelled = true;\n };\n}\n","/**\n * `SpecStore` — the durable **visual description** of one layer's elements.\n *\n * A spec says *what to draw* (`{ kind: 'circle', radius, fill, plane }`) and\n * contains no drawing code. Layers resolve style + templates into specs and\n * publish them here; renderers subscribe and project. That inversion is the\n * point: two backends reading one description cannot disagree about intent, and\n * the description is serialisable, diffable and testable without a GPU.\n *\n * **Generic over `T`, though it no longer has to be.** The vocabulary now sits\n * beside this file (`./index`), so this store *could* name its own element types.\n * It stays generic deliberately: nothing needs the narrowing, and a concrete\n * signature would ripple through `SpecProjector` and `GraphLayer` for no new\n * capability. The engine instantiates it as\n * `SpecStore<BaseShapeSpec | BaseConnectorSpec>`.\n *\n * **What does *not* live here:** positions. Those stay in {@link LayerData}'s\n * typed arrays on the machine-rate path — a drag frame moves nodes without\n * touching a single spec. And transient visuals (lasso, brush, drag ghosts) never\n * enter the store at all; they are drawn through the renderer's overlay device,\n * so gesture noise stays out of history, undo and saved files.\n *\n * Writes mark a dirty delta and arm a coalesced flush — the same contract as\n * {@link LayerData}, so both channels settle in the same frame.\n *\n * See `docs/renderer-split-design.md` §2 (specs as state) and §4.2b (the channel).\n */\n\nimport { scheduleFlush, type FlushMode } from '../state/data/flush';\n\n/**\n * One coalesced batch of spec changes. Ids only — the receiver reads the specs\n * it cares about, so a flush stays O(dirty) regardless of collection size.\n */\nexport interface SpecFlush {\n readonly added: readonly string[];\n readonly changed: readonly string[];\n readonly removed: readonly string[];\n /** Monotonic, per store. Lets a consumer detect a missed batch. */\n readonly version: number;\n}\n\nexport class SpecStore<T extends object = object> {\n private readonly specs = new Map<string, T>();\n private readonly added = new Set<string>();\n private readonly changed = new Set<string>();\n private readonly removed = new Set<string>();\n private readonly listeners = new Set<(e: SpecFlush) => void>();\n private version = 0;\n private scheduled = false;\n private flushMode: FlushMode = 'microtask';\n private cancel: (() => void) | undefined;\n\n // ── Reads ──────────────────────────────────────────────────────────────────\n\n get(id: string): T | undefined {\n return this.specs.get(id);\n }\n\n has(id: string): boolean {\n return this.specs.has(id);\n }\n\n get size(): number {\n return this.specs.size;\n }\n\n ids(): IterableIterator<string> {\n return this.specs.keys();\n }\n\n entries(): IterableIterator<[string, T]> {\n return this.specs.entries();\n }\n\n // ── Writes ─────────────────────────────────────────────────────────────────\n\n /** Publish (or replace) the spec for `id`. */\n set(id: string, spec: T): void {\n const existed = this.specs.has(id);\n this.specs.set(id, spec);\n if (existed) {\n this.removed.delete(id);\n // An id added and then re-set before the flush is still just \"added\".\n if (!this.added.has(id)) this.changed.add(id);\n } else {\n this.added.add(id);\n this.removed.delete(id);\n }\n this.schedule();\n }\n\n /**\n * Shallow-merge `partial` over the stored spec. Returns `false` when `id` is\n * unknown, so a caller can fall back to {@link set} with a full spec.\n */\n patch(id: string, partial: Partial<T>): boolean {\n const current = this.specs.get(id);\n if (!current) return false;\n this.specs.set(id, { ...current, ...partial });\n if (!this.added.has(id)) this.changed.add(id);\n this.schedule();\n return true;\n }\n\n delete(id: string): void {\n if (!this.specs.delete(id)) return;\n this.changed.delete(id);\n // Added-then-removed before a flush is a net no-op: the receiver never saw it.\n if (!this.added.delete(id)) this.removed.add(id);\n this.schedule();\n }\n\n /** Drop every spec. Emits one flush listing all ids as removed. */\n clear(): void {\n for (const id of this.specs.keys()) {\n if (!this.added.delete(id)) this.removed.add(id);\n }\n this.specs.clear();\n this.changed.clear();\n this.schedule();\n }\n\n // ── Flush ──────────────────────────────────────────────────────────────────\n\n onFlush(listener: (e: SpecFlush) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Choose **when** a coalesced flush fires. `'manual'` disarms auto-flush so the\n * engine's single rAF drives it — which is how the renderer stays on one clock.\n */\n setFlushMode(mode: FlushMode): void {\n this.flushMode = mode;\n if (mode === 'manual' && this.scheduled) {\n this.cancel?.();\n this.scheduled = false;\n }\n }\n\n /** Emit the pending delta, if any. Safe to call when nothing is dirty. */\n flush(): void {\n this.scheduled = false;\n if (this.added.size === 0 && this.changed.size === 0 && this.removed.size === 0) return;\n const event: SpecFlush = {\n added: [...this.added],\n changed: [...this.changed],\n removed: [...this.removed],\n version: ++this.version,\n };\n this.added.clear();\n this.changed.clear();\n this.removed.clear();\n for (const listener of this.listeners) listener(event);\n }\n\n private schedule(): void {\n if (this.scheduled || this.flushMode === 'manual') return;\n this.scheduled = true;\n this.cancel = scheduleFlush(this.flushMode, () => this.flush());\n }\n}\n","/**\n * `ICameraBinding` with no backend behind it.\n *\n * The projection math mirrors the engine's coordinate model exactly\n * (`screen = world * zoom + offset`), so camera semantics — clamping, anchored\n * zoom, fit, the bus and store sync — are exercisable with no GPU.\n * `emitTransformChange` simulates a backend-driven gesture (a wheel tick, a\n * momentum glide), the one path `Camera` cannot trigger itself.\n *\n * Shipped rather than test-only: §7 keeps a headless backend deliberately, so\n * consumers can test layouts, picking and projection without a renderer.\n */\n\nimport type { Point, Rect } from '../specs/geom';\nimport type {\n CameraChangeKind,\n CameraInputConfig,\n CameraTransformValue,\n ICameraBinding,\n} from '../contracts/ICameraBinding';\n\nexport class HeadlessCameraBinding implements ICameraBinding {\n private t: CameraTransformValue = { x: 0, y: 0, zoom: 1 };\n private screenWidth: number;\n private screenHeight: number;\n private readonly changeListeners = new Set<(kind: CameraChangeKind) => void>();\n private readonly dragStartListeners = new Set<() => void>();\n\n /** Every `configureInput` patch received, in order — for asserting input wiring. */\n readonly inputConfigs: CameraInputConfig[] = [];\n /** Latest `setDragSuspended` value. */\n dragSuspended = false;\n /** Accumulated `tick` time, to prove the engine drives the clock. */\n tickedMs = 0;\n\n constructor(screenWidth = 800, screenHeight = 600) {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n }\n\n getTransform(): CameraTransformValue {\n return { ...this.t };\n }\n\n setTransform(t: CameraTransformValue): void {\n this.t = { ...t };\n }\n\n zoomToCentre(zoom: number): void {\n // Keep the world point at the screen centre fixed, which is what a backend's\n // own centre-anchored zoom does.\n const cx = this.screenWidth / 2;\n const cy = this.screenHeight / 2;\n const world = this.toWorld(cx, cy);\n this.t = { x: cx - world.x * zoom, y: cy - world.y * zoom, zoom };\n }\n\n resize(screenWidth: number, screenHeight: number): void {\n this.screenWidth = screenWidth;\n this.screenHeight = screenHeight;\n }\n\n toWorld(screenX: number, screenY: number): Point {\n return { x: (screenX - this.t.x) / this.t.zoom, y: (screenY - this.t.y) / this.t.zoom };\n }\n\n toScreen(worldX: number, worldY: number): Point {\n return { x: worldX * this.t.zoom + this.t.x, y: worldY * this.t.zoom + this.t.y };\n }\n\n getVisibleBounds(): Rect {\n const tl = this.toWorld(0, 0);\n const br = this.toWorld(this.screenWidth, this.screenHeight);\n return { x: tl.x, y: tl.y, width: br.x - tl.x, height: br.y - tl.y };\n }\n\n configureInput(config: CameraInputConfig): void {\n this.inputConfigs.push(config);\n }\n\n setDragSuspended(suspended: boolean): void {\n this.dragSuspended = suspended;\n }\n\n onTransformChange(fn: (kind: CameraChangeKind) => void): () => void {\n this.changeListeners.add(fn);\n return () => this.changeListeners.delete(fn);\n }\n\n onDragStart(fn: () => void): () => void {\n this.dragStartListeners.add(fn);\n return () => this.dragStartListeners.delete(fn);\n }\n\n tick(dtMs: number): void {\n this.tickedMs += dtMs;\n }\n\n // ─── Test-only drivers ───────────────────────────────────────────────────\n\n /** Simulate a backend-driven transform change (wheel, drag, momentum). */\n emitTransformChange(t: CameraTransformValue, kind: CameraChangeKind): void {\n this.t = { ...t };\n for (const fn of this.changeListeners) fn(kind);\n }\n\n /** Simulate the backend reporting the start of a drag-pan. */\n emitDragStart(): void {\n for (const fn of this.dragStartListeners) fn();\n }\n}\n","/**\n * `HeadlessRenderer` — a complete `IRenderer` that draws nothing.\n *\n * Not a product renderer: a **test double**, kept deliberately (§7) so layouts,\n * picking, bounds, spec projection and the whole layer / behaviour lifecycle can\n * be exercised with no GPU and no DOM. It is why `@invana/canvas` needs a\n * drawing library neither as a dependency nor a devDependency.\n *\n * It doubles as the reference for how small the contract really is: if a new\n * feature means adding a method here that cannot be implemented without pixels,\n * that method belongs on a concrete backend, not on `IRenderer`.\n *\n * ```ts\n * const canvas = new Canvas();\n * canvas.initWithRenderer(new HeadlessRenderer(), 800, 600);\n * ```\n */\n\nimport { EventEmitter } from '../state/events/EventEmitter';\nimport type { Camera } from '../abstracts/Camera';\nimport type { ICameraBinding } from '../contracts/ICameraBinding';\nimport type {\n IElementRenderer,\n LabelSizePolicy,\n LabelSizeTarget,\n ShapeDisplayOverride,\n} from '../contracts/IElementRenderer';\nimport type { IOverlayDevice } from '../contracts/IOverlayDevice';\nimport type {\n IRenderer,\n RendererCapabilities,\n} from '../contracts/IRenderer';\nimport type { ISurface, SurfaceBackdrop, SurfaceSpace } from '../contracts/ISurface';\nimport type { BaseShapeSpec, ElementEventMap } from '../specs';\nimport { boundsOfSpec } from '../specs';\nimport type { Rect } from '../specs/geom';\nimport { HeadlessCameraBinding } from './HeadlessCameraBinding';\n\n/** An `IOverlayDevice` that records nothing and draws nothing. */\nfunction noopOverlay(): IOverlayDevice {\n const self = {\n clear: () => self,\n moveTo: () => self,\n lineTo: () => self,\n quadraticCurveTo: () => self,\n closePath: () => self,\n rect: () => self,\n roundRect: () => self,\n ellipse: () => self,\n poly: () => self,\n fill: () => self,\n stroke: () => self,\n setVisible: () => self,\n setZIndex: () => self,\n setPosition: () => self,\n destroy: () => {},\n } as unknown as IOverlayDevice;\n return self;\n}\n\n/**\n * An `IElementRenderer` that tracks which ids exist and their specs, and\n * answers geometry from the spec alone. Enough for a layer test to assert that\n * elements were mounted, moved and removed.\n */\nexport class HeadlessElementRenderer implements IElementRenderer {\n readonly events = new EventEmitter<ElementEventMap>();\n readonly shapes = new Map<string, { kind: string; x: number; y: number }>();\n readonly connectors = new Set<string>();\n readonly shapeKinds = new Set<string>([\n 'circle', 'ellipse', 'rect', 'tabbed-rect', 'polygon',\n 'regular-polygon', 'star', 'arc', 'path', 'composite',\n ]);\n\n registerShape(kind: string): void {\n this.shapeKinds.add(kind);\n }\n\n getShapeKind(id: string): string | undefined {\n return this.shapes.get(id)?.kind;\n }\n hasShape(id: string): boolean {\n return this.shapes.has(id);\n }\n hasConnector(id: string): boolean {\n return this.connectors.has(id);\n }\n\n addShape(id: string, spec: { kind: string; x?: number; y?: number }): void {\n this.shapes.set(id, { kind: spec.kind, x: spec.x ?? 0, y: spec.y ?? 0 });\n }\n updateShape(id: string, patch: { x?: number; y?: number }): void {\n const cur = this.shapes.get(id);\n if (cur) this.shapes.set(id, { ...cur, ...patch });\n }\n removeShape(id: string): void {\n this.shapes.delete(id);\n }\n addConnector(id: string): void {\n this.connectors.add(id);\n }\n updateConnector(): void {}\n removeConnector(id: string): void {\n this.connectors.delete(id);\n }\n\n moveShape(id: string, x: number, y: number): void {\n const cur = this.shapes.get(id);\n if (cur) this.shapes.set(id, { ...cur, x, y });\n }\n getShapePosition(id: string): { x: number; y: number } | null {\n const s = this.shapes.get(id);\n return s ? { x: s.x, y: s.y } : null;\n }\n\n /**\n * Display overrides by shape id — recorded so a test can assert what a\n * behaviour asked to draw. Nothing is drawn, and positions stay logical.\n */\n readonly displayOverrides = new Map<string, ShapeDisplayOverride>();\n setShapeDisplayOverride(id: string, override: ShapeDisplayOverride | null): void {\n if (!this.shapes.has(id)) return;\n if (override === null) this.displayOverrides.delete(id);\n else this.displayOverrides.set(id, override);\n }\n clearShapeDisplayOverrides(): void {\n this.displayOverrides.clear();\n }\n\n /**\n * Ids whose text the LOD channel has hidden (`setShapeTextVisible` /\n * `setConnectorTextVisible` with `false`) — recorded so a behaviour test can\n * assert what a text LOD asked for.\n */\n readonly textHidden = new Set<string>();\n setShapeTextVisible(id: string, visible: boolean): void {\n if (visible) this.textHidden.delete(id);\n else this.textHidden.add(id);\n }\n setConnectorTextVisible(id: string, visible: boolean): void {\n if (visible) this.textHidden.delete(id);\n else this.textHidden.add(id);\n }\n isTextVisible(id: string): boolean {\n if (!this.shapes.has(id) && !this.connectors.has(id)) return false;\n return !this.textHidden.has(id);\n }\n\n /** The label-size policy last pushed per target — recorded for assertions. */\n readonly labelSizePolicies: Record<LabelSizeTarget, LabelSizePolicy | null> = {\n shape: null,\n connector: null,\n };\n setLabelSizePolicy(target: LabelSizeTarget, policy: LabelSizePolicy | null): void {\n this.labelSizePolicies[target] = policy;\n }\n\n // Everything below is a no-op or a null answer: these are the calls a layer\n // makes for pixels, and there are none here.\n scaleShape(): void {}\n setConnectorStroke(): void {}\n scaleConnectorStroke(): void {}\n setRaised(): void {}\n setShapeIconVisible(): void {}\n setShapeImageVisible(): void {}\n setLabelsResolution(): void {}\n setVisibleSet(): void {}\n cull(): void {}\n uncull(): void {}\n setDecoration(): void {}\n setEffect(): void {}\n getDecoration(): undefined {\n return undefined;\n }\n setDecorationVisible(): void {}\n getDecorationWorldBounds(): null {\n return null;\n }\n setBadge(): void {}\n removeBadge(): void {}\n getShapeWorldBounds(): null {\n return null;\n }\n getShapeCenter(): null {\n return null;\n }\n getConnectorPolyline(): null {\n return null;\n }\n connectorGeometryUnchanged(): boolean {\n return false;\n }\n /**\n * Pure geometry, answered for real: the kernel's spec-geometry covers every\n * built-in kind, so a headless canvas measures node footprints exactly like\n * a drawing backend would (`GraphLayer.boundsOfNode`, minimap estimates,\n * ELK size queries — and `getBounds()`'s store-derived fit box — all work\n * with no GPU). `undefined` only for unregistered third-party kinds.\n */\n boundsOfSpec(spec: { readonly kind: string }): Rect | undefined {\n return boundsOfSpec(spec as BaseShapeSpec);\n }\n scaleShapeSpec(): undefined {\n return undefined;\n }\n collapsedShapeSpec(): undefined {\n return undefined;\n }\n fitShapeSpecToContent(): undefined {\n return undefined;\n }\n measureLabel(): null {\n return null;\n }\n hitTest(): null {\n return null;\n }\n setHitTestEnabled(): void {}\n reindexScaledShapeHits(): void {}\n reanchorAllConnectors(): void {}\n reRouteAllConnectors(): void {}\n tickAnimations(): void {}\n toSVG(): string {\n return '';\n }\n destroy(): void {\n this.shapes.clear();\n this.connectors.clear();\n }\n}\n\nexport class HeadlessSurface implements ISurface {\n readonly primitives = new HeadlessElementRenderer();\n /** Last backdrop pushed — lets a background test assert without pixels. */\n backdrop: SurfaceBackdrop | null = null;\n visible = true;\n /** Last alpha pushed — lets an entrance test assert without pixels. */\n alpha = 1;\n zIndex = 0;\n destroyed = false;\n\n constructor(\n readonly id: string,\n readonly space: SurfaceSpace,\n ) {}\n\n overlay(): IOverlayDevice {\n return noopOverlay();\n }\n setBackdrop(backdrop: SurfaceBackdrop | null): void {\n this.backdrop = backdrop;\n }\n setVisible(visible: boolean): void {\n this.visible = visible;\n }\n setAlpha(alpha: number): void {\n this.alpha = alpha;\n }\n setZIndex(z: number): void {\n this.zIndex = z;\n }\n destroy(): void {\n this.destroyed = true;\n this.primitives.destroy();\n }\n}\n\nexport class HeadlessRenderer implements IRenderer {\n readonly backend = 'canvas' as const;\n readonly canvasElement: HTMLCanvasElement | null = null;\n /** Every surface handed out, by layer id — for asserting layer lifecycle. */\n readonly surfaces = new Map<string, HeadlessSurface>();\n readonly binding = new HeadlessCameraBinding();\n camera?: Camera;\n destroyed = false;\n /** Every `tick(dt)` the engine drove, in order. */\n readonly frames: number[] = [];\n\n get capabilities(): RendererCapabilities {\n return {\n effects: 'none',\n textMode: 'native',\n rasterExport: false,\n depth: false,\n specKinds: [],\n };\n }\n\n mount(): void {}\n\n createSurface(space: SurfaceSpace, id: string): ISurface {\n const s = new HeadlessSurface(id, space);\n this.surfaces.set(id, s);\n return s;\n }\n\n createOverlay(): IOverlayDevice {\n return noopOverlay();\n }\n\n createCameraBinding(): ICameraBinding {\n return this.binding;\n }\n\n attachCamera(camera: Camera): void {\n this.camera = camera;\n }\n\n worldContentBounds(): Rect | null {\n return null;\n }\n\n resize(): void {}\n\n /** Records the frames the engine drove, so a test can assert the clock ran. */\n tick(dtMs: number): void {\n this.frames.push(dtMs);\n }\n\n destroy(): void {\n this.destroyed = true;\n }\n}\n","import type { IAnchor } from '../../../../specs';\n\n/**\n * Default anchor — resolves a shape endpoint to the shape's bounding-box\n * **centre** in world space. Uses `ref.center` (computed by the renderer\n * from `origin + bounds`) rather than the raw `(spec.x, spec.y)` origin so\n * the anchor is uniform regardless of each shape's local-origin convention\n * (`RectShape` is anchored top-left; `CircleShape` is centred).\n *\n * Ignores `fromPoint`; the centre never depends on the other endpoint.\n */\nexport const centerAnchor: IAnchor = (endpoint, _fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`centerAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n return { x: ref.center.x, y: ref.center.y };\n};\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Boundary anchor — snaps the endpoint onto the shape silhouette where the\n * ray from the shape's geometric **centre** toward the *other* endpoint\n * exits.\n *\n * The ray is cast from `ref.center` (the bounding-box centre, computed by\n * the renderer from `origin + bounds`) rather than from `ref.origin` so the\n * behaviour is uniform regardless of each shape's local-origin convention.\n * `RectShape` is anchored top-left, `CircleShape` is centred — `ref.center`\n * normalises the difference.\n *\n * Calls the shape's optional `boundaryIntersect(localFromCenter)` for\n * analytical shapes (`CircleShape` overrides). For shapes that don't\n * override, falls back to a centred-AABB ray-exit (provided by\n * `ShapeBase.boundaryIntersect`). The input is centre-relative; the output\n * is centre-relative; this anchor converts back to world via `ref.center`.\n *\n * Sets an outward-pointing `tangent` on the returned endpoint (unit vector\n * from shape centre to the boundary point) so port-aware routers can use it\n * as an exit-direction hint.\n */\nexport const boundaryAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`boundaryAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n\n const localFromCenter: Point = {\n x: fromPoint.x - ref.center.x,\n y: fromPoint.y - ref.center.y,\n };\n\n const localPoint = ref.boundaryIntersect?.(localFromCenter)\n ?? { x: 0, y: 0 };\n\n const x = ref.center.x + localPoint.x;\n const y = ref.center.y + localPoint.y;\n\n const len = Math.hypot(localPoint.x, localPoint.y);\n const tangent = len === 0\n ? { x: 1, y: 0 }\n : { x: localPoint.x / len, y: localPoint.y / len };\n\n return { x, y, tangent };\n};\n","import type { IAnchor } from '../../../../specs';\n\n/**\n * Perpendicular anchor — exits at the **midpoint of the face** of the\n * shape's bounding box that is closest to the other endpoint. The face is\n * picked by comparing `|dx| / halfWidth` against `|dy| / halfHeight`: the\n * ratio that's larger wins (so a target slightly to the right of a wide,\n * short rect still picks the right side; a tall, narrow rect picks the top\n * or bottom more readily).\n *\n * Best for **orth-style routing** (`orth`, `manhattan`, `metro`, `er`,\n * `oneSide`) where the natural exit is along one cardinal axis. Produces\n * the \"lines start at the middle of a side\" look common in flowcharts and\n * ER diagrams.\n *\n * For circles (square bounds), this lands at the cardinal points\n * (N / S / E / W) on the perimeter — a useful default though `boundary`\n * still gives smoother diagonal exits for non-orthogonal routers.\n *\n * Sets the outward tangent to the face normal: `(±1, 0)` for left/right\n * faces, `(0, ±1)` for top/bottom. Routers like `orth` consume this to\n * pick H-first vs V-first.\n */\nexport const perpendicularAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`perpendicularAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n\n const dx = fromPoint.x - ref.center.x;\n const dy = fromPoint.y - ref.center.y;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Degenerate fallback when the two endpoints coincide.\n if (dx === 0 && dy === 0) {\n return {\n x: ref.center.x + halfW,\n y: ref.center.y,\n tangent: { x: 1, y: 0 },\n };\n }\n\n // Compare the ratio so the face choice scales with each axis's extent.\n const rx = halfW > 0 ? Math.abs(dx) / halfW : Infinity;\n const ry = halfH > 0 ? Math.abs(dy) / halfH : Infinity;\n\n if (rx >= ry) {\n // Left or right face.\n const sx = dx >= 0 ? halfW : -halfW;\n return {\n x: ref.center.x + sx,\n y: ref.center.y,\n tangent: { x: dx >= 0 ? 1 : -1, y: 0 },\n };\n }\n\n // Top or bottom face.\n const sy = dy >= 0 ? halfH : -halfH;\n return {\n x: ref.center.x,\n y: ref.center.y + sy,\n tangent: { x: 0, y: dy >= 0 ? 1 : -1 },\n };\n};\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Edge-port anchor — lands the endpoint on a named face of the host's\n * bounding box, displaced from that face's midpoint along the face axis by\n * `offset` world units.\n *\n * Use this when many connectors share a node but each needs to attach at a\n * specific position along one of its faces — the canonical case is a Sankey\n * diagram, where the ribbons stack vertically on the source's right face and\n * the target's left face. The layout owns the offsets (they map to the\n * cumulative link y-positions); the anchor just resolves them to world points\n * every time the connector re-routes. Generally useful for any port-attached\n * edge model — ER table rows, BPMN sequence flows, switch-statement diagrams.\n *\n * Opts:\n * - `side: 'left' | 'right' | 'top' | 'bottom' | 'auto'` — which face to\n * attach to. `'auto'` picks the face whose outward normal best aligns\n * with the vector from this shape's centre to the *other* endpoint\n * (`fromPoint`) — dominant-axis rule. Default `'auto'`.\n * - `offset: number` — displacement from the face midpoint along the face\n * axis (the axis parallel to the face). For `'left'` / `'right'` this is\n * a vertical offset (+ down); for `'top'` / `'bottom'` a horizontal offset\n * (+ right). Default `0` (face midpoint).\n *\n * The returned `tangent` is the outward face normal — `(±1, 0)` for left /\n * right, `(0, ±1)` for top / bottom — so routers that consume the tangent\n * (orth, er, …) keep working unchanged.\n *\n * Geometric only: no graph / node / port domain concepts in the\n * implementation. The \"port\" word in the registered name describes a generic\n * port-on-an-AABB-face primitive; any domain can compose it.\n */\n\ninterface EdgePortOpts {\n readonly side?: 'left' | 'right' | 'top' | 'bottom' | 'auto';\n readonly offset?: number;\n}\n\nexport const edgePortAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`edgePortAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n const opts = endpoint.opts as EdgePortOpts | undefined;\n const offset = opts?.offset ?? 0;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Default `side` is `'auto'` — pick the face pointing toward the other\n // endpoint. Callers that want a fixed face pass an explicit `side`.\n const requestedSide = opts?.side ?? 'auto';\n const side: 'left' | 'right' | 'top' | 'bottom' =\n requestedSide === 'auto' ? resolveAutoSide(fromPoint, ref.center) : requestedSide;\n\n switch (side) {\n case 'left':\n return {\n x: ref.center.x - halfW,\n y: ref.center.y + offset,\n tangent: { x: -1, y: 0 },\n };\n case 'right':\n return {\n x: ref.center.x + halfW,\n y: ref.center.y + offset,\n tangent: { x: 1, y: 0 },\n };\n case 'top':\n return {\n x: ref.center.x + offset,\n y: ref.center.y - halfH,\n tangent: { x: 0, y: -1 },\n };\n case 'bottom':\n return {\n x: ref.center.x + offset,\n y: ref.center.y + halfH,\n tangent: { x: 0, y: 1 },\n };\n }\n};\n\n/**\n * Pick the AABB face whose outward normal best aligns with the vector from\n * the host centre to `fromPoint` (the other endpoint). Dominant axis wins;\n * ties resolve to the horizontal face (`right` / `left`).\n */\nfunction resolveAutoSide(\n fromPoint: Point,\n center: Point,\n): 'left' | 'right' | 'top' | 'bottom' {\n const dx = fromPoint.x - center.x;\n const dy = fromPoint.y - center.y;\n if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left';\n return dy >= 0 ? 'bottom' : 'top';\n}\n","import type { IAnchor, Point } from '../../../../specs';\n\n/**\n * Silhouette-port anchor — silhouette-aware sibling of {@link edgePortAnchor}.\n *\n * Same `{ side, offset }` opts as `edge-port`, but resolves the endpoint by\n * casting a ray from the shape's centre through the AABB's face point\n * `(±halfW, offset)` (or `(offset, ±halfH)` for top / bottom faces) and\n * intersecting it with the shape's actual silhouette via\n * `ref.boundaryIntersect`. The endpoint therefore lands on the rendered\n * outline — not on the AABB face — for every shape that overrides\n * `boundaryIntersect` (circle, polygon, …). Shapes without an override fall\n * through to the AABB face, matching `edge-port` exactly.\n *\n * Use this when fanning many connectors along one face of a non-rect node\n * (parallel graph edges between two circles, ER table → enum, etc.) — every\n * offset stays on the silhouette instead of floating off the AABB tangent\n * point. Large offsets that would exceed the face on a rect auto-wrap around\n * the corner to the top / bottom face instead of falling off the shape.\n *\n * Opts:\n * - `side: 'left' | 'right' | 'top' | 'bottom' | 'auto'` — which AABB face's\n * direction the offset is measured against. `'auto'` picks the face whose\n * outward normal best aligns with the vector from this shape's centre to\n * the *other* endpoint (`fromPoint`) — dominant-axis rule. Default\n * `'auto'`.\n * - `offset: number` — displacement from the face midpoint along the face\n * axis. For `'left'` / `'right'` this is a vertical offset (+ down); for\n * `'top'` / `'bottom'` a horizontal offset (+ right). Default `0`.\n *\n * The returned `tangent` is the outward radial unit vector from shape centre\n * to the silhouette point (matches `boundary`'s convention). For analytic\n * shapes this is the true surface normal; orth / er routers consume the\n * dominant axis component and remain happy.\n *\n * Geometric only: no graph / node / port domain concepts in the\n * implementation. Composable from any domain layer that already speaks the\n * `{ side, offset }` port vocabulary.\n */\n\ninterface SilhouettePortOpts {\n readonly side?: 'left' | 'right' | 'top' | 'bottom' | 'auto';\n readonly offset?: number;\n}\n\nexport const silhouettePortAnchor: IAnchor = (endpoint, fromPoint, ctx) => {\n const ref = ctx.getShape(endpoint.shapeId);\n if (!ref) {\n throw new Error(`silhouettePortAnchor: unknown shape \"${endpoint.shapeId}\"`);\n }\n const opts = endpoint.opts as SilhouettePortOpts | undefined;\n const offset = opts?.offset ?? 0;\n const halfW = ref.bounds.width / 2;\n const halfH = ref.bounds.height / 2;\n\n // Default `side` is `'auto'` — pick the face pointing toward the other\n // endpoint. Callers that want a fixed face pass an explicit `side`.\n const requestedSide = opts?.side ?? 'auto';\n const side: 'left' | 'right' | 'top' | 'bottom' =\n requestedSide === 'auto' ? resolveAutoSide(fromPoint, ref.center) : requestedSide;\n\n // Centre-relative target the ray aims at. The ray runs from local origin\n // (= centre) through this point and intersects the silhouette en route.\n let localTarget: Point;\n switch (side) {\n case 'left': localTarget = { x: -halfW, y: offset }; break;\n case 'right': localTarget = { x: halfW, y: offset }; break;\n case 'top': localTarget = { x: offset, y: -halfH }; break;\n case 'bottom': localTarget = { x: offset, y: halfH }; break;\n }\n\n // Analytical shapes (circle / polygon) override `boundaryIntersect` and\n // return the exact silhouette exit. Shapes without an override fall back\n // to the AABB target — same behaviour as `edge-port` for that case.\n const exit = ref.boundaryIntersect?.(localTarget) ?? localTarget;\n\n const x = ref.center.x + exit.x;\n const y = ref.center.y + exit.y;\n const len = Math.hypot(exit.x, exit.y);\n const tangent = len === 0\n ? { x: 1, y: 0 }\n : { x: exit.x / len, y: exit.y / len };\n\n return { x, y, tangent };\n};\n\n/**\n * Pick the AABB face whose outward normal best aligns with the vector from\n * the host centre to `fromPoint` (the other endpoint). Dominant axis wins;\n * ties resolve to the horizontal face (`right` / `left`).\n */\nfunction resolveAutoSide(\n fromPoint: Point,\n center: Point,\n): 'left' | 'right' | 'top' | 'bottom' {\n const dx = fromPoint.x - center.x;\n const dy = fromPoint.y - center.y;\n if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left';\n return dy >= 0 ? 'bottom' : 'top';\n}\n","import type { IRouter } from '../../../../specs';\n\n/**\n * Direct line from source through any waypoints to target.\n * Output: `[source, ...waypoints, target]` — a flat polyline.\n *\n * Routers decide topology (where bends sit). The visual style of segments\n * between these points is owned by the downstream `PathStyle`:\n * - `normal` → straight segments (`M, L, L, …`)\n * - `rounded` → quadratic fillets at corners\n * - `smooth` → Catmull-Rom cubic spline\n * - `bezier` → single cubic A→B (intermediate points ignored)\n */\nexport const straightRouter: IRouter = (source, target, waypoints) => {\n if (!waypoints || waypoints.length === 0) {\n return [\n { x: source.x, y: source.y },\n { x: target.x, y: target.y },\n ];\n }\n return [\n { x: source.x, y: source.y },\n ...waypoints.map((p) => ({ x: p.x, y: p.y })),\n { x: target.x, y: target.y },\n ];\n};\n","import type { Endpoint, IRouter, Point } from '../../../../specs';\n\n/**\n * Orth router — produces a polyline made of horizontal and vertical\n * segments only. Simple, geometric, **no obstacle awareness**: pick this\n * for clean H/V routing in layouts you trust to have no shapes in the way.\n * For obstacle avoidance, use `manhattan` (which is built on top of A*).\n *\n * Naming follows X6 / JointJS / mxGraph: their `Orth` is also the simple\n * H/V router, while their `Manhattan` is the obstacle-aware variant.\n *\n * For each consecutive pair `(P, Q)` of `[source, ...waypoints, target]`,\n * one bend point is inserted (producing an L-shape for that pair). The bend\n * direction (H-first vs V-first) is chosen by:\n *\n * 1. **Source tangent** on the first segment — the line exits along the\n * tangent's dominant axis. The boundary anchor sets this as an outward\n * normal hint.\n * 2. **Target tangent** on the last segment — the line approaches matching\n * the tangent's dominant axis (so the final leg is perpendicular to the\n * target boundary).\n * 3. **Alternation** in between — alternate H ↔ V across consecutive\n * segments to avoid back-tracking.\n * 4. **Dominant axis** as a final fallback when no other signal applies.\n *\n * Aligned consecutive points (same x or same y) emit no bend.\n */\nexport const orthRouter: IRouter = (source, target, waypoints) => {\n const hasWaypoints = waypoints !== undefined && waypoints.length > 0;\n\n // Special case: no waypoints, both endpoints provide tangents that agree\n // on axis. A single L-bend can't satisfy both tangents (one leg would\n // exit along the wrong axis), so emit a Z-bend with two corners. Examples:\n // - both horizontal tangents → out H, V at midX, in H\n // - both vertical tangents → out V, H at midY, in V\n if (!hasWaypoints && source.tangent && target.tangent && source.x !== target.x && source.y !== target.y) {\n const srcH = Math.abs(source.tangent.x) > Math.abs(source.tangent.y);\n const tgtH = Math.abs(target.tangent.x) > Math.abs(target.tangent.y);\n if (srcH && tgtH) {\n const midX = (source.x + target.x) / 2;\n return [\n { x: source.x, y: source.y },\n { x: midX, y: source.y },\n { x: midX, y: target.y },\n { x: target.x, y: target.y },\n ];\n }\n if (!srcH && !tgtH) {\n const midY = (source.y + target.y) / 2;\n return [\n { x: source.x, y: source.y },\n { x: source.x, y: midY },\n { x: target.x, y: midY },\n { x: target.x, y: target.y },\n ];\n }\n // Mismatched axes (one H, one V) — a single L-bend already satisfies both\n // tangents naturally, so fall through to the standard logic below.\n }\n\n const points: ReadonlyArray<Endpoint | Point> = hasWaypoints\n ? [source, ...waypoints, target]\n : [source, target];\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n let prevDir: 'H' | 'V' | null = null;\n\n for (let i = 0; i < points.length - 1; i++) {\n const P = points[i]!;\n const Q = points[i + 1]!;\n const isFirst = i === 0;\n const isLast = i === points.length - 2;\n\n if (P.x === Q.x) {\n out.push({ x: Q.x, y: Q.y });\n prevDir = 'V';\n continue;\n }\n if (P.y === Q.y) {\n out.push({ x: Q.x, y: Q.y });\n prevDir = 'H';\n continue;\n }\n\n const goHFirst = pickHFirst({\n source: isFirst ? source : null,\n target: isLast ? target : null,\n prevDir,\n P, Q,\n });\n\n const bend: Point = goHFirst\n ? { x: Q.x, y: P.y }\n : { x: P.x, y: Q.y };\n\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n prevDir = goHFirst ? 'V' : 'H';\n }\n\n return out;\n};\n\ninterface PickArgs {\n readonly source: Endpoint | null;\n readonly target: Endpoint | null;\n readonly prevDir: 'H' | 'V' | null;\n readonly P: Endpoint | Point;\n readonly Q: Endpoint | Point;\n}\n\nfunction pickHFirst({ source, target, prevDir, P, Q }: PickArgs): boolean {\n if (source?.tangent) {\n return Math.abs(source.tangent.x) >= Math.abs(source.tangent.y);\n }\n if (target?.tangent) {\n // Last leg should align with the target's tangent axis. If target tangent\n // is vertical, last leg is V → first leg of this segment is H.\n return Math.abs(target.tangent.y) >= Math.abs(target.tangent.x);\n }\n if (prevDir === 'H') return false;\n if (prevDir === 'V') return true;\n return Math.abs(Q.x - P.x) >= Math.abs(Q.y - P.y);\n}\n","/**\n * Coarse-grid construction for obstacle-aware routing. Used internally by\n * `manhattan`, `metro`, `er`, and `oneSide` routers when `RouterCtx.obstacles`\n * is non-empty. Pure data structure — no pixi, no router, no scene access.\n */\n\nimport type { Obstacle, Point } from '../../../../specs';\n\nexport interface ObstacleGrid {\n /** Cell count along x. */\n readonly width: number;\n /** Cell count along y. */\n readonly height: number;\n /** World-space x of cell `(0, _)` centre. */\n readonly originX: number;\n /** World-space y of cell `(_, 0)` centre. */\n readonly originY: number;\n /** Edge length of each cell in world units. */\n readonly cellSize: number;\n /** Length = `width * height`; `1` = blocked, `0` = free. */\n readonly cells: Uint8Array;\n}\n\nexport interface BuildGridOpts {\n readonly source: Point;\n readonly target: Point;\n readonly obstacles: ReadonlyArray<Obstacle>;\n /** Cell edge length in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region of source / target / obstacles. Default `64`. */\n readonly margin?: number;\n /** Per-obstacle inflation in world units (so the path doesn't graze edges). Default `4`. */\n readonly inflate?: number;\n /** Hard cap on `width * height`. Default `40_000` (200×200). Returns `null` on overflow. */\n readonly maxCells?: number;\n}\n\nconst DEFAULT_GRID_STEP = 16;\nconst DEFAULT_MARGIN = 64;\nconst DEFAULT_INFLATE = 4;\nconst DEFAULT_MAX_CELLS = 40_000;\n\n/**\n * Build a grid covering the **neighbourhood of this edge** — the bounding box\n * of `source` / `target` (padded by `margin`), expanded to fully contain any\n * obstacle that intersects that box. Obstacles elsewhere in the scene are\n * ignored: a whole-graph grid would need millions of cells for a single edge\n * (blowing `maxCells`), so avoidance would never run on a large diagram. The\n * edge can only route through its own neighbourhood anyway, so bounding the\n * grid there keeps it small without losing the obstacles that actually matter.\n *\n * Each obstacle is inflated by `inflate` and any cell whose centre lies inside\n * an inflated rect is marked blocked. The cell size adapts upward (never below\n * `gridStep`) so the grid always fits `maxCells` — long spans route coarsely\n * but still avoid, rather than bailing to a straight line through nodes.\n *\n * Returns `null` only for a degenerate `gridStep <= 0`.\n */\nexport function buildObstacleGrid(opts: BuildGridOpts): ObstacleGrid | null {\n const requestedStep = opts.gridStep ?? DEFAULT_GRID_STEP;\n const margin = opts.margin ?? DEFAULT_MARGIN;\n const inflate = opts.inflate ?? DEFAULT_INFLATE;\n const maxCells = opts.maxCells ?? DEFAULT_MAX_CELLS;\n\n if (requestedStep <= 0) return null;\n\n // Seed region: just the source / target span + margin.\n const seedMinX = Math.min(opts.source.x, opts.target.x) - margin;\n const seedMaxX = Math.max(opts.source.x, opts.target.x) + margin;\n const seedMinY = Math.min(opts.source.y, opts.target.y) - margin;\n const seedMaxY = Math.max(opts.source.y, opts.target.y) + margin;\n\n // Expand to fully contain obstacles that intersect the seed region, so a\n // node straddling the boundary is marked in full. Test against the *seed*\n // bounds (not the growing region) so the result is order-independent and the\n // region stays the edge's locality rather than chaining out to the whole graph.\n let minX = seedMinX;\n let maxX = seedMaxX;\n let minY = seedMinY;\n let maxY = seedMaxY;\n for (const r of opts.obstacles) {\n const r1x = r.x + r.width;\n const r1y = r.y + r.height;\n if (r.x > seedMaxX || r1x < seedMinX || r.y > seedMaxY || r1y < seedMinY) continue;\n if (r.x < minX) minX = r.x;\n if (r.y < minY) minY = r.y;\n if (r1x > maxX) maxX = r1x;\n if (r1y > maxY) maxY = r1y;\n }\n\n // Adaptive cell size: coarsen so `width * height <= maxCells` instead of\n // returning null (which would fall back to a node-crossing straight line).\n const spanX = maxX - minX;\n const spanY = maxY - minY;\n const fitStep = Math.sqrt((Math.max(spanX, 1) * Math.max(spanY, 1)) / maxCells);\n const gridStep = fitStep > requestedStep ? fitStep : requestedStep;\n\n const width = Math.max(1, Math.ceil(spanX / gridStep));\n const height = Math.max(1, Math.ceil(spanY / gridStep));\n\n const cells = new Uint8Array(width * height);\n\n const originX = minX + gridStep / 2;\n const originY = minY + gridStep / 2;\n\n for (const r of opts.obstacles) {\n const ix0 = r.x - inflate;\n const iy0 = r.y - inflate;\n const ix1 = r.x + r.width + inflate;\n const iy1 = r.y + r.height + inflate;\n const cMinX = Math.max(0, Math.floor((ix0 - originX) / gridStep));\n const cMaxX = Math.min(width - 1, Math.ceil((ix1 - originX) / gridStep));\n const cMinY = Math.max(0, Math.floor((iy0 - originY) / gridStep));\n const cMaxY = Math.min(height - 1, Math.ceil((iy1 - originY) / gridStep));\n const silhouette = r.containsInflated;\n for (let cy = cMinY; cy <= cMaxY; cy++) {\n for (let cx = cMinX; cx <= cMaxX; cx++) {\n const wx = originX + cx * gridStep;\n const wy = originY + cy * gridStep;\n // Cheap AABB pre-filter — skips cells well outside the obstacle's\n // bounding box. Required because the cell range above is rounded\n // up/down by `Math.floor` / `Math.ceil`.\n if (wx < ix0 || wx > ix1 || wy < iy0 || wy > iy1) continue;\n // Silhouette test when provided — tightens the marking from the\n // bounding box to the actual shape (circle disc, polygon outline, …).\n // When absent, the inflated AABB IS the obstacle.\n if (silhouette && !silhouette(wx, wy, inflate)) continue;\n cells[cy * width + cx] = 1;\n }\n }\n }\n\n return { width, height, originX, originY, cellSize: gridStep, cells };\n}\n\n/** Round-to-nearest cell containing the world-space point. */\nexport function worldToCell(grid: ObstacleGrid, p: Point): { cx: number; cy: number } {\n return {\n cx: Math.round((p.x - grid.originX) / grid.cellSize),\n cy: Math.round((p.y - grid.originY) / grid.cellSize),\n };\n}\n\n/** World-space centre of cell `(cx, cy)`. */\nexport function cellToWorld(grid: ObstacleGrid, cx: number, cy: number): Point {\n return {\n x: grid.originX + cx * grid.cellSize,\n y: grid.originY + cy * grid.cellSize,\n };\n}\n\n/** True when `(cx, cy)` is inside the grid and not blocked. */\nexport function isFreeCell(grid: ObstacleGrid, cx: number, cy: number): boolean {\n if (cx < 0 || cy < 0 || cx >= grid.width || cy >= grid.height) return false;\n return grid.cells[cy * grid.width + cx] === 0;\n}\n","/**\n * A* search on an `ObstacleGrid` plus path simplification. Used internally\n * by obstacle-aware routers (`manhattan`, `metro`, `er`, `oneSide`).\n *\n * The search works in cell coordinates; converting back to world points is\n * the caller's job (`cellToWorld` from `_obstacleGrid`).\n */\n\nimport type { ObstacleGrid } from './_obstacleGrid';\nimport { isFreeCell } from './_obstacleGrid';\n\nexport interface Cell {\n readonly cx: number;\n readonly cy: number;\n}\n\nexport type Connectivity = 4 | 8;\n\ninterface AStarOpts {\n readonly connectivity: Connectivity;\n}\n\nconst SQRT2 = Math.SQRT2;\n\nconst DIRS_4: ReadonlyArray<readonly [number, number, number]> = [\n [1, 0, 1],\n [-1, 0, 1],\n [0, 1, 1],\n [0, -1, 1],\n];\n\nconst DIRS_8: ReadonlyArray<readonly [number, number, number]> = [\n [1, 0, 1],\n [-1, 0, 1],\n [0, 1, 1],\n [0, -1, 1],\n [1, 1, SQRT2],\n [1, -1, SQRT2],\n [-1, 1, SQRT2],\n [-1, -1, SQRT2],\n];\n\n/**\n * A* from `start` to `goal` on `grid`. Returns the cell path (inclusive of\n * start and goal) or `null` if unreachable.\n *\n * Connectivity:\n * - `4` — H/V neighbours only. Manhattan-distance heuristic.\n * - `8` — H/V/diagonal neighbours. Octile-distance heuristic. Diagonal cost\n * is `√2`. Diagonal moves through a corner where one of the two flanking\n * cells is blocked are forbidden (\"no corner cutting\").\n *\n * Blocked start/goal cells are snapped to the nearest free cell within an\n * 8-cell radius — useful when the literal endpoint sits inside an inflated\n * obstacle (commonly the source/target shape itself, when the renderer\n * forgot to exclude it). Returns `null` if no free cell is found.\n */\nexport function aStar(\n grid: ObstacleGrid,\n start: Cell,\n goal: Cell,\n opts: AStarOpts,\n): Cell[] | null {\n const startSnapped = snapToFree(grid, start);\n const goalSnapped = snapToFree(grid, goal);\n if (!startSnapped || !goalSnapped) return null;\n\n const w = grid.width;\n const startIdx = startSnapped.cy * w + startSnapped.cx;\n const goalIdx = goalSnapped.cy * w + goalSnapped.cx;\n if (startIdx === goalIdx) return [startSnapped];\n\n const dirs = opts.connectivity === 4 ? DIRS_4 : DIRS_8;\n const heuristic = opts.connectivity === 4 ? manhattanH : octileH;\n\n const gScore = new Map<number, number>();\n const cameFrom = new Map<number, number>();\n const closed = new Set<number>();\n gScore.set(startIdx, 0);\n\n const open = new MinHeap();\n open.push(startIdx, heuristic(startSnapped, goalSnapped));\n\n while (open.size > 0) {\n const cur = open.pop()!;\n if (closed.has(cur)) continue;\n closed.add(cur);\n\n if (cur === goalIdx) return reconstruct(cameFrom, cur, w);\n\n const cx = cur % w;\n const cy = Math.floor(cur / w);\n const curG = gScore.get(cur)!;\n\n for (const [dx, dy, cost] of dirs) {\n const ncx = cx + dx;\n const ncy = cy + dy;\n if (!isFreeCell(grid, ncx, ncy)) continue;\n // No-corner-cutting on diagonal moves.\n if (dx !== 0 && dy !== 0) {\n if (!isFreeCell(grid, cx + dx, cy)) continue;\n if (!isFreeCell(grid, cx, cy + dy)) continue;\n }\n const nIdx = ncy * w + ncx;\n if (closed.has(nIdx)) continue;\n const tentativeG = curG + cost;\n const prevG = gScore.get(nIdx) ?? Infinity;\n if (tentativeG < prevG) {\n gScore.set(nIdx, tentativeG);\n cameFrom.set(nIdx, cur);\n const f = tentativeG + heuristic({ cx: ncx, cy: ncy }, goalSnapped);\n open.push(nIdx, f);\n }\n }\n }\n return null;\n}\n\n/**\n * Drop interior cells whose direction-in equals direction-out — the result\n * is a polyline of bend points only. Works for both 4- and 8-connectivity\n * (the direction signature is `(dx, dy)` so diagonal runs collapse the\n * same way as cardinal ones).\n */\nexport function simplifyCellPath(cells: ReadonlyArray<Cell>): Cell[] {\n if (cells.length <= 2) return cells.slice();\n const out: Cell[] = [cells[0]!];\n for (let i = 1; i < cells.length - 1; i++) {\n const prev = cells[i - 1]!;\n const cur = cells[i]!;\n const next = cells[i + 1]!;\n const dx1 = sign(cur.cx - prev.cx);\n const dy1 = sign(cur.cy - prev.cy);\n const dx2 = sign(next.cx - cur.cx);\n const dy2 = sign(next.cy - cur.cy);\n if (dx1 !== dx2 || dy1 !== dy2) out.push(cur);\n }\n out.push(cells[cells.length - 1]!);\n return out;\n}\n\nfunction sign(n: number): number {\n return n > 0 ? 1 : n < 0 ? -1 : 0;\n}\n\nfunction manhattanH(a: Cell, b: Cell): number {\n return Math.abs(a.cx - b.cx) + Math.abs(a.cy - b.cy);\n}\n\nfunction octileH(a: Cell, b: Cell): number {\n const dx = Math.abs(a.cx - b.cx);\n const dy = Math.abs(a.cy - b.cy);\n return dx + dy + (SQRT2 - 2) * Math.min(dx, dy);\n}\n\nfunction snapToFree(grid: ObstacleGrid, c: Cell): Cell | null {\n if (isFreeCell(grid, c.cx, c.cy)) return c;\n for (let r = 1; r <= 8; r++) {\n for (let dy = -r; dy <= r; dy++) {\n for (let dx = -r; dx <= r; dx++) {\n if (Math.abs(dx) !== r && Math.abs(dy) !== r) continue;\n if (isFreeCell(grid, c.cx + dx, c.cy + dy)) {\n return { cx: c.cx + dx, cy: c.cy + dy };\n }\n }\n }\n }\n return null;\n}\n\nfunction reconstruct(cameFrom: Map<number, number>, end: number, w: number): Cell[] {\n const out: Cell[] = [];\n let cur: number | undefined = end;\n while (cur !== undefined) {\n out.push({ cx: cur % w, cy: Math.floor(cur / w) });\n cur = cameFrom.get(cur);\n }\n return out.reverse();\n}\n\n/**\n * Minimal binary min-heap. Two parallel arrays — priorities and values —\n * keyed by the same index. Stable ordering is not required; A* tolerates\n * stale entries via the `closed` set in the search loop.\n */\nclass MinHeap {\n private p: number[] = [];\n private v: number[] = [];\n\n get size(): number {\n return this.p.length;\n }\n\n push(value: number, priority: number): void {\n this.p.push(priority);\n this.v.push(value);\n this.bubbleUp(this.p.length - 1);\n }\n\n pop(): number | undefined {\n if (this.p.length === 0) return undefined;\n const top = this.v[0]!;\n const lastP = this.p.pop()!;\n const lastV = this.v.pop()!;\n if (this.p.length > 0) {\n this.p[0] = lastP;\n this.v[0] = lastV;\n this.bubbleDown(0);\n }\n return top;\n }\n\n private bubbleUp(i: number): void {\n while (i > 0) {\n const parent = (i - 1) >> 1;\n if (this.p[i]! < this.p[parent]!) {\n this.swap(i, parent);\n i = parent;\n } else break;\n }\n }\n\n private bubbleDown(i: number): void {\n const n = this.p.length;\n while (true) {\n const left = i * 2 + 1;\n const right = i * 2 + 2;\n let smallest = i;\n if (left < n && this.p[left]! < this.p[smallest]!) smallest = left;\n if (right < n && this.p[right]! < this.p[smallest]!) smallest = right;\n if (smallest === i) break;\n this.swap(i, smallest);\n i = smallest;\n }\n }\n\n private swap(a: number, b: number): void {\n const pa = this.p[a]!;\n const va = this.v[a]!;\n this.p[a] = this.p[b]!;\n this.v[a] = this.v[b]!;\n this.p[b] = pa;\n this.v[b] = va;\n }\n}\n","import type { IRouter, Obstacle, Point } from '../../../../specs';\nimport { orthRouter } from './orth';\nimport { aStar, simplifyCellPath } from './_aStar';\nimport {\n buildObstacleGrid,\n cellToWorld,\n worldToCell,\n} from './_obstacleGrid';\n\ninterface ManhattanOpts {\n /** Grid cell size in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region. Default `64`. */\n readonly margin?: number;\n /** Obstacle inflation in world units. Default `4`. */\n readonly inflate?: number;\n /** Hard cap on grid cells (width × height). Default `40_000`. */\n readonly maxCells?: number;\n /**\n * Length of the perpendicular stub off each tangent-bearing endpoint when\n * A* takes over. Guarantees the line exits/enters the shape along its\n * tangent before A* bends it around obstacles — feels \"natural\" like ER\n * routing. Default `24` world units. Set to `0` to disable stubs (line\n * will exit/enter wherever A* decides).\n */\n readonly stubLength?: number;\n}\n\nconst DEFAULT_INFLATE = 4;\nconst DEFAULT_STUB_LENGTH = 24;\n\n/**\n * Manhattan router — H/V segments only, **routing around obstacles when\n * necessary**.\n *\n * Naming follows X6 / JointJS / mxGraph where `Manhattan` is the\n * obstacle-aware variant and `Orth` is the simple non-avoiding one.\n *\n * Pipeline (lazy A*):\n * 1. Compute the simple `orthRouter` polyline first (single L-bend or\n * tangent-aware Z-bend).\n * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline\n * crosses an inflated obstacle, return it directly. Same output as the\n * `orth` router — clean, no stair-stepping.\n * 3. Otherwise build a coarse `ObstacleGrid` and run A* (connectivity 4)\n * from source cell to target cell. Simplify the cell path to bend\n * points only and convert back to world coordinates.\n *\n * Failure cases all fall back to the simple `orthRouter` polyline:\n * - Grid construction returns `null` (cell-count cap exceeded).\n * - A* finds no path (source/target unreachable through inflated obstacles).\n *\n * The fallback emits a `console.warn` so the dev sees why avoidance didn't\n * kick in; toggle `routerOpts.obstacles: 'none'` to skip the obstacle check\n * entirely.\n *\n * Waypoints are not yet threaded through A* — when present, the simple orth\n * polyline (which respects waypoints) is checked against obstacles. If it's\n * clear, return it; if not, A* runs between source and target only.\n * Routing through waypoints with obstacle awareness is a future extension.\n */\nexport const manhattanRouter: IRouter = (source, target, waypoints, opts, ctx) => {\n const obstacles = ctx?.obstacles ?? [];\n const simple = orthRouter(source, target, waypoints, opts, ctx);\n\n if (obstacles.length === 0) return simple;\n\n const o = opts as ManhattanOpts | undefined;\n const inflate = o?.inflate ?? DEFAULT_INFLATE;\n\n if (!polylineCrossesObstacles(simple, obstacles, inflate)) {\n return simple;\n }\n\n const stubLength = o?.stubLength ?? DEFAULT_STUB_LENGTH;\n\n // Stub endpoints: when an endpoint provides a tangent (from the\n // perpendicular / boundary anchor), project the actual A* start/goal one\n // `stubLength` away along the tangent. This guarantees the visible line\n // exits the source / enters the target along the tangent direction — A*\n // never sees the literal endpoints, so it can't accidentally pick a\n // first/last move along the \"wrong\" axis.\n const sourceStub: Point = source.tangent && stubLength > 0\n ? { x: source.x + source.tangent.x * stubLength, y: source.y + source.tangent.y * stubLength }\n : { x: source.x, y: source.y };\n const targetStub: Point = target.tangent && stubLength > 0\n ? { x: target.x + target.tangent.x * stubLength, y: target.y + target.tangent.y * stubLength }\n : { x: target.x, y: target.y };\n\n const grid = buildObstacleGrid({\n source: sourceStub,\n target: targetStub,\n obstacles,\n gridStep: o?.gridStep,\n margin: o?.margin,\n inflate: o?.inflate,\n maxCells: o?.maxCells,\n });\n if (!grid) {\n if (typeof console !== 'undefined') {\n console.warn('manhattanRouter: obstacle grid exceeded maxCells; falling back to orth.');\n }\n return simple;\n }\n\n const startCell = worldToCell(grid, sourceStub);\n const goalCell = worldToCell(grid, targetStub);\n const cells = aStar(grid, startCell, goalCell, { connectivity: 4 });\n if (!cells) {\n if (typeof console !== 'undefined') {\n console.warn('manhattanRouter: A* found no path through obstacles; falling back to orth.');\n }\n return simple;\n }\n\n const simplified = simplifyCellPath(cells);\n\n // A* cell path between the stub points → world points.\n const middle: Point[] = [{ x: sourceStub.x, y: sourceStub.y }];\n for (let i = 1; i < simplified.length - 1; i++) {\n const c = simplified[i]!;\n middle.push(cellToWorld(grid, c.cx, c.cy));\n }\n middle.push({ x: targetStub.x, y: targetStub.y });\n\n // Greedy L-bend simplification ONLY across the stub-to-stub portion. The\n // source/target stub legs are preserved as the perpendicular exit/entry.\n const simplifiedMiddle = simplifyOrthPolylineAroundObstacles(middle, obstacles, inflate);\n\n // Prepend the literal source / append the literal target. The stub legs\n // (source → sourceStub and targetStub → target) emerge automatically\n // because `simplifiedMiddle` starts at `sourceStub` and ends at\n // `targetStub`. When an endpoint has no tangent, its stub equals the\n // endpoint itself; the dedup below collapses the zero-length segment.\n const out: Point[] = [{ x: source.x, y: source.y }];\n for (const p of simplifiedMiddle) {\n const last = out[out.length - 1]!;\n if (p.x === last.x && p.y === last.y) continue;\n out.push(p);\n }\n const tEnd = { x: target.x, y: target.y };\n const lastOut = out[out.length - 1]!;\n if (lastOut.x !== tEnd.x || lastOut.y !== tEnd.y) out.push(tEnd);\n return out;\n};\n\n/**\n * Returns `true` if any axis-aligned segment of `polyline` crosses any\n * inflated `obstacle` rect. Designed for orth output (H/V segments only);\n * diagonal segments fall through as non-crossing.\n */\nfunction polylineCrossesObstacles(\n polyline: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (let i = 0; i < polyline.length - 1; i++) {\n const a = polyline[i]!;\n const b = polyline[i + 1]!;\n for (const r of obstacles) {\n if (segmentCrossesRect(a, b, r, inflate)) return true;\n }\n }\n return false;\n}\n\nfunction segmentCrossesRect(a: Point, b: Point, r: Obstacle, inflate: number): boolean {\n const x0 = r.x - inflate;\n const y0 = r.y - inflate;\n const x1 = r.x + r.width + inflate;\n const y1 = r.y + r.height + inflate;\n\n // AABB pre-filter: if the segment misses the inflated bounding box, no\n // need to consult the silhouette.\n if (a.y === b.y) {\n if (a.y < y0 || a.y > y1) return false;\n const segMinX = a.x < b.x ? a.x : b.x;\n const segMaxX = a.x < b.x ? b.x : a.x;\n if (segMaxX < x0 || segMinX > x1) return false;\n // Inside AABB — silhouette refinement for non-rect obstacles.\n return segmentHitsSilhouette(a, b, r, inflate);\n }\n if (a.x === b.x) {\n if (a.x < x0 || a.x > x1) return false;\n const segMinY = a.y < b.y ? a.y : b.y;\n const segMaxY = a.y < b.y ? b.y : a.y;\n if (segMaxY < y0 || segMinY > y1) return false;\n return segmentHitsSilhouette(a, b, r, inflate);\n }\n // Diagonal segments (shouldn't appear in orth output) — be permissive\n // and let A* take over by reporting \"blocked\".\n return true;\n}\n\n/**\n * Walks an axis-aligned segment that already passed the AABB pre-filter and\n * tests sample points against the obstacle's `containsInflated` silhouette.\n * When the obstacle has no silhouette, the segment is considered blocked\n * (AABB IS the obstacle). Sample density is `~inflate / 2`, capped to a\n * reasonable max.\n */\nfunction segmentHitsSilhouette(\n a: Point,\n b: Point,\n obstacle: Obstacle,\n inflate: number,\n): boolean {\n const test = obstacle.containsInflated;\n if (!test) return true;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.abs(dx) + Math.abs(dy); // axis-aligned, so Manhattan = Euclidean\n const step = Math.max(inflate / 2, 2);\n const samples = Math.min(64, Math.max(2, Math.ceil(len / step)));\n for (let i = 0; i <= samples; i++) {\n const t = i / samples;\n const wx = a.x + dx * t;\n const wy = a.y + dy * t;\n if (test(wx, wy, inflate)) return true;\n }\n return false;\n}\n\n/**\n * Greedy L-bend reduction of an orthogonal polyline. Walks the points\n * forward; at each step looks as far ahead as possible while the connection\n * from the current point to that look-ahead point can still be made with\n * **at most one bend** that doesn't cross any obstacle. Replaces the\n * skipped intermediate points with that single bend (or no bend, when the\n * two points are already axis-aligned).\n *\n * The result preserves both endpoints exactly and stays obstacle-free; it\n * reduces a stair-stepped A* output to the minimum-bend orthogonal path\n * around the obstacle. Worst case is O(n²) in polyline length but n is\n * typically the bend count (≤ 10 for sensible diagrams), so this is cheap.\n */\nfunction simplifyOrthPolylineAroundObstacles(\n points: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): Point[] {\n if (points.length <= 2) return points.slice();\n\n const out: Point[] = [points[0]!];\n let i = 0;\n\n while (i < points.length - 1) {\n let bestJ = i + 1;\n let bestBend: Point | null = null;\n\n for (let j = i + 2; j < points.length; j++) {\n const conn = findClearOrthConnection(points[i]!, points[j]!, obstacles, inflate);\n if (conn === undefined) break;\n bestJ = j;\n bestBend = conn;\n }\n\n if (bestBend !== null) {\n const last = out[out.length - 1]!;\n if (bestBend.x !== last.x || bestBend.y !== last.y) out.push(bestBend);\n }\n out.push(points[bestJ]!);\n i = bestJ;\n }\n\n return out;\n}\n\n/**\n * Returns:\n * - `null` — `a` and `b` are axis-aligned and the straight segment is clear (no bend needed)\n * - `Point` — a clear L-bend (the bend point) connects `a` and `b`\n * - `undefined` — neither a straight nor an L-bend can connect `a` and `b` without crossing an obstacle\n */\nfunction findClearOrthConnection(\n a: Point,\n b: Point,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): Point | null | undefined {\n if (a.x === b.x || a.y === b.y) {\n return segmentCrosses(a, b, obstacles, inflate) ? undefined : null;\n }\n const bendH: Point = { x: b.x, y: a.y };\n const hClear =\n !segmentCrosses(a, bendH, obstacles, inflate) &&\n !segmentCrosses(bendH, b, obstacles, inflate);\n if (hClear) return bendH;\n\n const bendV: Point = { x: a.x, y: b.y };\n const vClear =\n !segmentCrosses(a, bendV, obstacles, inflate) &&\n !segmentCrosses(bendV, b, obstacles, inflate);\n if (vClear) return bendV;\n\n return undefined;\n}\n\nfunction segmentCrosses(\n a: Point,\n b: Point,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (const r of obstacles) {\n if (segmentCrossesRect(a, b, r, inflate)) return true;\n }\n return false;\n}\n","import type { Endpoint, IRouter, Obstacle, Point } from '../../../../specs';\nimport { aStar, simplifyCellPath } from './_aStar';\nimport { buildObstacleGrid, cellToWorld, worldToCell } from './_obstacleGrid';\n\ninterface MetroOpts {\n /** Grid cell size in world units. Default `16`. */\n readonly gridStep?: number;\n /** Padding around the bounding region. Default `64`. */\n readonly margin?: number;\n /** Obstacle inflation in world units. Default `4`. */\n readonly inflate?: number;\n /** Hard cap on grid cells (width × height). Default `40_000`. */\n readonly maxCells?: number;\n}\n\nconst DEFAULT_INFLATE = 4;\n\n/**\n * Metro router — manhattan-style topology with 45° diagonals.\n *\n * Pipeline (lazy A*):\n * 1. Compute the simple geometric metro polyline first — one straight\n * axis-aligned leg followed by a 45° diagonal absorbing the remaining\n * distance. Mirrors classic transit-map line drawing.\n * 2. If `ctx.obstacles` is empty OR no segment of the simple polyline\n * crosses an inflated obstacle, return it directly.\n * 3. Otherwise run A* with **connectivity 8** (H + V + 45° moves) on a\n * coarse grid. Simplify cell runs and convert back to world coords.\n *\n * Connectivity 8 is what makes this metro-shaped: diagonal cost `√2` is\n * cheaper than two cardinals (`1 + 1 = 2`), so A* prefers 45° moves where\n * obstacles permit — producing the metro look around obstacles too.\n */\nexport const metroRouter: IRouter = (source, target, waypoints, opts, ctx) => {\n const simple = simpleMetroPolyline(source, target, waypoints);\n const obstacles = ctx?.obstacles ?? [];\n if (obstacles.length === 0) return simple;\n\n const o = opts as MetroOpts | undefined;\n const inflate = o?.inflate ?? DEFAULT_INFLATE;\n\n if (!polylineCrossesAnyObstacle(simple, obstacles, inflate)) {\n return simple;\n }\n\n const grid = buildObstacleGrid({\n source,\n target,\n obstacles,\n gridStep: o?.gridStep,\n margin: o?.margin,\n inflate: o?.inflate,\n maxCells: o?.maxCells,\n });\n if (!grid) {\n if (typeof console !== 'undefined') {\n console.warn('metroRouter: obstacle grid exceeded maxCells; falling back to simple metro.');\n }\n return simple;\n }\n\n const startCell = worldToCell(grid, source);\n const goalCell = worldToCell(grid, target);\n const cells = aStar(grid, startCell, goalCell, { connectivity: 8 });\n if (!cells) {\n if (typeof console !== 'undefined') {\n console.warn('metroRouter: A* found no path through obstacles; falling back to simple metro.');\n }\n return simple;\n }\n\n const simplified = simplifyCellPath(cells);\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n for (let i = 1; i < simplified.length - 1; i++) {\n const c = simplified[i]!;\n out.push(cellToWorld(grid, c.cx, c.cy));\n }\n out.push({ x: target.x, y: target.y });\n return out;\n};\n\n/**\n * Simple geometric metro — between two non-aligned points, one straight\n * axis-aligned leg followed by a 45° diagonal that absorbs the remaining\n * distance. Picks \"horizontal first\" when `|dx| ≥ |dy|`. Aligned points\n * and zero-area `|dx| === |dy|` cases collapse to a single straight\n * segment. Waypoints get the same per-pair treatment.\n */\nfunction simpleMetroPolyline(\n source: Endpoint,\n target: Endpoint,\n waypoints: ReadonlyArray<Point> | undefined,\n): Point[] {\n const points: ReadonlyArray<Endpoint | Point> = waypoints && waypoints.length > 0\n ? [source, ...waypoints, target]\n : [source, target];\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n\n for (let i = 0; i < points.length - 1; i++) {\n const P = points[i]!;\n const Q = points[i + 1]!;\n const dx = Q.x - P.x;\n const dy = Q.y - P.y;\n const adx = Math.abs(dx);\n const ady = Math.abs(dy);\n\n if (adx === 0 || ady === 0 || adx === ady) {\n out.push({ x: Q.x, y: Q.y });\n continue;\n }\n\n if (adx > ady) {\n const bend: Point = { x: P.x + Math.sign(dx) * (adx - ady), y: P.y };\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n } else {\n const bend: Point = { x: P.x, y: P.y + Math.sign(dy) * (ady - adx) };\n out.push(bend);\n out.push({ x: Q.x, y: Q.y });\n }\n }\n\n return out;\n}\n\n/**\n * Returns `true` if any segment of `polyline` (H, V, or 45° diagonal)\n * crosses any inflated obstacle's bounding box plus silhouette test.\n * Conservative: diagonal segments are tested via point-sampling at the\n * obstacle's `containsInflated` (when present) or rejected on AABB-only\n * obstacles (since we can't quickly decide an arbitrary-diagonal vs\n * non-axis AABB intersection cheaper than sampling).\n */\nfunction polylineCrossesAnyObstacle(\n polyline: ReadonlyArray<Point>,\n obstacles: ReadonlyArray<Obstacle>,\n inflate: number,\n): boolean {\n for (let i = 0; i < polyline.length - 1; i++) {\n const a = polyline[i]!;\n const b = polyline[i + 1]!;\n for (const r of obstacles) {\n if (segmentCrossesObstacle(a, b, r, inflate)) return true;\n }\n }\n return false;\n}\n\nfunction segmentCrossesObstacle(a: Point, b: Point, r: Obstacle, inflate: number): boolean {\n const x0 = r.x - inflate;\n const y0 = r.y - inflate;\n const x1 = r.x + r.width + inflate;\n const y1 = r.y + r.height + inflate;\n\n // Cheap AABB pre-filter: bounding box of the segment vs. obstacle.\n const segMinX = a.x < b.x ? a.x : b.x;\n const segMaxX = a.x < b.x ? b.x : a.x;\n const segMinY = a.y < b.y ? a.y : b.y;\n const segMaxY = a.y < b.y ? b.y : a.y;\n if (segMaxX < x0 || segMinX > x1 || segMaxY < y0 || segMinY > y1) return false;\n\n // Axis-aligned segment + AABB-only obstacle: the pre-filter is already\n // exact (segment within the AABB strip), so return true.\n if ((a.x === b.x || a.y === b.y) && !r.containsInflated) return true;\n\n // Silhouette refinement / diagonal segment: sample points along the\n // segment and consult `containsInflated`. Falls back to AABB-only\n // (sample test pass = blocked) when no silhouette test is present.\n const test = r.containsInflated;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const len = Math.hypot(dx, dy);\n const step = Math.max(inflate / 2, 2);\n const samples = Math.min(64, Math.max(2, Math.ceil(len / step)));\n for (let i = 0; i <= samples; i++) {\n const t = i / samples;\n const wx = a.x + dx * t;\n const wy = a.y + dy * t;\n if (test) {\n if (test(wx, wy, inflate)) return true;\n } else {\n // No silhouette test — fall back to AABB containment per sample.\n if (wx >= x0 && wx <= x1 && wy >= y0 && wy <= y1) return true;\n }\n }\n return false;\n}\n","import type { IRouter, Point, Vec2 } from '../../../../specs';\n\ninterface ErOpts {\n /**\n * Length of the perpendicular stub off each endpoint that has a tangent\n * (set by the `boundary` anchor). Default `16` world units.\n */\n readonly stubLength?: number;\n}\n\nconst DEFAULT_STUB_LENGTH = 16;\n\n/**\n * ER (entity-relationship) router — exits each endpoint perpendicular to\n * its boundary, then routes orthogonally between the stub points.\n *\n * Reads the outward `tangent` set by the `boundary` anchor on each endpoint.\n * Each stub leg is `tangent * stubLength`. The bridge between stubs is a\n * single H-or-V segment plus one bend, picked so the bend axis alternates\n * with each stub direction (horizontal stubs → vertical bridge first).\n *\n * Falls back to a single bend (manhattan-equivalent) when neither endpoint\n * has a tangent. Waypoints are inserted between the stubs as plain\n * polyline points (no extra orthogonalisation pass).\n */\nexport const erRouter: IRouter = (source, target, waypoints, opts) => {\n const stubLen = (opts as ErOpts | undefined)?.stubLength ?? DEFAULT_STUB_LENGTH;\n\n const out: Point[] = [{ x: source.x, y: source.y }];\n\n let cur: Point = { x: source.x, y: source.y };\n if (source.tangent) {\n cur = offsetAlong(source, source.tangent, stubLen);\n out.push(cur);\n }\n\n let end: Point = { x: target.x, y: target.y };\n let preEnd: Point | null = null;\n if (target.tangent) {\n preEnd = offsetAlong(target, target.tangent, stubLen);\n }\n\n // Insert waypoints verbatim between the stub ends.\n if (waypoints && waypoints.length > 0) {\n for (const w of waypoints) {\n bridgeOrthogonal(out, cur, { x: w.x, y: w.y }, prevAxis(out));\n cur = { x: w.x, y: w.y };\n }\n }\n\n const bridgeTarget = preEnd ?? end;\n bridgeOrthogonal(out, cur, bridgeTarget, prevAxis(out));\n\n if (preEnd) out.push(end);\n\n return out;\n};\n\nfunction offsetAlong(p: Point, t: Vec2, dist: number): Point {\n return { x: p.x + t.x * dist, y: p.y + t.y * dist };\n}\n\n/**\n * Append a single H-then-V or V-then-H bend that connects `from` to `to`,\n * choosing H-first or V-first to alternate with the most recent leg axis.\n * Aligned points emit no bend.\n */\nfunction bridgeOrthogonal(\n out: Point[],\n from: Point,\n to: Point,\n prevAxisDir: 'H' | 'V' | null,\n): void {\n if (from.x === to.x || from.y === to.y) {\n if (from.x !== to.x || from.y !== to.y) out.push({ x: to.x, y: to.y });\n return;\n }\n // Alternate from previous axis; default to dominant axis if no history.\n const goHFirst = prevAxisDir === 'H'\n ? false\n : prevAxisDir === 'V'\n ? true\n : Math.abs(to.x - from.x) >= Math.abs(to.y - from.y);\n const bend: Point = goHFirst\n ? { x: to.x, y: from.y }\n : { x: from.x, y: to.y };\n out.push(bend);\n out.push({ x: to.x, y: to.y });\n}\n\n/** Direction of the most recently appended leg. */\nfunction prevAxis(out: ReadonlyArray<Point>): 'H' | 'V' | null {\n if (out.length < 2) return null;\n const a = out[out.length - 2]!;\n const b = out[out.length - 1]!;\n if (a.x === b.x && a.y !== b.y) return 'V';\n if (a.y === b.y && a.x !== b.x) return 'H';\n return null;\n}\n","import type { IRouter, Point } from '../../../../specs';\n\ninterface OneSideOpts {\n /**\n * Which side of the source the line must leave on. Default `'right'`.\n */\n readonly side?: 'top' | 'right' | 'bottom' | 'left';\n /**\n * How far the source projects along the chosen side direction before\n * turning toward the target. Default `30` world units.\n */\n readonly padLength?: number;\n}\n\nconst DEFAULT_SIDE: 'right' = 'right';\nconst DEFAULT_PAD = 30;\n\n/**\n * oneSide router — forces the line to exit the source on a designated side,\n * then routes orthogonally to the target. Useful for swimlane / \"all on one\n * side\" diagrams where every connector must leave the source in the same\n * direction regardless of where the target is.\n *\n * Polyline shape:\n * `source → exit → midBend → target`\n *\n * - `exit` — source stepped `padLength` along the side direction.\n * - `midBend` — perpendicular to the side at the target's parallel axis\n * (so the leg from exit→midBend is along the side direction\n * inverted, and midBend→target is perpendicular).\n *\n * For 'right' / 'left' the exit/midBend legs are horizontal then vertical;\n * for 'top' / 'bottom' they're vertical then horizontal. When source and\n * target are perfectly aligned with the side direction the path collapses\n * to a single-leg traversal.\n *\n * Waypoints are not honoured by this router — its purpose is the forced\n * exit, not free-form routing. Pass `manhattan` for waypoint routing.\n */\nexport const oneSideRouter: IRouter = (source, target, _waypoints, opts) => {\n const o = opts as OneSideOpts | undefined;\n const side = o?.side ?? DEFAULT_SIDE;\n const pad = o?.padLength ?? DEFAULT_PAD;\n\n const isHorizontal = side === 'left' || side === 'right';\n const exit: Point = isHorizontal\n ? { x: source.x + (side === 'right' ? pad : -pad), y: source.y }\n : { x: source.x, y: source.y + (side === 'bottom' ? pad : -pad) };\n\n // For horizontal sides, midBend is at (exit.x, target.y) — vertical leg\n // from exit, horizontal leg to target. For vertical sides, swap axes.\n const midBend: Point = isHorizontal\n ? { x: exit.x, y: target.y }\n : { x: target.x, y: exit.y };\n\n const out: Point[] = [{ x: source.x, y: source.y }, exit];\n if (midBend.x !== exit.x || midBend.y !== exit.y) out.push(midBend);\n if (midBend.x !== target.x || midBend.y !== target.y) out.push({ x: target.x, y: target.y });\n else if (out[out.length - 1]!.x !== target.x || out[out.length - 1]!.y !== target.y) {\n out.push({ x: target.x, y: target.y });\n }\n\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Sharp segments. Walks the polyline emitting `M` then `L L L …`.\n *\n * For a 2-point polyline, this is `[M source, L target]` — equivalent to\n * the straight-line baseline. For an N-point polyline (router-produced\n * bends), this draws straight segments between every consecutive pair with\n * no corner treatment.\n */\nexport const normalPathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n for (let i = 1; i < polyline.length; i++) {\n out.push({ kind: 'L', x: polyline[i]!.x, y: polyline[i]!.y });\n }\n return out;\n};\n","import type { IPathStyle, PathCommand, Point } from '../../../../specs';\n\ninterface RoundedOpts {\n /** Corner fillet radius in world units. Default `8`. Auto-clamped per corner. */\n readonly radius?: number;\n}\n\nconst DEFAULT_RADIUS = 8;\n\n/**\n * Quadratic arc fillets at every interior polyline corner.\n *\n * For each interior corner B between segments A→B and B→C:\n * - Pick a per-corner radius `t = min(radius, |AB|/2, |BC|/2)`.\n * - Approach point P1 on segment AB at distance `t` from B.\n * - Departure point P2 on segment BC at distance `t` from B.\n * - Emit `L P1`, then `Q B P2` — the corner becomes a quadratic with control\n * at the original corner.\n *\n * For a 2-point polyline (no interior corners) the output is identical to\n * `normal`: `[M, L]`. Collinear corners (parallel incoming/outgoing) emit a\n * straight `L` through B with no Q (degenerate fillet).\n */\nexport const roundedPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const radius = (opts as RoundedOpts | undefined)?.radius ?? DEFAULT_RADIUS;\n\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n\n if (polyline.length === 2) {\n out.push({ kind: 'L', x: polyline[1]!.x, y: polyline[1]!.y });\n return out;\n }\n\n for (let i = 1; i < polyline.length - 1; i++) {\n const a = polyline[i - 1]!;\n const b = polyline[i]!;\n const c = polyline[i + 1]!;\n\n const ab = sub(b, a);\n const bc = sub(c, b);\n const lenAB = len(ab);\n const lenBC = len(bc);\n if (lenAB === 0 || lenBC === 0) {\n out.push({ kind: 'L', x: b.x, y: b.y });\n continue;\n }\n\n // Cap the fillet so adjacent corners can't overlap on short segments.\n const t = Math.min(radius, lenAB / 2, lenBC / 2);\n if (t <= 0) {\n out.push({ kind: 'L', x: b.x, y: b.y });\n continue;\n }\n\n const p1 = { x: b.x - (ab.x / lenAB) * t, y: b.y - (ab.y / lenAB) * t };\n const p2 = { x: b.x + (bc.x / lenBC) * t, y: b.y + (bc.y / lenBC) * t };\n\n out.push({ kind: 'L', x: p1.x, y: p1.y });\n out.push({ kind: 'Q', cx: b.x, cy: b.y, x: p2.x, y: p2.y });\n }\n\n const last = polyline[polyline.length - 1]!;\n out.push({ kind: 'L', x: last.x, y: last.y });\n return out;\n};\n\nfunction sub(a: Point, b: Point): Point {\n return { x: a.x - b.x, y: a.y - b.y };\n}\n\nfunction len(v: Point): number {\n return Math.hypot(v.x, v.y);\n}\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BezierOpts {\n /**\n * Direction of the s-curve. `'h'` pulls control points horizontally,\n * `'v'` pulls them vertically, `'auto'` picks the dominant axis from the\n * source→target delta. Default `'auto'`.\n */\n readonly axis?: 'h' | 'v' | 'auto';\n /**\n * How far the control points pull along the axis, as a fraction of the\n * source→target delta on that axis. `0.5` produces a balanced s-curve;\n * `0` collapses to a straight line; `>0.5` produces an exaggerated swing.\n * Default `0.5`.\n */\n readonly tension?: number;\n}\n\nconst DEFAULT_TENSION = 0.5;\n\n/**\n * Single cubic Bézier between the first and last polyline points, with\n * auto-generated control handles. Intermediate polyline points (router\n * waypoints, manhattan corners, …) are **ignored** — pick `smooth` if you\n * want the path to follow them.\n *\n * Control-point strategy: direction-aware s-curve.\n * - For horizontal-dominant layouts the controls pull horizontally:\n * `c1 = source + (dx * tension, 0)`, `c2 = target - (dx * tension, 0)`.\n * Source leaves and target arrives along the x-axis.\n * - For vertical-dominant layouts the controls pull vertically.\n *\n * Output: `[M source, C target]` — a single curve segment.\n */\nexport const bezierPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const o = opts as BezierOpts | undefined;\n const tension = o?.tension ?? DEFAULT_TENSION;\n const axisOpt = o?.axis ?? 'auto';\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const dx = t.x - s.x;\n const dy = t.y - s.y;\n\n const axis: 'h' | 'v' = axisOpt === 'auto'\n ? Math.abs(dx) >= Math.abs(dy) ? 'h' : 'v'\n : axisOpt;\n\n const c1: { x: number; y: number } = axis === 'h'\n ? { x: s.x + dx * tension, y: s.y }\n : { x: s.x, y: s.y + dy * tension };\n\n const c2: { x: number; y: number } = axis === 'h'\n ? { x: t.x - dx * tension, y: t.y }\n : { x: t.x, y: t.y - dy * tension };\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface QuadraticOpts {\n /**\n * Perpendicular offset of the control point from the source→target chord,\n * in world units. Positive values bow the curve to the **right** of the\n * chord direction (in screen-y-down coordinates: rotating the chord 90°\n * CW); negative values bow it to the left. Default `30`.\n *\n * Choose the sign to give every edge in a radial / hub-and-spoke layout\n * a consistent rotational bias — a positive offset on every spoke makes\n * the bundle read as a coherent swirl rather than a noisy spray.\n */\n readonly curveOffset?: number;\n /**\n * Where along the chord the control point's foot sits, as a fraction\n * `0..1` (`0` = source, `1` = target). The perpendicular offset is\n * applied from this foot. Default `0.5` (chord midpoint), which\n * produces a symmetric arc.\n */\n readonly curvePosition?: number;\n}\n\nconst DEFAULT_OFFSET = 30;\nconst DEFAULT_POSITION = 0.5;\n\n/**\n * Quadratic Bézier from the first polyline point to the last with a single\n * control point placed **perpendicular to the chord** at `curvePosition`\n * along it and `curveOffset` units to the side.\n *\n * This is the G6-style \"quadratic edge\": one control point, signed\n * perpendicular offset, fixed position along the chord. Unlike axis-aligned\n * `bezier` (whose control handles pull along `axis: 'h' | 'v'`), the\n * perpendicular construction gives a real bow on **every** orientation —\n * cardinal chords no longer collapse to straight lines.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored (a router that produces extra points doesn't compose\n * meaningfully with a single-control-point quadratic).\n *\n * Edge cases:\n * - Polyline shorter than two points → `[]` (matches the other pathStyles).\n * - Coincident endpoints (`len === 0`) → degenerate `M` only; the\n * perpendicular is undefined.\n */\nexport const quadraticPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n\n const o = opts as QuadraticOpts | undefined;\n const offset = o?.curveOffset ?? DEFAULT_OFFSET;\n const position = o?.curvePosition ?? DEFAULT_POSITION;\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const dx = t.x - s.x;\n const dy = t.y - s.y;\n const len = Math.hypot(dx, dy);\n\n if (len === 0) {\n return [{ kind: 'M', x: s.x, y: s.y }];\n }\n\n // Anchor point along the chord at `position` (0 = source, 1 = target).\n const ax = s.x + dx * position;\n const ay = s.y + dy * position;\n\n // Unit perpendicular to the chord. In screen-y-down coords this rotates\n // the chord direction 90° clockwise so positive `offset` bows the curve\n // to the visual right of the chord direction (source → target).\n const px = dy / len;\n const py = -dx / len;\n\n const cx = ax + px * offset;\n const cy = ay + py * offset;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'Q', cx, cy, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BumpRadialOpts {\n /**\n * Polar origin (centre of the polar coordinate system) in world units.\n * Source / target angles are measured from this point. Default `(0, 0)`.\n *\n * Set this when your radial layout is centred somewhere other than the\n * world origin — e.g. an offset hierarchy, a sub-tree positioned beside\n * a sibling cluster.\n */\n readonly origin?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Single cubic Bézier from the first to the last polyline point with control\n * points placed on the **midradius circle** at the source and target angles.\n *\n * This is the same curve `d3.linkRadial()` produces, ported to operate on\n * cartesian polyline endpoints (we recover the polar coordinates from the\n * configured origin). It gives a tree edge that:\n * - leaves the source tangent to the radius (radially outward / inward),\n * - sweeps through the midradius arc between the two angles,\n * - arrives at the target tangent to the radius.\n *\n * The result reads correctly in any orientation — it doesn't bulge sideways\n * the way an axis-aligned `bezier` does on near-vertical edges. Pair with\n * `router: 'straight'`; intermediate polyline waypoints are ignored (a\n * router that produces extra points doesn't compose meaningfully with a\n * polar curve).\n *\n * Edge cases:\n * - Co-linear with the origin (`r0` or `r1` is zero, or both angles equal):\n * falls back to a straight line, since a polar curve isn't defined.\n * - Polyline shorter than two points: returns `[]` (matches other styles).\n */\nexport const bumpRadialPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const origin = (opts as BumpRadialOpts | undefined)?.origin ?? { x: 0, y: 0 };\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const sxRel = s.x - origin.x;\n const syRel = s.y - origin.y;\n const txRel = t.x - origin.x;\n const tyRel = t.y - origin.y;\n\n const r0 = Math.hypot(sxRel, syRel);\n const r1 = Math.hypot(txRel, tyRel);\n\n // Degenerate cases — emit a straight segment. A polar curve would either\n // collapse to zero or NaN.\n if (r0 === 0 || r1 === 0) {\n return [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'L', x: t.x, y: t.y },\n ];\n }\n\n const a0 = Math.atan2(syRel, sxRel);\n const a1 = Math.atan2(tyRel, txRel);\n const rMid = (r0 + r1) / 2;\n\n const c1x = origin.x + rMid * Math.cos(a0);\n const c1y = origin.y + rMid * Math.sin(a0);\n const c2x = origin.x + rMid * Math.cos(a1);\n const c2y = origin.y + rMid * Math.sin(a1);\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x, c1y, c2x, c2y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Single cubic Bézier from the first to the last polyline point.\n *\n * Two modes depending on whether anchor `endpoints` are passed in:\n *\n * - **Tangent-aware (preferred)** — when `endpoints.source.tangent` and / or\n * `endpoints.target.tangent` are available, the control points are placed\n * along each shape's outward surface normal: `c1 = s + sTan × handle`,\n * `c2 = t + tTan × handle`, with `handle = |tx − sx| / 2`. The curve\n * therefore leaves the source flush with its silhouette tangent and\n * arrives at the target flush with *its* silhouette tangent — no kink\n * at off-equator anchors (circles, polygons, rounded rects).\n *\n * - **Fallback** — when no tangents are available (direct unit-test\n * invocation, or an anchor that produced no tangent), the control\n * points fall back to the **vertical midline** between source and\n * target — `c1 = ((sx + tx)/2, sy)` and `c2 = ((sx + tx)/2, ty)` —\n * matching d3-shape's `linkHorizontal()` / d3-sankey's\n * `sankeyLinkHorizontal()` ribbon curve. For rect + horizontal-face\n * anchors (`edge-port` on `'left'` / `'right'`) the tangent-aware\n * formula reduces to this same placement, so existing rect-on-rect\n * visuals are unchanged.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored (a router that produces extra points doesn't compose\n * meaningfully with a horizontal-bump curve).\n *\n * Edge cases:\n * - Polyline shorter than two points → `[]` (matches the other pathStyles).\n * - `sx === tx` (vertical link) → tangent-aware path uses `handle = 0`,\n * collapsing both control points onto the endpoints (a straight line);\n * fallback degenerates to a vertical line on `x = sx`. Both stay\n * well-defined.\n */\nexport const bumpHorizontalPathStyle: IPathStyle = (polyline, _opts, endpoints) => {\n if (polyline.length < 2) return [];\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const handle = Math.abs(t.x - s.x) / 2;\n\n const sTan = endpoints?.source.tangent;\n const tTan = endpoints?.target.tangent;\n\n const c1x = sTan ? s.x + sTan.x * handle : (s.x + t.x) / 2;\n const c1y = sTan ? s.y + sTan.y * handle : s.y;\n const c2x = tTan ? t.x + tTan.x * handle : (s.x + t.x) / 2;\n const c2y = tTan ? t.y + tTan.y * handle : t.y;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x, c1y, c2x, c2y, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\n/**\n * Single cubic Bézier from the first to the last polyline point, pulled\n * **vertically** — the curve of a top-to-bottom tree, d3-shape's\n * `linkVertical()`: `c1 = (sx, (sy + ty)/2)`, `c2 = (tx, (sy + ty)/2)`.\n *\n * Unlike `bump-horizontal` it ignores the anchors' tangents. On a circle with\n * the default `boundary` anchor the tangent points at the other node, so a\n * tangent-following curve flattens into a straight line; the midline keeps the\n * S-curve on every shape.\n *\n * Pair with `router: 'straight'`; intermediate waypoints are ignored.\n *\n * Edge cases: fewer than two points → `[]`; `sy === ty` → a straight line.\n */\nexport const bumpVerticalPathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const midY = (s.y + t.y) / 2;\n\n const out: PathCommand[] = [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'C', c1x: s.x, c1y: midY, c2x: t.x, c2y: midY, x: t.x, y: t.y },\n ];\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ntype Pt = { readonly x: number; readonly y: number };\n\n/** Below this distance (world units) two points are the same point. */\nconst COINCIDENT = 0.5;\n\n/**\n * A piecewise cubic Bézier read from its **control points** — the curve a\n * layout engine computed, drawn as it computed it.\n *\n * Pair with `router: 'straight'`, which yields\n * `[sourceAnchor, ...waypoints, targetAnchor]`. The waypoints are read as a\n * Bézier chain `P0, C1, C2, P1, C1, C2, P2, …, Pn` — `3k + 1` points, every\n * third one on the curve. That is how ELK's `SPLINES` edge routing reports a\n * section: start point, bend points (always `3k − 1` of them), end point. The\n * chain is drawn as is, so the curve keeps the clearance from nodes the engine\n * routed it for — unlike `smooth`, which interpolates *through* points and can\n * overshoot.\n *\n * The anchors join the chain with a straight leg when they don't sit on its\n * ends. With the default `boundary` anchor aiming at the first / last waypoint,\n * and ELK's section ends on the node border, the legs are zero-length and are\n * left out.\n *\n * Waypoints that don't form a chain (wrong count, or none) are drawn as a\n * polyline through them — the same as `normal` — so a misconfigured edge stays\n * visible and connected.\n */\nexport const splinePathStyle: IPathStyle = (polyline) => {\n if (polyline.length < 2) return [];\n const source = polyline[0]!;\n const target = polyline[polyline.length - 1]!;\n const chain = polyline.slice(1, -1);\n\n if (chain.length < 4 || (chain.length - 1) % 3 !== 0) {\n return polyline.map((p, i): PathCommand =>\n i === 0 ? { kind: 'M', x: p.x, y: p.y } : { kind: 'L', x: p.x, y: p.y },\n );\n }\n\n const first = chain[0]!;\n const last = chain[chain.length - 1]!;\n const out: PathCommand[] = [{ kind: 'M', x: source.x, y: source.y }];\n if (!coincident(source, first)) out.push({ kind: 'L', x: first.x, y: first.y });\n for (let i = 1; i + 2 < chain.length; i += 3) {\n const c1 = chain[i]!;\n const c2 = chain[i + 1]!;\n const p = chain[i + 2]!;\n out.push({ kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: p.x, y: p.y });\n }\n if (!coincident(last, target)) out.push({ kind: 'L', x: target.x, y: target.y });\n return out;\n};\n\nfunction coincident(a: Pt, b: Pt): boolean {\n return Math.abs(a.x - b.x) < COINCIDENT && Math.abs(a.y - b.y) < COINCIDENT;\n}\n","import type { IPathStyle, PathCommand, Point } from '../../../../specs';\n\ninterface SmoothOpts {\n /**\n * Catmull-Rom tension. `1` is the standard uniform spline (visually\n * smooth, slightly loose at sharp turns); higher values tighten the\n * curve toward the polyline; `0` collapses to straight segments. Default\n * `1`.\n */\n readonly tension?: number;\n}\n\nconst DEFAULT_TENSION = 1;\n\n/**\n * Catmull-Rom spline through every polyline point, emitted as cubic Béziers.\n * The curve passes through every input point exactly; intermediate router\n * waypoints / manhattan corners become smoothly interpolated bends.\n *\n * For each segment `Pi → Pi+1`, the control points use Catmull-Rom to Bézier\n * conversion:\n * `c1 = Pi + (Pi+1 - Pi-1) * tension / 6`\n * `c2 = Pi+1 - (Pi+2 - Pi) * tension / 6`\n *\n * At the endpoints, the missing virtual neighbour is mirrored\n * (`P-1 = P0`, `Pn+1 = Pn`).\n *\n * For a 2-point polyline this produces a single cubic with collinear control\n * points — visually identical to a straight line.\n */\nexport const smoothPathStyle: IPathStyle = (polyline, opts) => {\n const n = polyline.length;\n if (n < 2) return [];\n\n const tension = (opts as SmoothOpts | undefined)?.tension ?? DEFAULT_TENSION;\n const k = tension / 6;\n\n const out: PathCommand[] = [{ kind: 'M', x: polyline[0]!.x, y: polyline[0]!.y }];\n\n for (let i = 0; i < n - 1; i++) {\n const p0 = polyline[i - 1] ?? polyline[i]!;\n const p1 = polyline[i]!;\n const p2 = polyline[i + 1]!;\n const p3 = polyline[i + 2] ?? p2;\n\n const c1: Point = { x: p1.x + (p2.x - p0.x) * k, y: p1.y + (p2.y - p0.y) * k };\n const c2: Point = { x: p2.x - (p3.x - p1.x) * k, y: p2.y - (p3.y - p1.y) * k };\n\n out.push({ kind: 'C', c1x: c1.x, c1y: c1.y, c2x: c2.x, c2y: c2.y, x: p2.x, y: p2.y });\n }\n\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface StepRadialOpts {\n /**\n * Polar origin (centre of the polar coordinate system) in world units.\n * Source / target angles are measured from this point. Default `(0, 0)`.\n *\n * Set this when your radial layout is centred somewhere other than the\n * world origin.\n */\n readonly origin?: { readonly x: number; readonly y: number };\n}\n\n/**\n * Two-segment **radial step** (a.k.a. \"elbow\") link, matching the d3\n * `linkStep` helper used by the canonical Tree of Life example:\n *\n * 1. Circular **arc** at the source's radius from the source angle to the\n * target angle (constant-radius sweep along the parent's tier).\n * 2. Straight **radial line** outward from there to the target.\n *\n * Visually this produces the boxy / angular cluster-dendrogram look — every\n * subtree fans out from a horizontal arc at its parent's radius, then shoots\n * outward as straight spokes. It's the right pick for radial *clusters*\n * (where all leaves sit on a single outer rim and the eye reads tiers via\n * the constant-radius arcs); the smooth {@link bumpRadialPathStyle} is the\n * right pick for radial *trees* (where edges should curve continuously).\n *\n * The arc is approximated with cubic Bézier sub-arcs (≤ 90° each) using the\n * standard `k = (4/3) tan(θ/4) r` handle-length formula — visually\n * indistinguishable from a true SVG `A` command at any zoom, and stays a\n * flat sequence of `M / C / L` commands the Pixi renderer already knows\n * how to consume.\n *\n * Pair with `router: 'straight'`; intermediate polyline waypoints are\n * ignored. Use `anchor: 'center'` on the edge so the tangent is computed\n * from the true node-centre angle (otherwise the arc would launch from the\n * trimmed boundary cut-point and read crooked).\n *\n * Edge cases:\n * - `r0 === 0` (source at the origin): emits a single straight `M → L`.\n * - Source / target angles equal (single-child clade, or angular wrap\n * collapses to zero): emits a straight radial `M → L`.\n * - Polyline shorter than two points: returns `[]`.\n */\nexport const stepRadialPathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 2) return [];\n const origin = (opts as StepRadialOpts | undefined)?.origin ?? { x: 0, y: 0 };\n\n const s = polyline[0]!;\n const t = polyline[polyline.length - 1]!;\n const sxRel = s.x - origin.x;\n const syRel = s.y - origin.y;\n const txRel = t.x - origin.x;\n const tyRel = t.y - origin.y;\n\n const r0 = Math.hypot(sxRel, syRel);\n\n // Degenerate: source has no defined angle. Straight line is the only\n // sensible fallback.\n if (r0 === 0) {\n return [\n { kind: 'M', x: s.x, y: s.y },\n { kind: 'L', x: t.x, y: t.y },\n ];\n }\n\n const a0 = Math.atan2(syRel, sxRel);\n const a1 = Math.atan2(tyRel, txRel);\n\n // Normalise the angular sweep into (-π, π] so we always take the shorter\n // way around. In a hierarchical layout the parent-to-child angular gap is\n // small (well under π/2 in practice), so this is just defensive.\n let delta = a1 - a0;\n while (delta > Math.PI) delta -= 2 * Math.PI;\n while (delta < -Math.PI) delta += 2 * Math.PI;\n\n // Arc-end point: same radius as source, angle of target.\n const arcEndX = origin.x + r0 * Math.cos(a1);\n const arcEndY = origin.y + r0 * Math.sin(a1);\n\n const out: PathCommand[] = [{ kind: 'M', x: s.x, y: s.y }];\n\n if (Math.abs(delta) > 1e-9) {\n // Approximate the arc with one or more cubic Béziers, each spanning at\n // most ~π/2 of the circle so the standard handle-length formula stays\n // visually exact.\n const numSegments = Math.max(1, Math.ceil(Math.abs(delta) / (Math.PI / 2)));\n const segAngle = delta / numSegments;\n // Signed handle length — sign of `tan(segAngle / 4)` already tracks\n // the direction of the sweep, so the same formula works for both\n // clockwise and anti-clockwise arcs.\n const k = (4 / 3) * Math.tan(segAngle / 4) * r0;\n\n let theta = a0;\n let px = origin.x + r0 * Math.cos(theta);\n let py = origin.y + r0 * Math.sin(theta);\n for (let i = 0; i < numSegments; i++) {\n const nextTheta = theta + segAngle;\n const nx = origin.x + r0 * Math.cos(nextTheta);\n const ny = origin.y + r0 * Math.sin(nextTheta);\n // Tangent at each endpoint of a circle (ccw): (-sin θ, cos θ).\n // Signed `k` flips it for clockwise sweeps automatically.\n const c1x = px + k * -Math.sin(theta);\n const c1y = py + k * Math.cos(theta);\n const c2x = nx - k * -Math.sin(nextTheta);\n const c2y = ny - k * Math.cos(nextTheta);\n out.push({ kind: 'C', c1x, c1y, c2x, c2y, x: nx, y: ny });\n theta = nextTheta;\n px = nx;\n py = ny;\n }\n } else {\n // Same ray — no arc, just glide to the arc-end point (which equals the\n // source up to floating-point noise) before emitting the radial line.\n out.push({ kind: 'L', x: arcEndX, y: arcEndY });\n }\n\n // Radial segment: straight line out to the target.\n out.push({ kind: 'L', x: t.x, y: t.y });\n return out;\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ninterface BundleOpts {\n /**\n * Bundling tension in `[0, 1]`. `0` collapses the curve to a straight chord\n * between the endpoints (the B-spline through the lerp line is linear);\n * `1` is a strict open cubic B-spline through every polyline point;\n * intermediate values β-blend each control point toward the chord per\n * `P_i' = β·P_i + (1 - β)·lerp(P_0, P_{n-1}, i/(n-1))`. Default `0.85`,\n * matching d3-shape's `curveBundle` default and the Observable\n * Hierarchical Edge Bundling example.\n */\n readonly beta?: number;\n}\n\nconst DEFAULT_BETA = 0.85;\n\n/**\n * Hierarchical-edge-bundling curve through the polyline, emitted as cubic\n * Béziers. This is the d3-shape `curveBundle.beta(β)` shape: an open cubic\n * B-spline driven by control points that are β-blended toward the straight\n * line from `P_0` to `P_{n-1}`.\n *\n * Pair with `router: 'straight'` and feed the hierarchy-ancestor sequence as\n * `waypoints` on the connector spec (per-edge layout output); the router will\n * pass `[source, ...waypoints, target]` through unchanged, and this pathStyle\n * sees the full sequence.\n *\n * Reference: d3-shape `src/curve/bundle.js` + `src/curve/basis.js`.\n */\nexport const bundlePathStyle: IPathStyle = (polyline, opts) => {\n const n = polyline.length;\n if (n < 2) return [];\n\n const p0 = polyline[0]!;\n const pn = polyline[n - 1]!;\n\n // 2 points = no interior to bundle — straight line.\n if (n === 2) {\n return [\n { kind: 'M', x: p0.x, y: p0.y },\n { kind: 'L', x: pn.x, y: pn.y },\n ];\n }\n\n const beta = clamp01((opts as BundleOpts | undefined)?.beta ?? DEFAULT_BETA);\n const dx = pn.x - p0.x;\n const dy = pn.y - p0.y;\n const inv = 1 / (n - 1);\n\n // β-blend each control point toward the straight chord. β=1 leaves the\n // polyline untouched (strict B-spline); β=0 maps every point onto the\n // chord (the B-spline through collinear points is linear).\n const bx: number[] = new Array(n);\n const by: number[] = new Array(n);\n for (let i = 0; i < n; i++) {\n const t = i * inv;\n const pi = polyline[i]!;\n bx[i] = beta * pi.x + (1 - beta) * (p0.x + t * dx);\n by[i] = beta * pi.y + (1 - beta) * (p0.y + t * dy);\n }\n\n // Open cubic B-spline emitted as Bézier segments. Matches d3.Basis.lineEnd\n // semantics: a `moveTo(B0)`, a `lineTo((5·B0 + B1)/6)` to anchor the first\n // segment, then for each `i ≥ 2` a Bézier from the running pen to the\n // averaged knot `(B_{i-2} + 4·B_{i-1} + B_i)/6` using the standard\n // B-spline-to-Bézier conversion, and finally a closing Bézier into\n // `(B_{n-2} + 5·B_{n-1})/6` plus a `lineTo(B_{n-1})` so the curve actually\n // terminates at the last input point rather than at the averaged knot.\n const out: PathCommand[] = [];\n out.push({ kind: 'M', x: bx[0]!, y: by[0]! });\n out.push({\n kind: 'L',\n x: (5 * bx[0]! + bx[1]!) / 6,\n y: (5 * by[0]! + by[1]!) / 6,\n });\n\n for (let i = 2; i < n; i++) {\n const x0 = bx[i - 2]!;\n const y0 = by[i - 2]!;\n const x1 = bx[i - 1]!;\n const y1 = by[i - 1]!;\n const x = bx[i]!;\n const y = by[i]!;\n out.push({\n kind: 'C',\n c1x: (2 * x0 + x1) / 3,\n c1y: (2 * y0 + y1) / 3,\n c2x: (x0 + 2 * x1) / 3,\n c2y: (y0 + 2 * y1) / 3,\n x: (x0 + 4 * x1 + x) / 6,\n y: (y0 + 4 * y1 + y) / 6,\n });\n }\n\n const xN1 = bx[n - 2]!;\n const yN1 = by[n - 2]!;\n const xN = bx[n - 1]!;\n const yN = by[n - 1]!;\n out.push({\n kind: 'C',\n c1x: (2 * xN1 + xN) / 3,\n c1y: (2 * yN1 + yN) / 3,\n c2x: (xN1 + 2 * xN) / 3,\n c2y: (yN1 + 2 * yN) / 3,\n x: (xN1 + 5 * xN) / 6,\n y: (yN1 + 5 * yN) / 6,\n });\n out.push({ kind: 'L', x: xN, y: yN });\n\n return out;\n};\n\nfunction clamp01(v: number): number {\n return v < 0 ? 0 : v > 1 ? 1 : v;\n}\n","import type { IPathStyle } from '../../../../specs';\n\ntype LoopPolylineCardinalSide = 'top' | 'right' | 'bottom' | 'left';\ntype LoopPolylineCornerSide =\n | 'top-right' | 'bottom-right' | 'bottom-left' | 'top-left';\ntype LoopPolylineSide = LoopPolylineCardinalSide | LoopPolylineCornerSide;\n\ninterface LoopPolylineOpts {\n /**\n * Where the loop sits relative to the pivot. Two families:\n *\n * **Cardinals** (`top` / `right` / `bottom` / `left`) — the loop is a\n * three-segment U-bracket sticking straight out from one side of the\n * host. Both feet sit on a chord perpendicular to `side` at distance\n * `baseOffset`.\n *\n * **Corners** (`top-right` / `bottom-right` / `bottom-left` /\n * `top-left`) — the loop is a three-segment orthogonal wrap around the\n * named corner of the host. One foot lands on a line parallel to the\n * horizontal edge, the other on a line parallel to the vertical edge;\n * the middle segment runs past the outer corner of the wrap. Use\n * `baseOffsetX` / `baseOffsetY` (or the symmetric fallback\n * `baseOffset`) to position the wrap corner relative to the host\n * silhouette.\n *\n * For arbitrary directions pass a number — radians, screen\n * coordinates (y points down). Numeric `side` always renders the\n * cardinal U-bracket geometry, even when the angle is diagonal.\n * Default `'top'`.\n */\n readonly side?: LoopPolylineSide | number;\n /**\n * Symmetric clearance from the pivot to the host silhouette. For\n * cardinals: distance along `side` from pivot to the foot midpoint.\n * For corners: distance along *both* axes from pivot to the named\n * corner of the silhouette — use `baseOffsetX` / `baseOffsetY` for\n * non-square hosts. Default `28`.\n */\n readonly baseOffset?: number;\n /**\n * Horizontal-axis distance from pivot to silhouette. Only consulted\n * for corner sides; defaults to `baseOffset` when omitted.\n */\n readonly baseOffsetX?: number;\n /**\n * Vertical-axis distance from pivot to silhouette. Only consulted\n * for corner sides; defaults to `baseOffset` when omitted.\n */\n readonly baseOffsetY?: number;\n /**\n * How far each stub extends past the silhouette. For cardinals: both\n * stubs run `stubLength` further along `side` from the feet. For\n * corners: each stub runs `stubLength` further outward (away from the\n * named corner) along its perpendicular axis. Default `30`.\n */\n readonly stubLength?: number;\n /**\n * Foot separation along the silhouette. For cardinals: tangential\n * distance perpendicular to `side` — both feet sit on a chord, one\n * at `-gap/2`, the other at `+gap/2`. For corners: along-edge\n * distance from the named corner of the silhouette to each foot —\n * one foot sits `gap` from the corner along the horizontal edge, the\n * other `gap` along the vertical edge. Default `30`.\n */\n readonly gap?: number;\n}\n\nconst DEFAULT_SIDE: LoopPolylineSide = 'top';\nconst DEFAULT_BASE_OFFSET = 28;\nconst DEFAULT_STUB_LENGTH = 30;\nconst DEFAULT_GAP = 30;\n\nconst CORNER_SIDES = new Set<LoopPolylineSide>([\n 'top-right', 'bottom-right', 'bottom-left', 'top-left',\n]);\n\nfunction sideToAngle(side: LoopPolylineSide | number): number {\n if (typeof side === 'number') return side;\n switch (side) {\n case 'top': return -Math.PI / 2;\n case 'top-right': return -Math.PI / 4;\n case 'right': return 0;\n case 'bottom-right': return Math.PI / 4;\n case 'bottom': return Math.PI / 2;\n case 'bottom-left': return 3 * Math.PI / 4;\n case 'left': return Math.PI;\n case 'top-left': return -3 * Math.PI / 4;\n }\n}\n\n/**\n * Signed unit vector components for each corner. Sign convention:\n * sx = +1 for *-right, -1 for *-left\n * sy = -1 for top-*, +1 for bottom-*\n */\nfunction cornerSigns(side: LoopPolylineCornerSide): { sx: number; sy: number } {\n switch (side) {\n case 'top-right': return { sx: 1, sy: -1 };\n case 'bottom-right': return { sx: 1, sy: 1 };\n case 'bottom-left': return { sx: -1, sy: 1 };\n case 'top-left': return { sx: -1, sy: -1 };\n }\n}\n\n/**\n * Self-loop pathStyle — orthogonal polyline anchored at the first\n * polyline point. Designed for edges where source and target reference\n * the same shape; the router output is `[p, p]` and this style ignores\n * everything after `polyline[0]`.\n *\n * Two geometries dispatch on `side`:\n *\n * **Cardinal U-bracket** (`top` / `right` / `bottom` / `left` or any\n * numeric angle) — three segments. Feet sit on a chord perpendicular\n * to `side` at distance `baseOffset` from the pivot, separated by\n * `gap`. From each foot the path runs `stubLength` further along\n * `side` to the two outer corners, joined by one cross segment.\n *\n * **Corner wrap** (`top-right` / `bottom-right` / `bottom-left` /\n * `top-left`) — four segments. Both feet sit on the host silhouette:\n * one on the horizontal edge `gap` from the named corner, the other\n * on the vertical edge `gap` from the same corner. From each foot the\n * path runs `stubLength` perpendicular to its edge (outward), the two\n * outward stubs are joined by a cross segment past the corner, and the\n * arrow lands flush with the perpendicular edge. The wrap's inner\n * corner sits at `(±baseOffsetX, ±baseOffsetY)` from the pivot.\n *\n * Pair with `router: 'straight'`; the polyline content beyond the first\n * point is ignored.\n *\n * Edge cases:\n * - Polyline shorter than one point: returns `[]`.\n * - Cardinal `gap = 0`: both stubs collapse onto the same line — the\n * loop reads as a single out-and-back spike.\n * - Corner `gap = 0`: both feet land at the corner itself; the wrap\n * degenerates to a closed rectangle whose inner corner touches the\n * silhouette.\n */\nexport const loopPolylinePathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 1) return [];\n const o = opts as LoopPolylineOpts | undefined;\n const side = o?.side ?? DEFAULT_SIDE;\n const baseOffset = o?.baseOffset ?? DEFAULT_BASE_OFFSET;\n const stubLength = o?.stubLength ?? DEFAULT_STUB_LENGTH;\n const gap = o?.gap ?? DEFAULT_GAP;\n const p = polyline[0]!;\n\n // Corner wrap — named corner sides only. Numeric angles always fall\n // through to the cardinal U-bracket geometry, even when the angle is\n // diagonal — callers asking for a literal corner wrap must use the\n // named corner sides.\n if (typeof side === 'string' && CORNER_SIDES.has(side)) {\n const { sx, sy } = cornerSigns(side as LoopPolylineCornerSide);\n const offX = o?.baseOffsetX ?? baseOffset;\n const offY = o?.baseOffsetY ?? baseOffset;\n // Silhouette corner in world coords (the named corner of the host).\n const cornerX = p.x + sx * offX;\n const cornerY = p.y + sy * offY;\n // Foot A — on the horizontal edge, `gap` along it from the corner.\n const ax = cornerX - sx * gap;\n const ay = cornerY;\n // Foot B — on the vertical edge, `gap` along it from the corner.\n const bx = cornerX;\n const by = cornerY - sy * gap;\n // Outer corner of the wrap bracket — `stubLength` past the silhouette\n // in both axes.\n const ox = cornerX + sx * stubLength;\n const oy = cornerY + sy * stubLength;\n // Path: out from horizontal edge, across past the corner, down past\n // the vertical-edge level, in to the vertical edge. Both endpoints\n // sit on the host silhouette so the arrow marker lands flush.\n return [\n { kind: 'M', x: ax, y: ay },\n { kind: 'L', x: ax, y: oy },\n { kind: 'L', x: ox, y: oy },\n { kind: 'L', x: ox, y: by },\n { kind: 'L', x: bx, y: by },\n ];\n }\n\n // Cardinal U-bracket — applies to the four cardinal sides and any\n // numeric angle.\n const angle = sideToAngle(side);\n const ux = Math.cos(angle);\n const uy = Math.sin(angle);\n // Perpendicular to `angle`, rotated 90° anti-clockwise.\n const px = -uy;\n const py = ux;\n // Foot midpoint sits `baseOffset` along the loop direction from pivot.\n const mx = p.x + ux * baseOffset;\n const my = p.y + uy * baseOffset;\n const halfG = gap / 2;\n const sx = mx - px * halfG;\n const sy = my - py * halfG;\n const ex = mx + px * halfG;\n const ey = my + py * halfG;\n const c1x = sx + ux * stubLength;\n const c1y = sy + uy * stubLength;\n const c2x = ex + ux * stubLength;\n const c2y = ey + uy * stubLength;\n return [\n { kind: 'M', x: sx, y: sy },\n { kind: 'L', x: c1x, y: c1y },\n { kind: 'L', x: c2x, y: c2y },\n { kind: 'L', x: ex, y: ey },\n ];\n};\n","import type { IPathStyle, PathCommand } from '../../../../specs';\n\ntype LoopCurveSide =\n | 'top' | 'right' | 'bottom' | 'left'\n | 'top-right' | 'bottom-right' | 'bottom-left' | 'top-left';\n\ninterface LoopCurveOpts {\n /**\n * Which way the petal blooms from the host. Named sides resolve to\n * world-space angles in screen coordinates (y points down):\n *\n * top = -π/2 top-right = -π/4\n * right = 0 bottom-right = π/4\n * bottom = π/2 bottom-left = 3π/4\n * left = π top-left = -3π/4\n *\n * Wins over `angle` when both are provided.\n */\n readonly side?: LoopCurveSide;\n /**\n * Direction the petal blooms from the host, in radians. `0` points\n * right, `π/2` points down (screen coords — y grows downward),\n * `-π/2` points up. Default `-π/2` — petal blooms above the host.\n * Ignored when `side` is set.\n */\n readonly angle?: number;\n /**\n * How far the balloon tip sits past the chord between the two feet,\n * measured along `angle` from the chord midpoint. The geometric apex\n * of the curve lands at roughly `0.75 * radius` past the chord\n * (cubic-bezier control-arm pull falls short of the geometric\n * maximum). Default `40`.\n */\n readonly radius?: number;\n /**\n * Belly half-spread of the balloon — distance from the tip along the\n * chord direction to each control point. When `bulge > clen/2` (half\n * the chord length) the control points lie past the feet in chord\n * direction, splaying the curve outward → balloon. When\n * `bulge = clen/2` the controls sit directly above the feet → U\n * (parallel-sided hairpin). When `bulge < clen/2` controls converge\n * toward the tip → teardrop. Default `radius` (round balloon).\n */\n readonly bulge?: number;\n /**\n * Used only in **single-pivot mode**, i.e. when the polyline's first\n * and last points coincide (source and target endpoints resolved to\n * the same world point — typical when both use the `center` anchor).\n * Distance from the pivot to the foot midpoint, measured along\n * `angle`. Ignored when the polyline has two distinct endpoints\n * (two-foot mode), since the feet are then taken directly from the\n * polyline. Default `28`.\n */\n readonly baseOffset?: number;\n /**\n * Used only in **single-pivot mode**. Tangential separation between\n * the two feet, perpendicular to `angle`. Ignored in two-foot mode.\n * Default `12`.\n */\n readonly width?: number;\n /**\n * Used only in **single-pivot mode**. World-space shift of the foot\n * midpoint, applied before `baseOffset` is added along `angle`. Lets\n * callers land the petal on a specific edge/corner when working\n * from a single `center` anchor. Ignored in two-foot mode (anchors\n * already position the feet). Default `{ dx: 0, dy: 0 }`.\n */\n readonly pivotOffset?: { readonly dx: number; readonly dy: number };\n}\n\nconst DEFAULT_ANGLE = -Math.PI / 2; // petal points up\nconst DEFAULT_BASE_OFFSET = 28;\nconst DEFAULT_RADIUS = 40;\nconst DEFAULT_WIDTH = 12;\n// Below this chord length we treat the two polyline endpoints as\n// coincident and fall back to single-pivot mode. 0.5 world units is\n// well below visible — anything smaller is sub-pixel jitter.\nconst COINCIDENT_EPS = 0.5;\n\n/**\n * Named loop-curve shape presets. Each preset carries the four\n * profile-shaping opts (`baseOffset`, `radius`, `width`, `bulge`); the\n * caller fills in placement (`side` / `angle`, `pivotOffset`) per\n * instance. Spread into `pathStyleOpts`:\n *\n * pathStyleOpts: { ...LOOP_CURVE_PRESETS.balloon, side: 'top' }\n *\n * Definitions:\n * - `balloon` — fat puffed belly. `bulge >> width/2` → controls\n * splay wide; `bulge > radius` → belly bulges past the tip.\n * - `teardrop` — slender pointed petal. `radius >> bulge`, narrow\n * `width` → long axis with controls converging toward the tip.\n * - `ring` — near-circular loop. `radius ≈ bulge`, modest neck.\n * - `hairpin` — parallel-sided U (legacy). `bulge ≈ width/2` →\n * controls sit directly above the feet, no flare.\n */\nexport const LOOP_CURVE_PRESETS = {\n balloon: { baseOffset: 2, radius: 22, width: 6, bulge: 26 },\n teardrop: { baseOffset: 2, radius: 34, width: 4, bulge: 8 },\n ring: { baseOffset: 2, radius: 20, width: 10, bulge: 20 },\n hairpin: { baseOffset: 2, radius: 28, width: 8, bulge: 4 },\n} as const satisfies Record<string, Required<Pick<LoopCurveOpts, 'baseOffset' | 'radius' | 'width' | 'bulge'>>>;\n\nexport type LoopCurvePresetName = keyof typeof LOOP_CURVE_PRESETS;\n\nfunction sideToAngle(side: LoopCurveSide): number {\n switch (side) {\n case 'top': return -Math.PI / 2;\n case 'top-right': return -Math.PI / 4;\n case 'right': return 0;\n case 'bottom-right': return Math.PI / 4;\n case 'bottom': return Math.PI / 2;\n case 'bottom-left': return 3 * Math.PI / 4;\n case 'left': return Math.PI;\n case 'top-left': return -3 * Math.PI / 4;\n }\n}\n\n/**\n * Self-loop pathStyle — single cubic Bézier \"balloon / petal / teardrop\"\n * drawn between two foot points. Mirrors AntV G6's `loop-curve` placement\n * model: cardinal placements (`top`, `right`, `bottom`, `left`) put both\n * feet on the same edge of the host; diagonal placements (`top-right`,\n * `bottom-right`, `bottom-left`, `top-left`) put the two feet on the two\n * adjacent edges that meet at the named corner.\n *\n * The path style runs in one of two modes depending on the polyline it\n * receives:\n *\n * - **Two-foot mode** (preferred): when `polyline[0]` and `polyline[N-1]`\n * are distinct (chord length > {@link COINCIDENT_EPS}), they are used\n * as the two feet. The caller positions them via anchors — typically\n * an `edge-port` anchor on the source endpoint and another on the\n * target endpoint. The path style only shapes the curve between them.\n *\n * - **Single-pivot mode** (legacy): when the two endpoints coincide\n * (typical when both source and target use the `center` anchor on the\n * same shape), the feet are synthesised from `pivotOffset`,\n * `baseOffset` and `width`. `baseOffset` shifts the foot midpoint\n * along `angle`; `width` separates the feet perpendicular to it.\n * Useful when no edge-port anchor is configured.\n *\n * Geometry (both modes): given two feet `start` and `end`, the tip sits\n * at `chordMid + bloom * radius`, and the two cubic control points are\n * placed at `tip ± chordDir * bulge`. `bulge > chordLen/2` → balloon\n * (controls splayed outward past the feet); `bulge = chordLen/2` →\n * parallel-sided U; `bulge < chordLen/2` → teardrop (controls converge).\n *\n * Pair with `router: 'straight'`. The polyline content between\n * `polyline[0]` and `polyline[N-1]` is ignored.\n *\n * Edge cases:\n * - Polyline shorter than one point: returns `[]`.\n * - `width = 0` in single-pivot mode: feet coincide → closed teardrop\n * cusp; the arrow marker lands on the start point.\n */\nexport const loopCurvePathStyle: IPathStyle = (polyline, opts) => {\n if (polyline.length < 1) return [];\n const o = opts as LoopCurveOpts | undefined;\n const angle = o?.side !== undefined ? sideToAngle(o.side) : (o?.angle ?? DEFAULT_ANGLE);\n const radius = o?.radius ?? DEFAULT_RADIUS;\n const bulge = o?.bulge ?? radius;\n\n const ux = Math.cos(angle);\n const uy = Math.sin(angle);\n\n // Resolve the two feet. Two-foot mode honours the polyline's start /\n // end directly (positioned by anchors); single-pivot mode synthesises\n // them from baseOffset + width.\n const start = polyline[0]!;\n const end = polyline[polyline.length - 1] ?? start;\n const chordDx = end.x - start.x;\n const chordDy = end.y - start.y;\n const chordLen = Math.hypot(chordDx, chordDy);\n\n let sx: number;\n let sy: number;\n let ex: number;\n let ey: number;\n\n if (chordLen > COINCIDENT_EPS) {\n sx = start.x; sy = start.y;\n ex = end.x; ey = end.y;\n } else {\n // Single-pivot mode — derive feet from baseOffset/width/pivotOffset.\n const baseOffset = o?.baseOffset ?? DEFAULT_BASE_OFFSET;\n const width = o?.width ?? DEFAULT_WIDTH;\n const pivotDx = o?.pivotOffset?.dx ?? 0;\n const pivotDy = o?.pivotOffset?.dy ?? 0;\n // Foot midpoint = pivot + pivotOffset + baseOffset along angle.\n const mx = start.x + pivotDx + ux * baseOffset;\n const my = start.y + pivotDy + uy * baseOffset;\n // Feet split perpendicular to angle by ±width/2.\n const px = -uy;\n const py = ux;\n const halfW = width / 2;\n sx = mx - px * halfW; sy = my - py * halfW;\n ex = mx + px * halfW; ey = my + py * halfW;\n }\n\n // Place controls. Tip sits `radius` along bloom direction from chord\n // midpoint. Controls flank the tip ±`bulge` along the chord direction\n // (start→end). When `bulge` exceeds the chord half-length, controls\n // splay past the feet → balloon.\n const midx = (sx + ex) / 2;\n const midy = (sy + ey) / 2;\n const tipx = midx + ux * radius;\n const tipy = midy + uy * radius;\n\n // Chord direction; falls back to perpendicular-to-bloom when chord is\n // degenerate (single-pivot mode with width = 0 — both feet identical).\n let cdx: number;\n let cdy: number;\n const realChordLen = Math.hypot(ex - sx, ey - sy);\n if (realChordLen > COINCIDENT_EPS) {\n cdx = (ex - sx) / realChordLen;\n cdy = (ey - sy) / realChordLen;\n } else {\n cdx = -uy;\n cdy = ux;\n }\n\n const c1x = tipx - cdx * bulge;\n const c1y = tipy - cdy * bulge;\n const c2x = tipx + cdx * bulge;\n const c2y = tipy + cdy * bulge;\n\n const out: PathCommand[] = [\n { kind: 'M', x: sx, y: sy },\n { kind: 'C', c1x, c1y, c2x, c2y, x: ex, y: ey },\n ];\n return out;\n};\n","/**\n * Path-walking utilities. Used by:\n * - `PrimitivesRenderer.hitTest` — needs a polyline approximation of the\n * path for distance-to-segment checks.\n * - `ConnectorBase.paintMarkers` — needs the tangent angle at the source /\n * target endpoints to orient marker shapes.\n * - Any future connector decoration that walks arc length (e.g. label-along-\n * path). Static / glow / halo decorations don't sample — they call\n * `connector.paintInto(...)` for native-rendered silhouettes.\n *\n * For v0 the only router is `straight` (just `[M, L]`), so the sampling /\n * tangent paths are degenerate. The functions are written to handle the full\n * `Path` type so additional router kinds drop in without changes.\n */\n\nimport type { Path, PathCommand, Point, Rect, Vec2 } from '../../../specs';\n\n/** Substeps per Q/C segment when densifying. Higher = smoother polyline. */\nconst QUAD_STEPS = 12;\nconst CUBIC_STEPS = 16;\n\n/**\n * Densify a `Path` into a flat polyline. Lines emit two endpoints per\n * segment; quadratic / cubic curves are sampled with fixed substep counts.\n * Returns at least the move-to point when the path has only one command.\n */\nexport function samplePath(path: Path): Point[] {\n const out: Point[] = [];\n if (path.length === 0) return out;\n\n let cx = 0;\n let cy = 0;\n\n for (const cmd of path) {\n switch (cmd.kind) {\n case 'M':\n out.push({ x: cmd.x, y: cmd.y });\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'L':\n out.push({ x: cmd.x, y: cmd.y });\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'Q':\n for (let i = 1; i <= QUAD_STEPS; i++) {\n const t = i / QUAD_STEPS;\n const mt = 1 - t;\n out.push({\n x: mt * mt * cx + 2 * mt * t * cmd.cx + t * t * cmd.x,\n y: mt * mt * cy + 2 * mt * t * cmd.cy + t * t * cmd.y,\n });\n }\n cx = cmd.x;\n cy = cmd.y;\n break;\n case 'C':\n for (let i = 1; i <= CUBIC_STEPS; i++) {\n const t = i / CUBIC_STEPS;\n const mt = 1 - t;\n out.push({\n x: mt * mt * mt * cx + 3 * mt * mt * t * cmd.c1x + 3 * mt * t * t * cmd.c2x + t * t * t * cmd.x,\n y: mt * mt * mt * cy + 3 * mt * mt * t * cmd.c1y + 3 * mt * t * t * cmd.c2y + t * t * t * cmd.y,\n });\n }\n cx = cmd.x;\n cy = cmd.y;\n break;\n }\n }\n\n return out;\n}\n\n/**\n * Compute the tangent unit vector at `t ∈ [0, 1]` along the path.\n * For v0 we only need `t = 0` (source) and `t = 1` (target) for marker\n * orientation; intermediate `t` is sampled via `samplePath` for now.\n */\nexport function tangentAt(path: Path, t: number): Vec2 {\n if (path.length < 2) return { x: 1, y: 0 };\n\n if (t <= 0) return tangentAtStart(path);\n if (t >= 1) return tangentAtEnd(path);\n\n // Approximate intermediate t via sampled polyline.\n const samples = samplePath(path);\n if (samples.length < 2) return { x: 1, y: 0 };\n const idx = Math.min(samples.length - 2, Math.floor(t * (samples.length - 1)));\n const a = samples[idx]!;\n const b = samples[idx + 1]!;\n return normalize(b.x - a.x, b.y - a.y);\n}\n\n/**\n * Combined point + unit-tangent sample at parameter `t ∈ [0, 1]` along the\n * path. Used by labels-along-path and any other decoration that needs both\n * the location and the local direction at the same parameter (e.g. for\n * `autoRotate`). Cheaper than calling `samplePath` + `tangentAt` separately\n * because it walks the polyline once.\n *\n * `t` is fractional in arc-length space — the function picks the segment of\n * the densified polyline whose cumulative length most closely matches `t *\n * totalLength` and linearly interpolates inside it. For most practical path\n * kinds this matches an analytical sample to within a pixel; orthogonal\n * paths reproduce segment endpoints exactly.\n */\nexport function samplePathAt(path: Path, t: number): { point: Point; tangent: Vec2 } {\n const samples = samplePath(path);\n if (samples.length === 0) return { point: { x: 0, y: 0 }, tangent: { x: 1, y: 0 } };\n if (samples.length === 1) return { point: samples[0]!, tangent: { x: 1, y: 0 } };\n\n // Compute cumulative arc length once.\n let total = 0;\n const cum = new Array<number>(samples.length);\n cum[0] = 0;\n for (let i = 1; i < samples.length; i++) {\n const a = samples[i - 1]!;\n const b = samples[i]!;\n total += Math.hypot(b.x - a.x, b.y - a.y);\n cum[i] = total;\n }\n\n if (total <= 0) {\n return { point: samples[0]!, tangent: { x: 1, y: 0 } };\n }\n\n const clamped = t <= 0 ? 0 : t >= 1 ? 1 : t;\n const target = clamped * total;\n\n // Binary search for the segment containing `target`.\n let lo = 0;\n let hi = samples.length - 1;\n while (lo < hi - 1) {\n const mid = (lo + hi) >>> 1;\n if (cum[mid]! <= target) lo = mid;\n else hi = mid;\n }\n const a = samples[lo]!;\n const b = samples[lo + 1]!;\n const segLen = cum[lo + 1]! - cum[lo]!;\n const u = segLen > 0 ? (target - cum[lo]!) / segLen : 0;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n return {\n point: { x: a.x + dx * u, y: a.y + dy * u },\n tangent: normalize(dx, dy),\n };\n}\n\n/** AABB of the path's anchor + control points. Used by hit-test bbox indexing. */\nexport function pathBounds(path: Path): Rect {\n if (path.length === 0) return { x: 0, y: 0, width: 0, height: 0 };\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const visit = (x: number, y: number): void => {\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n };\n for (const cmd of path) {\n switch (cmd.kind) {\n case 'M':\n case 'L':\n visit(cmd.x, cmd.y);\n break;\n case 'Q':\n visit(cmd.cx, cmd.cy);\n visit(cmd.x, cmd.y);\n break;\n case 'C':\n visit(cmd.c1x, cmd.c1y);\n visit(cmd.c2x, cmd.c2y);\n visit(cmd.x, cmd.y);\n break;\n }\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/**\n * Pull the path's start / end anchors inward by the requested arc-length\n * insets so the connector body stops short of where its markers will be\n * drawn. Markers themselves still anchor at the *original* endpoints (their\n * tips touch the target) — only the body is shortened.\n *\n * Correctness:\n * - `L` segments are trimmed in closed form (exact).\n * - `Q` / `C` segments are trimmed by walking arc length over a fine\n * sub-step table, refining the parameter `t` between bracketing samples,\n * and **De Casteljau subdividing** the curve at `t`. The kept half is\n * emitted as a new `Q` / `C` command, preserving correct curvature on\n * tight bends — chord-along-tangent approximation would diverge.\n * - When an inset exceeds the trailing segment's arc length, the segment\n * is consumed entirely and the trim continues into the prior segment.\n *\n * v0 only ships the `straight` router, so curve trimming is forward-looking\n * scaffolding for the upcoming `bezier` / `orthogonal` routers.\n */\nexport function trimPathEnds(path: Path, startInset: number, endInset: number): Path {\n if (path.length < 2) return path;\n if (startInset <= 0 && endInset <= 0) return path;\n\n let result: PathCommand[] = path.slice();\n\n if (endInset > 0) {\n result = trimPathEnd(result, endInset);\n if (result.length < 2) return result;\n }\n\n if (startInset > 0) {\n result = trimPathStart(result, startInset);\n }\n\n return result;\n}\n\n// ─── Internals ─────────────────────────────────────────────────────────────\n\n/** Substeps used during arc-length trim — finer than display sampling. */\nconst TRIM_QUAD_STEPS = 24;\nconst TRIM_CUBIC_STEPS = 32;\n\n/**\n * Trim `remaining` pixels from the end of the path, consuming whole segments\n * when they're shorter than what's left to remove. Returns a fresh\n * `PathCommand[]`. If the inset exceeds the path's total length, returns the\n * leading `M` (degenerate but well-formed).\n */\nfunction trimPathEnd(path: PathCommand[], remaining: number): PathCommand[] {\n let work = path.slice();\n while (work.length >= 2 && remaining > 0) {\n const tail = work[work.length - 1]!;\n const prev = anchorBefore(work, work.length - 1);\n const segLen = segmentLength(prev, tail);\n\n if (segLen <= 0) {\n // Degenerate segment — drop it and continue.\n work.pop();\n continue;\n }\n\n if (remaining >= segLen) {\n // Consume the whole segment and continue trimming into the prior one.\n remaining -= segLen;\n work.pop();\n continue;\n }\n\n // Partial trim: clip the tail at arc-length distance `segLen - remaining`\n // from `prev`. The result is a fresh segment whose end anchor sits at\n // that interior point.\n const keepLen = segLen - remaining;\n work[work.length - 1] = clipSegmentEnd(prev, tail, keepLen);\n remaining = 0;\n }\n return work;\n}\n\n/**\n * Trim `remaining` pixels from the start of the path. Walks forward from\n * the leading `M`, dropping commands whose arc length is fully consumed and\n * partially clipping the first segment that survives.\n */\nfunction trimPathStart(path: PathCommand[], remaining: number): PathCommand[] {\n if (path.length < 2) return path;\n const first = path[0];\n if (!first || first.kind !== 'M') return path;\n\n let cursor: Point = { x: first.x, y: first.y };\n let i = 1;\n while (i < path.length && remaining > 0) {\n const seg = path[i]!;\n const segLen = segmentLength(cursor, seg);\n\n if (segLen <= 0) {\n // Degenerate — advance cursor (without dropping; preserves anchor flow).\n cursor = endpointOf(seg, cursor);\n i++;\n continue;\n }\n\n if (remaining >= segLen) {\n remaining -= segLen;\n cursor = endpointOf(seg, cursor);\n i++;\n continue;\n }\n\n // Partial trim: split at arc-length `remaining` from cursor and keep\n // the back half. The new `M` lands at the split point.\n const split = clipSegmentStart(cursor, seg, remaining);\n const head: PathCommand[] = [{ kind: 'M', x: split.start.x, y: split.start.y }, split.tail];\n return head.concat(path.slice(i + 1));\n }\n\n // The inset consumed every segment — collapse to a bare moveTo at the\n // last anchor we walked through.\n return [{ kind: 'M', x: cursor.x, y: cursor.y }];\n}\n\n/**\n * Replace `seg` with a new segment that runs from `start` to the point on\n * `seg` at arc length `keepLen` (measured from `start`). For `Q` / `C`\n * segments, sub-divides via De Casteljau at the parameter t found by walking\n * the sampled arc-length table.\n */\nfunction clipSegmentEnd(start: Point, seg: PathCommand, keepLen: number): PathCommand {\n switch (seg.kind) {\n case 'L': {\n const dx = seg.x - start.x;\n const dy = seg.y - start.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) return seg;\n const u = keepLen / len;\n return { kind: 'L', x: start.x + dx * u, y: start.y + dy * u };\n }\n case 'Q': {\n const t = quadParamAtArcLength(start, seg, keepLen);\n const split = subdivideQuad(start, seg, t);\n return { kind: 'Q', cx: split.head.cx, cy: split.head.cy, x: split.head.x, y: split.head.y };\n }\n case 'C': {\n const t = cubicParamAtArcLength(start, seg, keepLen);\n const split = subdivideCubic(start, seg, t);\n return {\n kind: 'C',\n c1x: split.head.c1x, c1y: split.head.c1y,\n c2x: split.head.c2x, c2y: split.head.c2y,\n x: split.head.x, y: split.head.y,\n };\n }\n case 'M':\n return seg;\n }\n}\n\n/**\n * Split `seg` at arc length `dropLen` from `start` and return both halves,\n * along with the new start anchor for the back half. Used by start-trim.\n */\nfunction clipSegmentStart(\n start: Point,\n seg: PathCommand,\n dropLen: number,\n): { start: Point; tail: PathCommand } {\n switch (seg.kind) {\n case 'L': {\n const dx = seg.x - start.x;\n const dy = seg.y - start.y;\n const len = Math.hypot(dx, dy);\n if (len === 0) return { start, tail: seg };\n const u = dropLen / len;\n const splitPoint = { x: start.x + dx * u, y: start.y + dy * u };\n return { start: splitPoint, tail: { kind: 'L', x: seg.x, y: seg.y } };\n }\n case 'Q': {\n const t = quadParamAtArcLength(start, seg, dropLen);\n const split = subdivideQuad(start, seg, t);\n return {\n start: { x: split.head.x, y: split.head.y },\n tail: { kind: 'Q', cx: split.tail.cx, cy: split.tail.cy, x: split.tail.x, y: split.tail.y },\n };\n }\n case 'C': {\n const t = cubicParamAtArcLength(start, seg, dropLen);\n const split = subdivideCubic(start, seg, t);\n return {\n start: { x: split.head.x, y: split.head.y },\n tail: {\n kind: 'C',\n c1x: split.tail.c1x, c1y: split.tail.c1y,\n c2x: split.tail.c2x, c2y: split.tail.c2y,\n x: split.tail.x, y: split.tail.y,\n },\n };\n }\n case 'M':\n return { start, tail: seg };\n }\n}\n\n/**\n * Total arc length of a single segment from `start` to its endpoint.\n * Straight segments use Euclidean distance; curved segments accumulate\n * chord lengths over a fixed substep count.\n */\nfunction segmentLength(start: Point, seg: PathCommand): number {\n switch (seg.kind) {\n case 'L':\n return Math.hypot(seg.x - start.x, seg.y - start.y);\n case 'Q': {\n let total = 0;\n let px = start.x, py = start.y;\n for (let i = 1; i <= TRIM_QUAD_STEPS; i++) {\n const t = i / TRIM_QUAD_STEPS;\n const mt = 1 - t;\n const x = mt * mt * start.x + 2 * mt * t * seg.cx + t * t * seg.x;\n const y = mt * mt * start.y + 2 * mt * t * seg.cy + t * t * seg.y;\n total += Math.hypot(x - px, y - py);\n px = x; py = y;\n }\n return total;\n }\n case 'C': {\n let total = 0;\n let px = start.x, py = start.y;\n for (let i = 1; i <= TRIM_CUBIC_STEPS; i++) {\n const t = i / TRIM_CUBIC_STEPS;\n const mt = 1 - t;\n const x = mt * mt * mt * start.x + 3 * mt * mt * t * seg.c1x + 3 * mt * t * t * seg.c2x + t * t * t * seg.x;\n const y = mt * mt * mt * start.y + 3 * mt * mt * t * seg.c1y + 3 * mt * t * t * seg.c2y + t * t * t * seg.y;\n total += Math.hypot(x - px, y - py);\n px = x; py = y;\n }\n return total;\n }\n case 'M':\n return 0;\n }\n}\n\nfunction endpointOf(seg: PathCommand, fallback: Point): Point {\n if (seg.kind === 'M' || seg.kind === 'L' || seg.kind === 'Q' || seg.kind === 'C') {\n return { x: seg.x, y: seg.y };\n }\n return fallback;\n}\n\n/** Walk the quadratic and find `t` where cumulative arc length ≈ targetLen. */\nfunction quadParamAtArcLength(\n start: Point,\n seg: { cx: number; cy: number; x: number; y: number },\n targetLen: number,\n): number {\n let prevX = start.x, prevY = start.y;\n let acc = 0;\n for (let i = 1; i <= TRIM_QUAD_STEPS; i++) {\n const t = i / TRIM_QUAD_STEPS;\n const mt = 1 - t;\n const x = mt * mt * start.x + 2 * mt * t * seg.cx + t * t * seg.x;\n const y = mt * mt * start.y + 2 * mt * t * seg.cy + t * t * seg.y;\n const step = Math.hypot(x - prevX, y - prevY);\n if (acc + step >= targetLen) {\n const frac = step === 0 ? 0 : (targetLen - acc) / step;\n const tPrev = (i - 1) / TRIM_QUAD_STEPS;\n return tPrev + (t - tPrev) * frac;\n }\n acc += step;\n prevX = x; prevY = y;\n }\n return 1;\n}\n\n/** Walk the cubic and find `t` where cumulative arc length ≈ targetLen. */\nfunction cubicParamAtArcLength(\n start: Point,\n seg: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number },\n targetLen: number,\n): number {\n let prevX = start.x, prevY = start.y;\n let acc = 0;\n for (let i = 1; i <= TRIM_CUBIC_STEPS; i++) {\n const t = i / TRIM_CUBIC_STEPS;\n const mt = 1 - t;\n const x = mt * mt * mt * start.x + 3 * mt * mt * t * seg.c1x + 3 * mt * t * t * seg.c2x + t * t * t * seg.x;\n const y = mt * mt * mt * start.y + 3 * mt * mt * t * seg.c1y + 3 * mt * t * t * seg.c2y + t * t * t * seg.y;\n const step = Math.hypot(x - prevX, y - prevY);\n if (acc + step >= targetLen) {\n const frac = step === 0 ? 0 : (targetLen - acc) / step;\n const tPrev = (i - 1) / TRIM_CUBIC_STEPS;\n return tPrev + (t - tPrev) * frac;\n }\n acc += step;\n prevX = x; prevY = y;\n }\n return 1;\n}\n\n/**\n * De Casteljau subdivision for a quadratic Bézier at parameter `t`.\n * Returns the two halves: `head` runs from `start` to the split point,\n * `tail` runs from the split point to the original endpoint. Each half is\n * itself a valid quadratic.\n */\nfunction subdivideQuad(\n start: Point,\n seg: { cx: number; cy: number; x: number; y: number },\n t: number,\n): {\n head: { cx: number; cy: number; x: number; y: number };\n tail: { cx: number; cy: number; x: number; y: number };\n} {\n const p0 = start, p1 = { x: seg.cx, y: seg.cy }, p2 = { x: seg.x, y: seg.y };\n const a = lerp(p0, p1, t);\n const b = lerp(p1, p2, t);\n const m = lerp(a, b, t);\n return {\n head: { cx: a.x, cy: a.y, x: m.x, y: m.y },\n tail: { cx: b.x, cy: b.y, x: p2.x, y: p2.y },\n };\n}\n\n/**\n * De Casteljau subdivision for a cubic Bézier at parameter `t`.\n * Returns the two halves as cubic segments.\n */\nfunction subdivideCubic(\n start: Point,\n seg: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number },\n t: number,\n): {\n head: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number };\n tail: { c1x: number; c1y: number; c2x: number; c2y: number; x: number; y: number };\n} {\n const p0 = start;\n const p1 = { x: seg.c1x, y: seg.c1y };\n const p2 = { x: seg.c2x, y: seg.c2y };\n const p3 = { x: seg.x, y: seg.y };\n const a = lerp(p0, p1, t);\n const b = lerp(p1, p2, t);\n const c = lerp(p2, p3, t);\n const d = lerp(a, b, t);\n const e = lerp(b, c, t);\n const m = lerp(d, e, t);\n return {\n head: { c1x: a.x, c1y: a.y, c2x: d.x, c2y: d.y, x: m.x, y: m.y },\n tail: { c1x: e.x, c1y: e.y, c2x: c.x, c2y: c.y, x: p3.x, y: p3.y },\n };\n}\n\nfunction lerp(a: Point, b: Point, t: number): Point {\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };\n}\n\nfunction tangentAtStart(path: Path): Vec2 {\n // Find the first non-M command; tangent points from M's anchor toward it.\n const m = path[0];\n if (!m || m.kind !== 'M') return { x: 1, y: 0 };\n const next = path[1];\n if (!next) return { x: 1, y: 0 };\n switch (next.kind) {\n case 'L': {\n const to = distinctAnchorAfter(path, 1, m);\n return normalize(to.x - m.x, to.y - m.y);\n }\n case 'Q':\n return normalize(next.cx - m.x, next.cy - m.y);\n case 'C':\n return normalize(next.c1x - m.x, next.c1y - m.y);\n default:\n return { x: 1, y: 0 };\n }\n}\n\nfunction tangentAtEnd(path: Path): Vec2 {\n const last = path[path.length - 1];\n if (!last) return { x: 1, y: 0 };\n // Need the prior point (or control point) to compute the incoming tangent.\n const prevAnchor = anchorBefore(path, path.length - 1);\n switch (last.kind) {\n case 'M':\n return { x: 1, y: 0 };\n case 'L': {\n // Walk back to the last *distinct* anchor rather than trusting the\n // immediately-preceding one — see `distinctAnchorBefore`.\n const from = distinctAnchorBefore(path, path.length - 1, last);\n return normalize(last.x - from.x, last.y - from.y);\n }\n case 'Q': {\n // Tangent at t=1 of a quadratic is 2·(P2 − P1). Degenerate when the\n // control point coincides with the endpoint — walk back one leg.\n const dx = last.x - last.cx;\n const dy = last.y - last.cy;\n const chordDx = last.x - prevAnchor.x;\n const chordDy = last.y - prevAnchor.y;\n if (isDegenerateLeg(dx, dy, chordDx, chordDy)) {\n return normalize(chordDx, chordDy);\n }\n return normalize(dx, dy);\n }\n case 'C': {\n // Tangent at t=1 of a cubic is 3·(P3 − P2). When the c2 → endpoint\n // leg is vanishingly short relative to the c1 → c2 leg (e.g. a polar\n // d3.linkRadial curve whose endpoints sit at near-equal radii from\n // the polar origin), that direction is ill-conditioned and bears no\n // resemblance to the curve's visual approach. Fall back to the\n // c1 → endpoint direction, which carries the dominant angular sweep.\n const dx = last.x - last.c2x;\n const dy = last.y - last.c2y;\n const c1dx = last.x - last.c1x;\n const c1dy = last.y - last.c1y;\n if (isDegenerateLeg(dx, dy, c1dx, c1dy)) {\n if (c1dx !== 0 || c1dy !== 0) return normalize(c1dx, c1dy);\n return normalize(last.x - prevAnchor.x, last.y - prevAnchor.y);\n }\n return normalize(dx, dy);\n }\n }\n}\n\n// A terminal Bézier handle is \"degenerate\" when its length is less than 1%\n// of the preceding control-polygon leg. Compared squared to avoid sqrts.\nfunction isDegenerateLeg(\n legDx: number, legDy: number,\n refDx: number, refDy: number,\n): boolean {\n const legSq = legDx * legDx + legDy * legDy;\n const refSq = refDx * refDx + refDy * refDy;\n return refSq > 0 && legSq * 10000 < refSq;\n}\n\nfunction anchorBefore(path: Path, idx: number): Point {\n // Return the anchor point reached after executing path[0..idx-1].\n let x = 0, y = 0;\n for (let i = 0; i < idx; i++) {\n const c: PathCommand = path[i]!;\n if (c.kind === 'M' || c.kind === 'L' || c.kind === 'Q' || c.kind === 'C') {\n x = c.x;\n y = c.y;\n }\n }\n return { x, y };\n}\n\n/**\n * Nearest anchor **before** `idx` that is not coincident with `to`.\n *\n * A zero-length terminal segment is easy to produce: any layout that pins an\n * endpoint to the same point it already emitted as its final waypoint leaves\n * two identical anchors at the end of the polyline. Differencing those yields\n * `(0, 0)`, and {@link normalize} then answers its `{ x: 1, y: 0 }` fallback —\n * so a marker silently points due east instead of along the path, which reads\n * as an arrowhead at the wrong angle (and, against a node that paints above\n * connectors, as a half-occluded one). Walking back to the last distinct\n * anchor keeps the direction honest without changing any non-degenerate case.\n *\n * Falls back to {@link anchorBefore} when every prior anchor is coincident —\n * a genuinely zero-length path, where any direction is equally meaningless.\n */\nfunction distinctAnchorBefore(path: Path, idx: number, to: Point): Point {\n for (let i = idx - 1; i >= 0; i--) {\n const c: PathCommand = path[i]!;\n if (c.kind !== 'M' && c.kind !== 'L' && c.kind !== 'Q' && c.kind !== 'C') continue;\n if (c.x !== to.x || c.y !== to.y) return { x: c.x, y: c.y };\n }\n return anchorBefore(path, idx);\n}\n\n/** Mirror of {@link distinctAnchorBefore} for the leading tangent. */\nfunction distinctAnchorAfter(path: Path, idx: number, from: Point): Point {\n for (let i = idx; i < path.length; i++) {\n const c: PathCommand = path[i]!;\n if (c.kind !== 'M' && c.kind !== 'L' && c.kind !== 'Q' && c.kind !== 'C') continue;\n if (c.x !== from.x || c.y !== from.y) return { x: c.x, y: c.y };\n }\n return from;\n}\n\nfunction normalize(dx: number, dy: number): Vec2 {\n const len = Math.hypot(dx, dy);\n if (len === 0) return { x: 1, y: 0 };\n return { x: dx / len, y: dy / len };\n}\n\n/**\n * Squared minimum distance from `(px, py)` to any segment of the polyline.\n * Squared (no sqrt) so callers can compare against a squared tolerance —\n * faster + branch-free for the common no-hit case.\n */\nexport function distanceToPolylineSq(\n poly: ReadonlyArray<Point>,\n px: number,\n py: number,\n): number {\n if (poly.length < 2) return Infinity;\n let best = Infinity;\n for (let i = 0; i < poly.length - 1; i++) {\n const a = poly[i]!;\n const b = poly[i + 1]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const lenSq = dx * dx + dy * dy;\n let t = lenSq === 0 ? 0 : ((px - a.x) * dx + (py - a.y) * dy) / lenSq;\n if (t < 0) t = 0;\n else if (t > 1) t = 1;\n const cx = a.x + dx * t;\n const cy = a.y + dy * t;\n const ex = px - cx;\n const ey = py - cy;\n const d = ex * ex + ey * ey;\n if (d < best) best = d;\n }\n return best;\n}\n","/**\n * Pure placement math for badges. Given the host's world-space AABB and the\n * badge's local-space AABB, resolve the world-space `(x, y)` to put on the\n * badge spec so that a chosen point on the badge's AABB lands at a chosen\n * point on the host's AABB (plus an optional pixel offset).\n *\n * No Pixi imports. Trivially testable.\n *\n * The maths splits cleanly along two axes:\n * 1. **Host anchor** — which point on the host AABB is the target. Driven by\n * `BadgePlacement` (8 named points around the host).\n * 2. **Badge origin** — which point on the badge AABB lands at that anchor.\n * Driven by the optional `origin` field. Defaults to the *mirror* of the\n * placement so the badge sits fully outside the host edge.\n */\n\nimport type { Rect } from '../../../specs';\nimport type { BadgeOptions, BadgePlacement, NamedBadgePlacement } from './types';\n\n/**\n * Returns the world-space anchor point for `placement`. Named placements\n * resolve against `hostBounds` (corner or edge midpoint of the AABB); the\n * raw `{ x, y }` variant is the world-space point itself, with `hostBounds`\n * ignored.\n */\nexport function placementToHostAnchor(\n hostBounds: Rect,\n placement: BadgePlacement,\n): { x: number; y: number } {\n if (typeof placement === 'object') {\n return { x: placement.x, y: placement.y };\n }\n return namedPlacementToAnchor(hostBounds, placement);\n}\n\n/**\n * Returns the world-space point on `bounds` named by a {@link\n * NamedBadgePlacement}. Edge names sit at the midpoint of that edge; corner\n * names at the corner. Used by both host-anchor resolution and badge-origin\n * resolution (with the badge's local AABB as the bounds).\n */\nfunction namedPlacementToAnchor(\n bounds: Rect,\n placement: NamedBadgePlacement,\n): { x: number; y: number } {\n const { x, y, width: w, height: h } = bounds;\n switch (placement) {\n case 'top': return { x: x + w / 2, y };\n case 'bottom': return { x: x + w / 2, y: y + h };\n case 'left': return { x, y: y + h / 2 };\n case 'right': return { x: x + w, y: y + h / 2 };\n case 'top-left': return { x, y };\n case 'top-right': return { x: x + w, y };\n case 'bottom-left': return { x, y: y + h };\n case 'bottom-right': return { x: x + w, y: y + h };\n }\n}\n\n/**\n * Returns the point on the badge's local AABB that should land at the host\n * anchor, given the chosen origin. The default (omitted origin) is the\n * mirror of `placement` so the badge sits fully outside the host edge.\n * When `placement` is a raw `{x, y}` point with no inherent mirror, the\n * default falls back to `'center'`.\n */\nexport function originToBadgeLocal(\n badgeLocalBounds: Rect,\n placement: BadgePlacement,\n origin: BadgeOptions['origin'],\n): { x: number; y: number } {\n if (origin === 'center' || (origin === undefined && typeof placement === 'object')) {\n return {\n x: badgeLocalBounds.x + badgeLocalBounds.width / 2,\n y: badgeLocalBounds.y + badgeLocalBounds.height / 2,\n };\n }\n const point = origin ?? mirrorPlacement(placement as NamedBadgePlacement);\n // Reuse named-point math — it's the same \"point on an AABB\" computation,\n // just applied to the badge's local AABB instead of the host's world AABB.\n return namedPlacementToAnchor(badgeLocalBounds, point);\n}\n\n/**\n * Mirror of a named placement across the host centre. `top-right` ↔\n * `bottom-left`, `right` ↔ `left`, and so on. Used as the default `origin`\n * so a badge with `placement: 'top-right'` sits with its `bottom-left`\n * corner at the host's top-right corner — i.e. the badge nests fully\n * outside the host edge. Only defined for {@link NamedBadgePlacement};\n * raw `{x, y}` placements have no symmetric counterpart on the host AABB.\n */\nexport function mirrorPlacement(p: NamedBadgePlacement): NamedBadgePlacement {\n switch (p) {\n case 'top': return 'bottom';\n case 'bottom': return 'top';\n case 'left': return 'right';\n case 'right': return 'left';\n case 'top-left': return 'bottom-right';\n case 'top-right': return 'bottom-left';\n case 'bottom-left': return 'top-right';\n case 'bottom-right': return 'top-left';\n }\n}\n\n/**\n * Resolve the badge spec's `(x, y)` so that the chosen origin point on the\n * badge AABB lands at the chosen anchor point on the host AABB, plus the\n * caller's pixel offset.\n *\n * The badge spec's `(x, y)` represents the badge's *local-origin* in world\n * space (e.g. circle centre, rect top-left). Local AABB origin is at\n * `(badgeLocalBounds.x, badgeLocalBounds.y)` — for a circle these are\n * negative (`-r, -r`); for a rect they are `(0, 0)`. We compute the badge's\n * `(x, y)` such that the chosen origin point — at\n * `(specX + originLocal.x, specY + originLocal.y)` in world space — equals\n * the host anchor + offset.\n */\nexport function resolveBadgePosition(\n hostWorldBounds: Rect,\n badgeLocalBounds: Rect,\n options: BadgeOptions,\n): { x: number; y: number } {\n // Shape-host dispatch: `options.placement` is statically widened to\n // `BadgePlacement | ConnectorBadgePlacement`. `setBadge` routes connector\n // hosts away from this function, so by construction the runtime placement\n // is always a `BadgePlacement` here. The cast collapses the unused union\n // arm at the type level only.\n const placement = options.placement as BadgePlacement;\n const anchor = placementToHostAnchor(hostWorldBounds, placement);\n const originLocal = originToBadgeLocal(\n badgeLocalBounds,\n placement,\n options.origin,\n );\n return {\n x: anchor.x + (options.offsetX ?? 0) - originLocal.x,\n y: anchor.y + (options.offsetY ?? 0) - originLocal.y,\n };\n}\n","/**\n * Pure placement math for connector-hosted badges. Given a router-resolved\n * `Path` and the badge's local-space AABB, resolve the world-space `(x, y)`\n * (plus optional rotation) so that a chosen point on the badge's AABB lands\n * on a chosen anchor along the path — `'start'` / `'middle'` / `'end'` or\n * an arbitrary arc-length `t ∈ [0, 1]`.\n *\n * No Pixi imports. The math mirrors {@link LabelConnectorDecoration} so\n * connector badges and connector labels share the same arc-length walk.\n */\n\nimport type { Path } from '../../../specs';\nimport type { BadgeOptions, ConnectorBadgePlacement } from './types';\nimport { samplePathAt } from '../connectors/pathSampling';\nimport { originToBadgeLocal } from './placement';\nimport type { Rect } from '../../../specs';\n\n/**\n * Map a {@link ConnectorBadgePlacement} to an arc-length parameter `t ∈\n * [0, 1]`. Numbers outside the closed unit interval are clamped.\n */\nexport function resolveConnectorT(placement: ConnectorBadgePlacement): number {\n if (typeof placement === 'number') {\n if (placement <= 0) return 0;\n if (placement >= 1) return 1;\n return placement;\n }\n switch (placement) {\n case 'start':\n return 0;\n case 'middle':\n return 0.5;\n case 'end':\n return 1;\n }\n}\n\n/**\n * Resolve the badge spec's `(x, y)` (and optional `rotation`) so that the\n * chosen origin point on the badge's local AABB lands at the path-anchor\n * defined by `options.placement`. The origin defaults to `'center'` for\n * connector hosts (badge centres on the path point); shape-style mirror\n * defaults don't apply here because the path has no \"outside edge\".\n *\n * The returned `rotation` is `0` unless {@link BadgeOptions.autoRotate} is\n * `true`. When auto-rotating with `keepUpright !== false` (the default),\n * tangents whose angle exceeds `±90°` are flipped by `π` so the badge's\n * top edge keeps facing the viewer.\n */\n/**\n * Per-endpoint extra clearance added to the auto-shift when\n * {@link BadgeOptions.placement} is `'start'` or `'end'`. The renderer\n * passes the source / target marker length here (so the badge clears the\n * arrowhead, not just the trimmed path endpoint) plus a small visual gap.\n *\n * Numeric placements (`0`, `1`, raw `t`) ignore this — they're the \"raw\n * arc-length\" escape hatch.\n */\nexport interface ConnectorBadgeEndpointClearance {\n readonly source: number;\n readonly target: number;\n}\n\n/** Default pixel gap inserted between an endpoint-anchored badge and the\n * endpoint shape's silhouette (or, when a marker is present, the marker's\n * far tip). Tunable by callers via the `clearance` parameter — this is\n * just the engine-side floor when the renderer doesn't know better. */\nexport const DEFAULT_ENDPOINT_BADGE_GAP_PX = 8;\n\nexport function resolveConnectorBadgePosition(\n path: Path,\n badgeLocalBounds: Rect,\n options: BadgeOptions,\n clearance: ConnectorBadgeEndpointClearance = { source: 0, target: 0 },\n): { x: number; y: number; rotation: number } {\n const placement = options.placement as ConnectorBadgePlacement;\n const t = resolveConnectorT(placement);\n const sample = samplePathAt(path, t);\n\n let baseX = sample.point.x;\n let baseY = sample.point.y;\n\n // Endpoint-clearance for the named `'start'` / `'end'` placements.\n //\n // The routed path stops at the source / target shape's *silhouette*, so a\n // badge centred on `t=0` or `t=1` would half-overlap the endpoint shape.\n // For the named placements we treat that overlap as a bug: shift the\n // badge tangentially by its own tangent-aligned half-extent so its\n // line-facing edge kisses the silhouette from outside, leaving the\n // endpoint shape un-occluded.\n //\n // Numeric placement (`0`, `1`, or any `t ∈ [0,1]`) keeps the raw\n // arc-length contract — use `placement: 0` / `placement: 1` when you\n // explicitly want a badge anchored at the silhouette point.\n if (placement === 'start' || placement === 'end') {\n // L1-norm projection of the badge's local half-extents onto the\n // tangent. Conservative for axis-aligned badges; exact when the badge\n // is rotated to align with the tangent (autoRotate).\n const halfTangentExtent =\n Math.abs(sample.tangent.x) * (badgeLocalBounds.width / 2) +\n Math.abs(sample.tangent.y) * (badgeLocalBounds.height / 2);\n // Per-endpoint extra clearance — marker length + a visual gap so the\n // arrowhead doesn't end up tucked under the badge. The renderer\n // computes these from `markerInsetFor(...)` + the engine-default gap.\n const extra = placement === 'start' ? clearance.source : clearance.target;\n // `'start'` at t=0: tangent points *forward* (toward target). Pushing\n // forward moves the badge off the source silhouette toward the line.\n // `'end'` at t=1: tangent still points forward (continuing past target).\n // Pushing backward moves the badge off the target silhouette toward\n // the line.\n const dir = placement === 'start' ? 1 : -1;\n const totalShift = (halfTangentExtent + extra) * dir;\n baseX += sample.tangent.x * totalShift;\n baseY += sample.tangent.y * totalShift;\n }\n\n // Tangent-space `pathOffset` — additional shift along the tangent on top\n // of any endpoint-clearance, so users can fine-tune.\n const pathOffset = options.pathOffset ?? 0;\n if (pathOffset !== 0) {\n baseX += sample.tangent.x * pathOffset;\n baseY += sample.tangent.y * pathOffset;\n }\n\n // Rotation — atan2 of the tangent vector. `keepUpright` flips the badge\n // by π when the tangent points \"downwards\" so text decorations stay\n // readable on every edge orientation.\n let rotation = 0;\n if (options.autoRotate === true) {\n let theta = Math.atan2(sample.tangent.y, sample.tangent.x);\n if (options.keepUpright !== false) {\n if (theta > Math.PI / 2) theta -= Math.PI;\n else if (theta < -Math.PI / 2) theta += Math.PI;\n }\n rotation = theta;\n }\n\n // Connector hosts default `origin` to `'center'` (badge sits *on* the\n // path point); shape-style mirror defaults have no analog here. Reuse\n // {@link originToBadgeLocal} — passing `'top'` as a sentinel placement\n // is fine because the function only consults `placement` when the\n // origin is omitted, and we always supply `'center'` as the fallback.\n const originLocal = originToBadgeLocal(\n badgeLocalBounds,\n 'top',\n options.origin ?? 'center',\n );\n\n // Screen-space offset applied after rotation so the badge keeps its\n // intended offset relative to the path's local frame.\n const offsetX = options.offsetX ?? 0;\n const offsetY = options.offsetY ?? 0;\n let rotatedOffsetX = offsetX;\n let rotatedOffsetY = offsetY;\n if (rotation !== 0 && (offsetX !== 0 || offsetY !== 0)) {\n const cos = Math.cos(rotation);\n const sin = Math.sin(rotation);\n rotatedOffsetX = offsetX * cos - offsetY * sin;\n rotatedOffsetY = offsetX * sin + offsetY * cos;\n }\n\n return {\n x: baseX + rotatedOffsetX - originLocal.x,\n y: baseY + rotatedOffsetY - originLocal.y,\n rotation,\n };\n}\n","import type { LabelSizePolicy } from '../../../contracts/IElementRenderer';\n\n/**\n * The scale to draw a label at so its on-screen font size follows `policy`.\n *\n * Positional arguments, not an options object: the renderer calls this once per\n * label per zoom-changed frame, so it must not allocate.\n *\n * @param fontSize The label's authored font size — its on-screen size at zoom `1`.\n * @param zoom Current camera zoom (`camera.scale`).\n * @param hostScale Visual scale the label inherits from its host before any label\n * scaling — e.g. a node-size LOD drawing the node at `1 / zoom`; `1` for\n * connectors. Excludes display-only magnification (a fisheye lens), which\n * should still enlarge the label.\n * @param policy The policy in force, or `null` for none.\n * @param contained `true` when the label must stay inside its host (an `inside-*`\n * placement): the result never exceeds `1`, so the host's fit-to-box budget holds.\n *\n * - `natural = fontSize × zoom × hostScale` — what the label measures on\n * screen with no policy.\n * - `target = zoomGrowth === undefined ? natural : fontSize × zoom ^ zoomGrowth`,\n * then clamped to `[minFontPx, maxFontPx]`.\n * - Result: `target / natural`, capped at `1` for a contained label.\n *\n * Returns `1` for a `null` policy and for degenerate input (non-positive font\n * size, zoom or host scale), so a caller can apply the result unconditionally.\n *\n * @example\n * ```ts\n * resolveLabelScale(12, 4, 1, { maxFontPx: 20 });\n * // → 20 / 48 ≈ 0.417 — the label reads 20px on screen instead of 48px\n * ```\n */\nexport function resolveLabelScale(\n fontSize: number,\n zoom: number,\n hostScale: number,\n policy: LabelSizePolicy | null,\n contained = false,\n): number {\n if (policy === null) return 1;\n if (!(fontSize > 0) || !(zoom > 0) || !(hostScale > 0)) return 1;\n\n const natural = fontSize * zoom * hostScale;\n let target =\n policy.zoomGrowth === undefined\n ? natural\n : fontSize * Math.pow(zoom, clampUnit(policy.zoomGrowth));\n if (policy.minFontPx !== undefined && target < policy.minFontPx) target = policy.minFontPx;\n if (policy.maxFontPx !== undefined && target > policy.maxFontPx) target = policy.maxFontPx;\n\n const scale = target / natural;\n return contained && scale > 1 ? 1 : scale;\n}\n\n/** Clamp to `[0, 1]`; a non-finite value falls back to `1` (grow with the world). */\nfunction clampUnit(v: number): number {\n if (!Number.isFinite(v)) return 1;\n return v < 0 ? 0 : v > 1 ? 1 : v;\n}\n","import { Tween } from './Tween';\nimport { easeOutCubic, type Easing } from './easings';\n\n/**\n * Options for {@link animatePositions}.\n *\n * Positions are passed as flat `Float32Array`s of length `n * 2` — `x, y`\n * interleaved per node — the same shape `GraphStore.setPositionsBulk` consumes,\n * so a layout can hand its result buffer straight through.\n */\nexport interface PositionTransitionOptions {\n /** Start positions (`n * 2`, x/y interleaved). Usually the nodes' current spots. */\n from: Float32Array;\n /** Target positions (`n * 2`, x/y interleaved). The computed layout result. */\n to: Float32Array;\n /** Transition duration in milliseconds. `<= 0` snaps to `to` immediately. */\n duration: number;\n /** Eased progress curve. Default {@link easeOutCubic}. */\n easing?: Easing;\n /**\n * Called once per frame with the interpolated buffer — write it straight to\n * the store (e.g. `store.setPositionsBulk(ids, xy)`). The SAME buffer is\n * reused every frame; copy it if you need to retain it.\n *\n * `progress` is the **eased** fraction of the transition, `0..1` — the same\n * factor the buffer was interpolated with — and is exactly `1` on the final\n * frame. Lets a caller move something else in lock-step (e.g. the camera).\n */\n onFrame: (xy: Float32Array, progress: number) => void;\n /** Fires once when the transition finishes naturally. NOT called on `cancel()`. */\n onComplete?: () => void;\n}\n\n/** Handle to an in-flight {@link animatePositions} transition. */\nexport interface PositionTransition {\n /** Abort the transition. `onComplete` will not fire; positions stop where they are. */\n cancel(): void;\n /** `true` once the transition has finished or been cancelled. */\n readonly done: boolean;\n}\n\n/** Default transition length when a caller opts in without specifying one. */\nexport const DEFAULT_POSITION_TRANSITION_MS = 500;\n\n/**\n * Tween a set of node positions from `from` to `to` over `duration` ms,\n * self-driven on `requestAnimationFrame`.\n *\n * One-shot layouts (ELK, d3-hierarchy, d3-sankey, …) compute a final position\n * set in a single pass and would otherwise `setPositionsBulk` it in one write,\n * teleporting every node. Routing that final buffer through `animatePositions`\n * instead glides each node from where it currently sits to its computed slot —\n * a far more legible layout switch / re-layout.\n *\n * The `Layout` base class is deliberately canvas-agnostic (it owns no RAF), so\n * this helper drives its own frame loop — mirroring how `D3ForceLayout` rides\n * d3's internal timer. It is store-agnostic: it only interpolates buffers and\n * hands each frame back via `onFrame`; the caller owns the write.\n *\n * Cancellation: call `cancel()` (typically from the layout's `stop()` or its\n * next `apply()`) to abort cleanly — the next run can start a fresh transition\n * from wherever the nodes currently are. SSR-safe and degenerate-input-safe:\n * with no `requestAnimationFrame`, a non-positive `duration`, or an empty set,\n * it writes the final positions once and completes synchronously.\n *\n * @throws if `from.length !== to.length`.\n */\nexport function animatePositions(opts: PositionTransitionOptions): PositionTransition {\n const { from, to, duration, easing = easeOutCubic, onFrame, onComplete } = opts;\n if (from.length !== to.length) {\n throw new Error(\n `animatePositions: from.length=${from.length} must equal to.length=${to.length}`,\n );\n }\n\n const n = from.length;\n let done = false;\n let cancelled = false;\n let rafId: number | null = null;\n let last = 0;\n\n const finish = (): void => {\n done = true;\n onFrame(to, 1); // land on the exact target, free of float drift\n onComplete?.();\n };\n\n const raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : null;\n if (!raf || duration <= 0 || n === 0) {\n finish();\n return { cancel() {}, get done() { return done; } };\n }\n\n const buffer = new Float32Array(n);\n const tween = new Tween({ from: 0, to: 1, duration, easing });\n\n const step = (now: number): void => {\n if (cancelled) return;\n const dt = last === 0 ? 0 : now - last;\n last = now;\n const alive = tween.tick(dt);\n if (!alive) {\n finish();\n return;\n }\n const t = tween.value;\n for (let i = 0; i < n; i++) buffer[i] = from[i]! + (to[i]! - from[i]!) * t;\n onFrame(buffer, t);\n rafId = raf(step);\n };\n rafId = raf(step);\n\n return {\n cancel(): void {\n if (done) return;\n cancelled = true;\n done = true;\n if (rafId !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(rafId);\n },\n get done(): boolean {\n return done;\n },\n };\n}\n","/**\n * SVG markup primitives — number formatting, XML escaping, attribute\n * serialisation and colour conversion shared by every serialiser in this\n * folder (and by the `exportSVG` document assembler in `@invana/canvas`).\n *\n * Pure string helpers: no DOM, no canvas, no backend.\n */\n\nimport type { Point } from '../../specs';\n\n/** Round to 3 decimals and drop a trailing `.0` — keeps the markup compact. */\nexport function n(v: number): string {\n return Number.isInteger(v) ? String(v) : v.toFixed(3).replace(/\\.?0+$/, '');\n}\n\n/** Escape text for use in an XML text node / attribute value. */\nexport function esc(s: string): string {\n return s.replace(/[&<>\"']/g, (c) =>\n c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '\"' ? '&quot;' : '&#39;',\n );\n}\n\n/** Serialise an attribute map, skipping `undefined` / empty values. */\nexport function attrs(map: Record<string, string | number | undefined>): string {\n return Object.entries(map)\n .filter(([, v]) => v !== undefined && v !== '')\n .map(([k, v]) => `${k}=\"${typeof v === 'number' ? n(v) : v}\"`)\n .join(' ');\n}\n\n/** `points=\"x,y x,y …\"` for `<polygon>`. */\nexport function pointsAttr(pts: readonly Point[]): string {\n return pts.map((p) => `${n(p.x)},${n(p.y)}`).join(' ');\n}\n\n/** `0xRRGGBB` → `#rrggbb`. */\nexport function hexToCss(n: number): string {\n return `#${(n & 0xffffff).toString(16).padStart(6, '0')}`;\n}\n","/**\n * `Path` → SVG path-data serialisation. Pure: a routed {@link Path} in, a `d`\n * attribute string out.\n */\n\nimport type { Path } from '../../specs';\nimport { n } from './markup';\n\n/** A `Path` (M/L/Q/C commands) → an SVG `d` attribute string. */\nexport function pathToSvgD(path: Path): string {\n const out: string[] = [];\n for (const c of path) {\n if (c.kind === 'M') out.push(`M ${n(c.x)} ${n(c.y)}`);\n else if (c.kind === 'L') out.push(`L ${n(c.x)} ${n(c.y)}`);\n else if (c.kind === 'Q') out.push(`Q ${n(c.cx)} ${n(c.cy)} ${n(c.x)} ${n(c.y)}`);\n else out.push(`C ${n(c.c1x)} ${n(c.c1y)} ${n(c.c2x)} ${n(c.c2y)} ${n(c.x)} ${n(c.y)}`);\n }\n return out.join(' ');\n}\n","/**\n * Spec paint → SVG paint attributes — the fill/stroke resolution shared by the\n * shape and connector serialisers, plus label-content extraction.\n *\n * Only the first `solid` fill layer is representable in flat SVG; `image` /\n * `glyph` / `svg` fills are skipped (→ `fill: none`) — a raster-only feature.\n */\n\nimport type { LabelContent, ShapeFill, ShapeStroke } from '../../specs';\nimport { hexToCss, n } from './markup';\n\n/**\n * Resolve a {@link ShapeFill} to SVG `fill` / `fill-opacity`. Only the first\n * `solid` layer is representable in flat SVG; `image` / `glyph` / `svg` fills\n * are skipped (→ `fill: none`), documented as a raster-only feature.\n */\nexport function fillPaint(fill: ShapeFill | undefined): Record<string, string | number | undefined> {\n if (fill === undefined) return { fill: 'none' };\n if (typeof fill === 'number') return { fill: hexToCss(fill) };\n const layers = Array.isArray(fill) ? fill : [fill];\n for (const layer of layers) {\n if (layer.kind === 'solid') {\n return { fill: hexToCss(layer.color), 'fill-opacity': layer.alpha ?? undefined };\n }\n }\n return { fill: 'none' };\n}\n\n/** Resolve a {@link ShapeStroke} to SVG stroke attributes. `widthScale` mirrors LOD scaling. */\nexport function strokePaint(stroke: ShapeStroke | undefined, widthScale = 1): Record<string, string | number | undefined> {\n if (!stroke) return {};\n const width = (stroke.width ?? 1) * widthScale;\n return {\n stroke: hexToCss(stroke.color),\n 'stroke-width': width,\n 'stroke-opacity': stroke.alpha ?? undefined,\n 'stroke-linecap': stroke.cap,\n 'stroke-linejoin': stroke.join,\n 'stroke-dasharray': stroke.dashArray ? `${n(stroke.dashArray[0])} ${n(stroke.dashArray[1])}` : undefined,\n 'stroke-dashoffset': stroke.dashOffset,\n };\n}\n\n/** Extract plain-text `LabelContent` from a label decoration style, if any. */\nexport function textContent(style: unknown): (LabelContent & { kind: 'text' }) | undefined {\n const content = (style as { content?: LabelContent } | undefined)?.content;\n return content?.kind === 'text' ? content : undefined;\n}\n","/**\n * Shape spec → SVG element serialisation — one half of the vector export path\n * (see `@invana/canvas`'s `exportSVG` for document assembly, and\n * {@link connectorToSvg} for the other half).\n *\n * The serialisers here are **pure and domain-free** (a `CircleSpec` knows\n * nothing about \"nodes\"): a spec goes in, markup comes out — no display object,\n * no canvas handle, which is why they live in `@invana/canvas-core` where a\n * rendering backend can call them directly.\n *\n * ## Coverage (v1)\n *\n * Faithful: `circle`, `ellipse`, `rect` (+ `cornerRadius`), `polygon`,\n * `regular-polygon`, `star`, `arc`, `composite` (root silhouette + `rect` /\n * `circle` / `line` / `label` parts), solid fills, strokes (colour / width /\n * alpha / dash / cap / join), per-shape `alpha` and container `rotation`, and\n * `text`-kind label decorations (approximate placement).\n *\n * Not represented (raster export covers these exactly — prefer PNG when they\n * matter): `image` / `glyph` / `svg` / `svg-url` fills, decorations other than\n * labels (glow / halo / rings / pulses), effects, blur / shadow filters, and\n * `html-text` labels. These are skipped rather than approximated.\n */\n\nimport type {\n ArcSpec,\n BaseShapeSpec,\n CircleSpec,\n CompositePart,\n CompositeSpec,\n EllipseSpec,\n Point,\n PolygonSpec,\n RectSpec,\n RegularPolygonSpec,\n ShapeLabelStyle,\n StarSpec,\n TabbedRectSpec,\n} from '../../specs';\nimport { tabbedRectFoldLine, tabbedRectOutline } from '../../specs';\nimport { attrs, esc, hexToCss, n, pointsAttr } from './markup';\nimport { fillPaint, strokePaint, textContent } from './paint';\n\n/** Vertices of a regular n-gon (pointy-top at `rotation = 0`). */\nfunction regularPolygonPoints(cx: number, cy: number, sides: number, radius: number, rotation = 0): Point[] {\n const pts: Point[] = [];\n const step = (Math.PI * 2) / Math.max(3, sides);\n const start = -Math.PI / 2 - rotation;\n for (let i = 0; i < sides; i++) {\n const a = start + i * step;\n pts.push({ x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) });\n }\n return pts;\n}\n\n/** Vertices of a star alternating outer/inner radius. */\nfunction starPoints(cx: number, cy: number, points: number, innerR: number, outerR: number, rotation = 0): Point[] {\n const pts: Point[] = [];\n const step = Math.PI / Math.max(2, points);\n const start = -Math.PI / 2 - rotation;\n for (let i = 0; i < points * 2; i++) {\n const r = i % 2 === 0 ? outerR : innerR;\n const a = start + i * step;\n pts.push({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });\n }\n return pts;\n}\n\n/**\n * Wrap `inner` in a `<g>` when the spec carries a container-level `alpha` or\n * `rotation` (radians, about the spec origin). Returns `inner` unchanged when\n * neither applies, to keep the markup minimal.\n */\nfunction wrapTransform(spec: BaseShapeSpec, inner: string): string {\n const rot = spec.rotation ?? 0;\n const hasAlpha = spec.alpha !== undefined && spec.alpha !== 1;\n if (!rot && !hasAlpha) return inner;\n const t = rot ? `transform=\"rotate(${n((rot * 180) / Math.PI)} ${n(spec.x)} ${n(spec.y)})\"` : '';\n const o = hasAlpha ? `opacity=\"${n(spec.alpha as number)}\"` : '';\n return `<g ${[t, o].filter(Boolean).join(' ')}>${inner}</g>`;\n}\n\n/**\n * Serialise a single shape spec to an SVG element. Returns `''` for a shape\n * kind that has no vector representation. `labelStyle` (from an attached\n * `label` decoration) is rendered as `<text>` when present.\n */\nexport function shapeSpecToSvg(spec: BaseShapeSpec, labelStyle?: unknown): string {\n if (spec.visible === false) return '';\n const paint = { ...fillPaint(spec.fill), ...strokePaint(spec.stroke) };\n let body = '';\n\n switch (spec.kind) {\n case 'circle': {\n const s = spec as CircleSpec;\n body = `<circle ${attrs({ cx: s.x, cy: s.y, r: s.radius, ...paint })}/>`;\n break;\n }\n case 'ellipse': {\n const s = spec as EllipseSpec;\n body = `<ellipse ${attrs({ cx: s.x, cy: s.y, rx: s.radiusX, ry: s.radiusY, ...paint })}/>`;\n break;\n }\n case 'rect': {\n const s = spec as RectSpec;\n body = `<rect ${attrs({ x: s.x, y: s.y, width: s.width, height: s.height, rx: s.cornerRadius || undefined, ...paint })}/>`;\n break;\n }\n case 'tabbed-rect': {\n const s = spec as TabbedRectSpec;\n // The folder outline is already a polyline (fillets sampled as\n // segments), so it exports exactly as the renderer draws it.\n const pts = tabbedRectOutline(s).map((v) => ({ x: v.x + s.x, y: v.y + s.y }));\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n // The fold line closing the tab's base is interior geometry, so it\n // rides as a separate stroked segment rather than part of the outline.\n const fold = tabbedRectFoldLine(s);\n if (fold && s.stroke) {\n body += `<line ${attrs({\n x1: fold[0].x + s.x,\n y1: fold[0].y + s.y,\n x2: fold[1].x + s.x,\n y2: fold[1].y + s.y,\n ...strokePaint(s.stroke),\n fill: 'none',\n })}/>`;\n }\n break;\n }\n case 'polygon': {\n const s = spec as PolygonSpec;\n const pts = s.vertices.map((v) => ({ x: v.x + s.x, y: v.y + s.y }));\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'regular-polygon': {\n const s = spec as RegularPolygonSpec;\n const pts = regularPolygonPoints(s.x, s.y, s.sides, s.radius, s.rotation ?? 0);\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'star': {\n const s = spec as StarSpec;\n const pts = starPoints(s.x, s.y, s.points, s.innerRadius, s.outerRadius, s.rotation ?? 0);\n body = `<polygon ${attrs({ points: pointsAttr(pts), ...paint })}/>`;\n break;\n }\n case 'arc': {\n body = `<path ${attrs({ d: arcToSvgD(spec as ArcSpec), 'fill-rule': 'evenodd', ...paint })}/>`;\n break;\n }\n case 'composite': {\n body = compositeToSvg(spec as CompositeSpec);\n break;\n }\n default:\n return ''; // unknown / raster-only shape kind\n }\n\n return wrapTransform(spec, body + labelToSvg(spec, labelStyle));\n}\n\n/** Annular-sector / pie `arc` spec → SVG path `d`. */\nfunction arcToSvgD(s: ArcSpec): string {\n const { x: cx, y: cy, innerR, outerR, startAngle: a0, endAngle: a1 } = s;\n const full = Math.abs(a1 - a0) >= Math.PI * 2 - 1e-6;\n const pt = (r: number, a: number): Point => ({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });\n\n if (full) {\n // Full disc / annulus — two half-arcs per ring; evenodd punches the hole.\n const ring = (r: number) =>\n `M ${n(cx - r)} ${n(cy)} A ${n(r)} ${n(r)} 0 1 1 ${n(cx + r)} ${n(cy)} A ${n(r)} ${n(r)} 0 1 1 ${n(cx - r)} ${n(cy)} Z`;\n return innerR > 0 ? `${ring(outerR)} ${ring(innerR)}` : ring(outerR);\n }\n\n const large = Math.abs(a1 - a0) > Math.PI ? 1 : 0;\n const os = pt(outerR, a0);\n const oe = pt(outerR, a1);\n if (innerR <= 0) {\n // Pie slice.\n return `M ${n(cx)} ${n(cy)} L ${n(os.x)} ${n(os.y)} A ${n(outerR)} ${n(outerR)} 0 ${large} 1 ${n(oe.x)} ${n(oe.y)} Z`;\n }\n const ie = pt(innerR, a1);\n const is = pt(innerR, a0);\n return (\n `M ${n(os.x)} ${n(os.y)} A ${n(outerR)} ${n(outerR)} 0 ${large} 1 ${n(oe.x)} ${n(oe.y)} ` +\n `L ${n(ie.x)} ${n(ie.y)} A ${n(innerR)} ${n(innerR)} 0 ${large} 0 ${n(is.x)} ${n(is.y)} Z`\n );\n}\n\n/**\n * Composite card → an SVG `<g>` translated to the composite's top-left origin:\n * the background silhouette (default rounded-rect, or the `root` shape centred\n * in the box) followed by each `rect` / `circle` / `line` / `label` part.\n */\nfunction compositeToSvg(s: CompositeSpec): string {\n const els: string[] = [];\n const paint = { ...fillPaint(s.fill), ...strokePaint(s.stroke) };\n\n if (s.root) {\n // Centre the borrowed root shape in the width×height box (its own x/y are\n // ignored per CompositeSpec) and serialise it as a normal shape.\n const centred = { ...s.root, x: s.width / 2, y: s.height / 2 } as BaseShapeSpec;\n // Rect roots are top-left anchored — offset so the box is centred.\n if (s.root.kind === 'rect') {\n const r = s.root as RectSpec;\n (centred as { x: number; y: number }).x = (s.width - r.width) / 2;\n (centred as { x: number; y: number }).y = (s.height - r.height) / 2;\n }\n els.push(shapeSpecToSvg(centred));\n } else {\n els.push(`<rect ${attrs({ x: 0, y: 0, width: s.width, height: s.height, rx: s.cornerRadius || undefined, ...paint })}/>`);\n }\n\n for (const part of s.parts) els.push(partToSvg(part));\n return `<g ${attrs({ transform: `translate(${n(s.x)} ${n(s.y)})` })}>${els.join('')}</g>`;\n}\n\n/** A single {@link CompositePart} → SVG element (coords relative to the card origin). */\nfunction partToSvg(part: CompositePart): string {\n switch (part.part) {\n case 'rect':\n return `<rect ${attrs({\n x: part.x,\n y: part.y,\n width: part.width,\n height: part.height,\n rx: part.cornerRadius || undefined,\n fill: part.fill !== undefined ? hexToCss(part.fill) : 'none',\n 'fill-opacity': part.fillAlpha,\n ...(part.stroke ? { stroke: hexToCss(part.stroke.color), 'stroke-width': part.stroke.width ?? 1, 'stroke-opacity': part.stroke.alpha } : {}),\n })}/>`;\n case 'circle':\n return `<circle ${attrs({\n cx: part.x,\n cy: part.y,\n r: part.radius,\n fill: part.fill !== undefined ? hexToCss(part.fill) : 'none',\n 'fill-opacity': part.fillAlpha,\n ...(part.stroke ? { stroke: hexToCss(part.stroke.color), 'stroke-width': part.stroke.width ?? 1, 'stroke-opacity': part.stroke.alpha } : {}),\n })}/>`;\n case 'line':\n return `<line ${attrs({\n x1: part.x,\n y1: part.y,\n x2: part.x2,\n y2: part.y2,\n stroke: hexToCss(part.stroke.color),\n 'stroke-width': part.stroke.width ?? 1,\n 'stroke-opacity': part.stroke.alpha,\n })}/>`;\n case 'label': {\n const anchor = part.anchor === 'center' ? 'middle' : part.anchor === 'right' ? 'end' : 'start';\n return `<text ${attrs({\n x: part.x,\n y: part.y,\n 'font-size': part.fontSize ?? 12,\n 'font-weight': part.fontWeight as string | number | undefined,\n 'font-style': part.fontStyle,\n 'text-anchor': anchor,\n 'dominant-baseline': 'hanging',\n fill: part.fill !== undefined ? hexToCss(part.fill) : '#111827',\n })}>${esc(part.text)}</text>`;\n }\n default:\n return '';\n }\n}\n\n/**\n * Approximate an attached `text` label as `<text>`, anchored at the shape\n * centre with a placement-derived vertical offset. Placement is coarse (SVG\n * can't run the engine's fit/collision cascade); it captures the text, colour,\n * and rough position — good enough for a legible vector export.\n */\nfunction labelToSvg(spec: BaseShapeSpec, style: unknown): string {\n const content = textContent(style);\n if (!content) return '';\n const s = style as ShapeLabelStyle;\n const placement = s.placement ?? 'bottom';\n // Rough half-extent from any radius/size field so outside labels clear the shape.\n const r =\n (spec as { radius?: number }).radius ??\n (spec as { outerRadius?: number }).outerRadius ??\n ((spec as { height?: number }).height ?? 24) / 2;\n let dy = 0;\n if (placement.includes('bottom')) dy = r + (content.fontSize ?? 12);\n else if (placement.includes('top')) dy = -(r + 4);\n const ox = s.offset?.x ?? 0;\n const oy = s.offset?.y ?? 0;\n return `<text ${attrs({\n x: spec.x + ox,\n y: spec.y + dy + oy,\n 'font-size': content.fontSize ?? 12,\n 'font-family': content.fontFamily ?? 'sans-serif',\n 'font-weight': content.fontWeight as string | number | undefined,\n 'font-style': content.fontStyle,\n 'text-anchor': 'middle',\n 'dominant-baseline': 'middle',\n fill: content.fill !== undefined ? hexToCss(content.fill) : '#111827',\n opacity: content.alpha,\n })}>${esc(content.text)}</text>`;\n}\n","/**\n * Connector spec → SVG serialisation — the other half of the vector export\n * path (see {@link shapeSpecToSvg}). Pure: a spec + its routed {@link Path} in,\n * markup out.\n */\n\nimport type { BaseConnectorSpec, ConnectorLabelStyle, Path, Point } from '../../specs';\nimport { attrs, esc, hexToCss, n, pointsAttr } from './markup';\nimport { strokePaint, textContent } from './paint';\nimport { pathToSvgD } from './pathToSvgD';\n\n/**\n * Serialise a connector (its routed `path` + stroke + optional arrow markers)\n * to SVG. `strokeWidthScale` mirrors the renderer's per-instance LOD scaling.\n */\nexport function connectorToSvg(\n spec: BaseConnectorSpec,\n path: Path,\n strokeWidthScale = 1,\n labelStyle?: unknown,\n): string {\n if (spec.visible === false || path.length === 0) return '';\n const paint = strokePaint(spec.stroke, strokeWidthScale);\n const width = (spec.stroke?.width ?? 1) * strokeWidthScale;\n const els = [`<path ${attrs({ d: pathToSvgD(path), fill: 'none', ...paint })}/>`];\n\n // Arrow markers as filled triangles at the path ends, oriented along the\n // terminal segment. Approximate (marker geometry sizes off stroke width).\n const color = spec.stroke ? hexToCss(spec.stroke.color) : '#000000';\n if (spec.targetMarker) els.push(arrowMarker(path, 'target', width, color));\n if (spec.sourceMarker) els.push(arrowMarker(path, 'source', width, color));\n\n const label = connectorLabelToSvg(path, labelStyle);\n const alpha = spec.alpha !== undefined && spec.alpha !== 1 ? ` opacity=\"${n(spec.alpha)}\"` : '';\n return `<g${alpha}>${els.join('')}${label}</g>`;\n}\n\n/** A triangular arrowhead at the source/target end of a path. */\nfunction arrowMarker(path: Path, end: 'source' | 'target', strokeWidth: number, color: string): string {\n const pts = pathPoints(path);\n if (pts.length < 2) return '';\n const tip = end === 'target' ? pts[pts.length - 1]! : pts[0]!;\n const prev = end === 'target' ? pts[pts.length - 2]! : pts[1]!;\n const ang = Math.atan2(tip.y - prev.y, tip.x - prev.x);\n const len = Math.max(6, strokeWidth * 4);\n const half = Math.max(3, strokeWidth * 2);\n const back = { x: tip.x - len * Math.cos(ang), y: tip.y - len * Math.sin(ang) };\n const nx = Math.cos(ang + Math.PI / 2);\n const ny = Math.sin(ang + Math.PI / 2);\n const p1 = { x: back.x + half * nx, y: back.y + half * ny };\n const p2 = { x: back.x - half * nx, y: back.y - half * ny };\n return `<polygon ${attrs({ points: pointsAttr([tip, p1, p2]), fill: color })}/>`;\n}\n\n/** Sample a path's command endpoints as a coarse polyline (ignores control points). */\nfunction pathPoints(path: Path): Point[] {\n return path.filter((c) => c.kind !== undefined).map((c) => ({ x: c.x, y: c.y }));\n}\n\n/** Approximate a connector's `text` label at the path midpoint. */\nfunction connectorLabelToSvg(path: Path, style: unknown): string {\n const content = textContent(style);\n if (!content) return '';\n const pts = pathPoints(path);\n if (pts.length === 0) return '';\n const mid = pts[Math.floor(pts.length / 2)]!;\n const s = style as ConnectorLabelStyle;\n return `<text ${attrs({\n x: mid.x + (s.offset?.x ?? 0),\n y: mid.y + (s.offset?.y ?? 0),\n 'font-size': content.fontSize ?? 12,\n 'font-family': content.fontFamily ?? 'sans-serif',\n 'text-anchor': 'middle',\n 'dominant-baseline': 'middle',\n fill: content.fill !== undefined ? hexToCss(content.fill) : '#111827',\n })}>${esc(content.text)}</text>`;\n}\n","import type { EasingName } from '../../lib/animation/easings';\nimport type { CameraTransform, Rect } from '../../specs/geom';\nimport type { ToolbarSpec } from './toolbars';\nimport type { CameraIntent } from '../log/types';\n\n/**\n * `CanvasView` — the reactive, observable, syncable half of `CanvasStore`: how a\n * visualisation is **defined**, **viewed**, and its small transient **runtime**\n * status. Small + human-rate → it lives on a {@link ReactiveStore}. Bulk data\n * (nodes/edges/positions) is the **other** half (`CanvasStore.data`, typed-array,\n * never reactive).\n *\n * Three compartments, three sync physics (see `docs/canvas-state-plan.md` §9):\n * - **`definition`** — \"what it IS\": persisted, converges (a CRDT doc later).\n * - **`interaction`** — \"the live view\": ephemeral / per-user (Awareness later).\n * - **`runtime`** — small observable transient status (layout run, message):\n * reactive so UIs can react, but **never synced**.\n *\n * Per-instance option bags are intentionally loose (`Record<string, unknown>`) at\n * this layer — the engine and the schema-driven editors give them concrete shape,\n * and the kernel stays domain-free (it treats element `style` as opaque).\n */\n/** A layout preset by id, and the options changed over its defaults. */\nexport interface CanvasLayoutPreset {\n id: string;\n /** Option key → chosen value, only where it differs from the preset's default. */\n overrides?: Record<string, string>;\n}\n\nexport interface CanvasView {\n /** \"What the visualisation IS\" — persisted, converged (a CRDT doc later). */\n definition: {\n /** Canvas/scene-level config (background, zoom limits, world bounds, …). */\n canvas: CanvasSceneOptions;\n /** Layer options keyed by instance id (a rendering layer binds a data source). */\n layers: Record<string, Record<string, unknown>>;\n /** Behaviour options keyed by instance id. `enabled` is explicit (rule 7). */\n behaviours: Record<string, Record<string, unknown>>;\n /** Layout options keyed by instance id. */\n layouts: Record<string, Record<string, unknown>>;\n /** Id of the active layout among {@link layouts}, or `null`. */\n activeLayout: string | null;\n /**\n * The layout preset the layout, edge and layout-option slices were last set\n * from, and the options changed over it — `null` when none was applied. The\n * expanded slices are what take effect; this names them, for the picker,\n * *Reset to preset* and a replayed walkthrough step.\n */\n layoutPreset: CanvasLayoutPreset | null;\n /** Authored node/edge templates (designer output). */\n templates: unknown[];\n /** Theme **config** (registry + active family + mode + accent). The *resolved* theme is derived. */\n theme: Record<string, unknown>;\n /**\n * Floating toolbars over the canvas, keyed by panel id. Pure JSON —\n * items name commands / icons / widgets by string (see {@link ToolbarSpec}).\n */\n toolbars: Record<string, ToolbarSpec>;\n };\n /** \"The live view onto it\" — mostly ephemeral / per-user (Awareness later). */\n interaction: {\n /** The semantic selection set (D11 — owned here, not in a behaviour). */\n selection: ReadonlySet<string>;\n /** Hovered element id, or `null`. */\n hover: string | null;\n /** Visual state sets (highlighted / context-open / …) keyed by state name (presence overlay). */\n states: Record<string, ReadonlySet<string>>;\n /**\n * Elements lifted above their peers, keyed by the **source** that lifted\n * them (a behaviour id) — so independent sources (hover, selection, …)\n * never clobber each other's set, and each can be cleared on its own.\n *\n * The renderer projects the union of every source onto its own paint order\n * and lowers anything absent from it. That single projection is what keeps\n * the lift honest: a raise is *derived from state*, not a side effect, so\n * it self-corrects when the state that motivated it changes (an element\n * stops being hovered, a frame opens and becomes a backdrop, …). Before,\n * each behaviour reparented display objects imperatively and tracked what\n * it had touched privately — nothing could reconcile them, so a stale lift\n * outranked the whole scene until that behaviour happened to run again.\n *\n * Ids only: the kernel stays domain-free. What an id *means* (a frame\n * lifting its contents instead of itself, say) is the renderer's business.\n */\n raised: Record<string, ReadonlySet<string>>;\n /** Abstract camera transform — renderer-agnostic; throttled/ephemeral. */\n camera: CameraTransform;\n /**\n * Focal-emphasis: the highlight set + whether the rest is dimmed. O(1) to set;\n * \"muted\" is a render-time derivation (`dim && !ids.has(id)`), not a per-node\n * write (see `canvas-state-plan.md` §7.1B). `null` when no focus is active.\n */\n focus: { ids: ReadonlySet<string>; dim: boolean } | null;\n /**\n * The element whose properties are open (a node or edge id), or `null`.\n * Written by a playbook step, the assistant or a panel; a property-view\n * behaviour (`ClickViewBehaviour`) follows it and writes it back when the\n * user opens or closes one. Recorded as view intent — plain undo steps\n * over it.\n */\n inspect: string | null;\n /**\n * The latest request to frame the camera — `'focus'` (the focus set),\n * `'visible'` (every visible element) or `'all'` (all content, hidden\n * included) — or `null` before any. An **intent, not pixels** (RFC D-4):\n * whoever owns that framing performs it once the canvas settles (the\n * engine frames `'visible'` / `'all'`, `FocusBehaviour` frames `'focus'`).\n * `seq` increases on every request, so asking for the same intent twice\n * frames twice. Recorded as view intent — plain undo steps over it.\n */\n cameraIntent: { intent: CameraIntent; seq: number } | null;\n /**\n * Nodes transiently locked during a drag/resize gesture — held against the\n * layout for the gesture's duration. **Distinct from data `pinned`** (the\n * permanent, synced user flag); these are ephemeral and never synced.\n */\n transientPins: ReadonlySet<string>;\n /**\n * Active interaction mode — the modeller \"tool\" (`'select'`, `'add'`,\n * `'connect'`, `'delete'`, or any string a host defines). Per-user and\n * ephemeral like the rest of `interaction`. Behaviours opt into following it\n * through `BehaviourOptions.modes`; commands switch it (`tool.active`).\n * Seeded from `definition.canvas.defaultViewMode` when a canvas starts.\n */\n viewMode: string;\n /**\n * Parameters of the active mode, as plain strings keyed by name — e.g.\n * `{ nodeKind: 'circle' }` for an \"add node\" tool. A bag rather than typed\n * fields so the kernel stays domain-free: what a key means is the\n * business of whoever reads it (the graph's `tool.nodeKind` command).\n */\n viewModeArgs: Readonly<Record<string, string>>;\n };\n /** Small observable transient status — reactive (UIs react) but **never synced**. */\n runtime: {\n /** Layout run status — drives spinners / a stop control. */\n layout: {\n running: boolean;\n /** The layout id currently executing, or `null`. */\n activeId: string | null;\n /** Whether the run animates its settle (force sim) vs jumps to final positions. */\n animate: boolean;\n /** 0..1 progress when known (force `alpha`); `null` for one-shot / unknown. */\n progress: number | null;\n };\n /** Transient overlay/status message, or `null`. */\n message: string | null;\n };\n}\n\n/**\n * Canvas/scene-level configuration — the settings that sit *above* individual\n * layers/behaviours/layouts. Renderer-init options (`preference`, `antialias`,\n * `resolution`, …) are deliberately **not** here: those belong to the renderer\n * adapter, not the syncable definition.\n */\nexport interface CanvasSceneOptions {\n /** Scene background colour (`0xRRGGBB`). */\n backgroundColor?: number;\n /** Suppress the browser's native context menu over the canvas. */\n suppressBrowserContextMenu?: boolean;\n /** Zoom clamp for the abstract camera. */\n zoom: { min: number; max: number };\n /** Initial camera transform applied on load. */\n initialCamera?: CameraTransform;\n /** Optional world/scene bounds (for fit-on-load / clamping), or `null`. */\n worldBounds?: Rect | null;\n /** Default interaction mode the view starts in. */\n defaultViewMode?: string;\n\n // ── Load behaviour ───────────────────────────────────────────────────────\n // These three are *how the scene arrives*, not what it is — but they are\n // authored config like any other, so they live in the definition and\n // round-trip through export / import. The engine reads them on `update()`.\n\n /**\n * Frame the camera on the content once on load. See\n * `CanvasConfig.fitOnLoad`.\n */\n fitOnLoad?: boolean;\n /**\n * Ease the first auto-fit instead of snapping to it. See\n * `CanvasConfig.fitAnimation`.\n */\n fitAnimation?: {\n durationMs?: number;\n easing?: EasingName;\n };\n /**\n * Fade the world content in once, the first time it is worth showing. See\n * `CanvasConfig.entrance`.\n */\n entrance?: {\n kind: 'fade';\n durationMs?: number;\n easing?: EasingName;\n };\n}\n\n/** The empty-but-valid initial {@link CanvasView}. */\nexport function defaultCanvasView(): CanvasView {\n return {\n definition: {\n canvas: { zoom: { min: 0.01, max: 100 } },\n layers: {},\n behaviours: {},\n layouts: {},\n activeLayout: null,\n layoutPreset: null,\n templates: [],\n theme: {},\n toolbars: {},\n },\n interaction: {\n selection: new Set<string>(),\n hover: null,\n states: {},\n raised: {},\n camera: { x: 0, y: 0, zoom: 1 },\n focus: null,\n inspect: null,\n cameraIntent: null,\n transientPins: new Set<string>(),\n viewMode: 'select',\n viewModeArgs: {},\n },\n runtime: {\n layout: { running: false, activeId: null, animate: false, progress: null },\n message: null,\n },\n };\n}\n","import type { LayerData, NodeRecord, EdgeRecord, GroupRecord, AnnotationRecord } from '../data/LayerData';\nimport type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { ReactiveStore } from '../port/types';\nimport type { CanvasSceneOptions, CanvasView } from './CanvasView';\nimport type { ToolbarSpec } from './toolbars';\nimport type { CameraIntent } from '../log/types';\n\n/** Loose option/patch bag for the view's per-instance config. */\ntype Bag = Record<string, unknown>;\n/** Partial camera transform. */\ntype CameraInput = Partial<{ x: number; y: number; zoom: number }>;\n\n/**\n * `createActions` — the **named, action-typed command API** over the kernel.\n *\n * Every mutation is a discoverable method (not a raw `view.update(recipe, …)`),\n * and each **bakes in its action label** (`'view:layer:setStyle'`, `'view:camera:zoom'`, …),\n * so telemetry, history, and the CRDT op-log all read as intent. View commands go\n * through the one `view.update(recipe, action)` seam; data commands proxy to the\n * target {@link LayerData}.\n *\n * Group by concern: `node / edge / group / annotation / positions` (data) and\n * `layers / behaviours / layouts / camera / selection / hover / viewMode / templates /\n * theme / toolbars` (view).\n *\n * ⚠ **Data actions target the default {@link LayerData} store only.** The\n * injected `layer(id)` accessor (see `createCanvasStore`) **throws** for any id\n * where a *custom* {@link DataSource} was registered via `setSource` — e.g.\n * `@invana/graph`'s `GraphStore`. For those, mutate through the domain store's\n * own API (`store.source(id)` / the layer's methods) instead. Unifying the data\n * actions over the `DataSource` interface is future work — audited and\n * deliberately deferred 2026-08-13 (the contract would need write methods it\n * doesn't carry today).\n */\nexport function createActions(\n view: ReactiveStore<CanvasView>,\n layer: (id: string) => LayerData,\n events: CanvasEventBus,\n) {\n // ── view helper: every command names its action ─────────────────────────────\n const v = (action: string, recipe: (s: CanvasView) => void): void => view.update(recipe, action);\n const mergeInto = (bag: Bag | undefined, patch: Bag): Bag => ({ ...(bag ?? {}), ...patch });\n // ── data helper: emit the GRANULAR taxonomy event (e.g. 'data:node:add') on the\n // tap — one per action (the per-frame 'data:flush' delta is separate). ─────\n const di = (type: string, layerId: string, ids: readonly string[]): void =>\n events.publish(type, { action: type, layerId, ids }, { kind: 'data', id: layerId });\n\n return {\n // ── DATA (proxy to the layer's bulk store + an intent record) ─────────────\n node: {\n add: (l: string, n: NodeRecord) => {\n layer(l).addNode(n);\n di('data:node:add', l, [n.id]);\n },\n update: (l: string, id: string, patch: Partial<NodeRecord>) => {\n layer(l).updateNode(id, patch);\n di('data:node:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeNode(id);\n di('data:node:remove', l, [id]);\n },\n moveTo: (l: string, id: string, x: number, y: number) => {\n layer(l).updateNode(id, { x, y });\n di('data:node:move', l, [id]);\n },\n },\n edge: {\n add: (l: string, e: EdgeRecord) => {\n layer(l).addEdge(e);\n di('data:edge:add', l, [e.id]);\n },\n update: (l: string, id: string, patch: Partial<EdgeRecord>) => {\n layer(l).updateEdge(id, patch);\n di('data:edge:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeEdge(id);\n di('data:edge:remove', l, [id]);\n },\n },\n group: {\n add: (l: string, g: GroupRecord) => {\n layer(l).addGroup(g);\n di('data:group:add', l, [g.id]);\n },\n update: (l: string, id: string, patch: Partial<GroupRecord>) => {\n layer(l).updateGroup(id, patch);\n di('data:group:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeGroup(id);\n di('data:group:remove', l, [id]);\n },\n },\n annotation: {\n add: (l: string, a: AnnotationRecord) => {\n layer(l).addAnnotation(a);\n di('data:annotation:add', l, [a.id]);\n },\n update: (l: string, id: string, patch: Partial<AnnotationRecord>) => {\n layer(l).updateAnnotation(id, patch);\n di('data:annotation:update', l, [id]);\n },\n remove: (l: string, id: string) => {\n layer(l).removeAnnotation(id);\n di('data:annotation:remove', l, [id]);\n },\n },\n /** Bulk layout output → node positions (transform-only re-render). */\n positions: {\n apply: (l: string, positions: Iterable<{ id: string; x: number; y: number }>) => {\n const arr = [...positions];\n layer(l).applyPositions(arr);\n di('data:position:apply', l, arr.map((p) => p.id));\n },\n },\n\n // ── VIEW · layers ─────────────────────────────────────────────────────────\n layers: {\n add: (id: string, opts: Bag) => v('view:layer:add', (s) => void (s.definition.layers[id] = opts)),\n update: (id: string, patch: Bag) =>\n v('view:layer:update', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], patch))),\n setStyle: (id: string, style: Bag) =>\n v('view:layer:setStyle', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], { style }))),\n setVisible: (id: string, visible: boolean) =>\n v('view:layer:setVisible', (s) => void (s.definition.layers[id] = mergeInto(s.definition.layers[id], { visible }))),\n remove: (id: string) => v('view:layer:remove', (s) => void delete s.definition.layers[id]),\n },\n\n // ── VIEW · behaviours ─────────────────────────────────────────────────────\n behaviours: {\n add: (id: string, opts: Bag) => v('view:behaviour:add', (s) => void (s.definition.behaviours[id] = opts)),\n update: (id: string, patch: Bag) =>\n v('view:behaviour:update', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], patch))),\n enable: (id: string) =>\n v('view:behaviour:enable', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], { enabled: true }))),\n disable: (id: string) =>\n v('view:behaviour:disable', (s) => void (s.definition.behaviours[id] = mergeInto(s.definition.behaviours[id], { enabled: false }))),\n remove: (id: string) => v('view:behaviour:remove', (s) => void delete s.definition.behaviours[id]),\n },\n\n // ── VIEW · layouts ────────────────────────────────────────────────────────\n layouts: {\n set: (id: string, opts: Bag) => v('view:layout:set', (s) => void (s.definition.layouts[id] = opts)),\n tune: (id: string, patch: Bag) =>\n v('view:layout:tune', (s) => void (s.definition.layouts[id] = mergeInto(s.definition.layouts[id], patch))),\n run: (id: string) => v('view:layout:run', (s) => void (s.definition.activeLayout = id)),\n remove: (id: string) =>\n v('view:layout:remove', (s) => {\n delete s.definition.layouts[id];\n if (s.definition.activeLayout === id) s.definition.activeLayout = null;\n }),\n },\n\n // ── VIEW · camera (interaction; abstract transform) ───────────────────────\n camera: {\n set: (c: CameraInput) => v('view:camera:set', (s) => void (s.interaction.camera = { ...s.interaction.camera, ...c })),\n pan: (dx: number, dy: number) =>\n v('view:camera:pan', (s) => {\n s.interaction.camera = {\n ...s.interaction.camera,\n x: s.interaction.camera.x + dx,\n y: s.interaction.camera.y + dy,\n };\n }),\n zoom: (factor: number) =>\n v('view:camera:zoom', (s) => void (s.interaction.camera = { ...s.interaction.camera, zoom: s.interaction.camera.zoom * factor })),\n zoomTo: (zoom: number) =>\n v('view:camera:zoomTo', (s) => void (s.interaction.camera = { ...s.interaction.camera, zoom })),\n reset: () => v('view:camera:reset', (s) => void (s.interaction.camera = { x: 0, y: 0, zoom: 1 })),\n },\n\n // ── VIEW · selection / hover (interaction) ────────────────────────────────\n selection: {\n set: (ids: Iterable<string>) => v('view:selection:set', (s) => void (s.interaction.selection = new Set(ids))),\n add: (ids: Iterable<string>) =>\n v('view:selection:add', (s) => void (s.interaction.selection = new Set([...s.interaction.selection, ...ids]))),\n toggle: (id: string) =>\n v('view:selection:toggle', (s) => {\n const next = new Set(s.interaction.selection);\n if (next.has(id)) next.delete(id);\n else next.add(id);\n s.interaction.selection = next;\n }),\n clear: () => v('view:selection:clear', (s) => void (s.interaction.selection = new Set())),\n },\n hover: {\n set: (id: string) => v('view:hover:set', (s) => void (s.interaction.hover = id)),\n clear: () => v('view:hover:clear', (s) => void (s.interaction.hover = null)),\n },\n /**\n * Paint-order lift, per source. `source` is the id of whatever is asking\n * (a behaviour id) — each owns its own set, so a hover lift and a selection\n * lift coexist and either can be dropped without disturbing the other.\n * The renderer projects the union; see `CanvasView.interaction.raised`.\n */\n raise: {\n set: (source: string, ids: Iterable<string>) =>\n v('view:raise:set', (s) => void (s.interaction.raised = { ...s.interaction.raised, [source]: new Set(ids) })),\n clear: (source: string) =>\n v('view:raise:clear', (s) => {\n if (!(source in s.interaction.raised)) return;\n const next = { ...s.interaction.raised };\n delete next[source];\n s.interaction.raised = next;\n }),\n },\n\n // ── VIEW · interaction mode (the modeller \"tool\") ─────────────────────────\n viewMode: {\n /**\n * Switch the active mode. `args`, when given, **replaces** the mode's\n * parameters; omit it to keep the current ones (a tool's node kind\n * survives a trip through Select).\n */\n set: (mode: string, args?: Readonly<Record<string, string>>) =>\n v('view:viewMode:set', (s) => {\n s.interaction.viewMode = mode;\n if (args !== undefined) s.interaction.viewModeArgs = { ...args };\n }),\n /** Shallow-merge `patch` into the mode parameters. */\n setArgs: (patch: Readonly<Record<string, string>>) =>\n v('view:viewMode:setArgs', (s) => void (s.interaction.viewModeArgs = { ...s.interaction.viewModeArgs, ...patch })),\n },\n\n // ── VIEW · templates (e.g. node templates) ────────────────────────────────\n templates: {\n create: (template: unknown) =>\n v('view:template:create', (s) => void (s.definition.templates = [...s.definition.templates, template])),\n update: (id: string, patch: Bag) =>\n v('view:template:update', (s) => {\n s.definition.templates = s.definition.templates.map((t) =>\n (t as { id?: string }).id === id ? { ...(t as object), ...patch } : t,\n );\n }),\n remove: (id: string) =>\n v('view:template:remove', (s) => void (s.definition.templates = s.definition.templates.filter((t) => (t as { id?: string }).id !== id))),\n },\n\n // ── VIEW · toolbars (floating chrome over the canvas) ───────────────\n toolbars: {\n /** Add (or replace) the panel `id`. */\n add: (id: string, spec: ToolbarSpec) =>\n v('view:toolbar:add', (s) => void (s.definition.toolbars[id] = spec)),\n /** Shallow-merge `patch` into panel `id` (`items` replaces). No-op when absent. */\n update: (id: string, patch: Partial<ToolbarSpec>) =>\n v('view:toolbar:update', (s) => {\n const cur = s.definition.toolbars[id];\n if (cur) s.definition.toolbars[id] = { ...cur, ...patch };\n }),\n show: (id: string) =>\n v('view:toolbar:show', (s) => {\n const cur = s.definition.toolbars[id];\n if (cur) s.definition.toolbars[id] = { ...cur, visible: true };\n }),\n hide: (id: string) =>\n v('view:toolbar:hide', (s) => {\n const cur = s.definition.toolbars[id];\n if (cur) s.definition.toolbars[id] = { ...cur, visible: false };\n }),\n remove: (id: string) => v('view:toolbar:remove', (s) => void delete s.definition.toolbars[id]),\n },\n\n // ── VIEW · theme ──────────────────────────────────────────────────────────\n theme: {\n set: (patch: Bag) => v('view:theme:set', (s) => void (s.definition.theme = { ...s.definition.theme, ...patch })),\n },\n\n // ── VIEW · scene (canvas-level definition) ────────────────────────────────\n scene: {\n set: (patch: Partial<CanvasSceneOptions>) =>\n v('view:scene:set', (s) => void (s.definition.canvas = { ...s.definition.canvas, ...patch })),\n setBackground: (backgroundColor: number) =>\n v('view:scene:setBackground', (s) => void (s.definition.canvas = { ...s.definition.canvas, backgroundColor })),\n setZoomLimits: (min: number, max: number) =>\n v('view:scene:setZoomLimits', (s) => void (s.definition.canvas = { ...s.definition.canvas, zoom: { min, max } })),\n },\n\n // ── RUNTIME · layout run status (observable, NOT synced) ───────────────────\n layoutStatus: {\n begin: (id: string, animate = false) =>\n v('view:layout:status:begin', (s) => void (s.runtime.layout = { running: true, activeId: id, animate, progress: animate ? 0 : null })),\n progress: (progress: number) =>\n v('view:layout:status:progress', (s) => void (s.runtime.layout = { ...s.runtime.layout, progress })),\n end: () =>\n v('view:layout:status:end', (s) => void (s.runtime.layout = { ...s.runtime.layout, running: false, progress: null })),\n },\n\n // ── RUNTIME · transient overlay message ───────────────────────────────────\n message: {\n show: (text: string) => v('view:message:show', (s) => void (s.runtime.message = text)),\n clear: () => v('view:message:clear', (s) => void (s.runtime.message = null)),\n },\n\n // ── VIEW · focus (highlight-neighbourhood; O(1) set + mode — §7.1B) ────────\n focus: {\n set: (ids: Iterable<string>, dim = true) =>\n v('view:focus:set', (s) => void (s.interaction.focus = { ids: new Set(ids), dim })),\n clear: () => v('view:focus:clear', (s) => void (s.interaction.focus = null)),\n },\n\n // ── VIEW · inspect (whose properties are open) ────────────────────────────\n inspect: {\n set: (id: string) => v('view:inspect:set', (s) => void (s.interaction.inspect = id)),\n clear: () => v('view:inspect:clear', (s) => void (s.interaction.inspect = null)),\n },\n\n // ── VIEW · camera intent (frame the focus / the visible / everything) ─────\n cameraIntent: {\n /** Ask for a framing; the owner performs it once the canvas settles. */\n request: (intent: CameraIntent) =>\n v(\n 'view:cameraIntent:request',\n (s) => void (s.interaction.cameraIntent = { intent, seq: (s.interaction.cameraIntent?.seq ?? 0) + 1 }),\n ),\n },\n\n // ── VIEW · transient pins (drag/resize gesture locks; NOT data `pinned`) ───\n transientPins: {\n add: (ids: Iterable<string>) =>\n v('view:transientPins:add', (s) => void (s.interaction.transientPins = new Set([...s.interaction.transientPins, ...ids]))),\n remove: (ids: Iterable<string>) =>\n v('view:transientPins:remove', (s) => {\n const next = new Set(s.interaction.transientPins);\n for (const id of ids) next.delete(id);\n s.interaction.transientPins = next;\n }),\n clear: () => v('view:transientPins:clear', (s) => void (s.interaction.transientPins = new Set())),\n },\n };\n}\n\n/** The named, action-typed command API (see {@link createActions}). */\nexport type CanvasActions = ReturnType<typeof createActions>;\n","/**\n * **Merge item lists by key** — how an app's default items and a host's\n * overrides combine, for toolbars now and rails and menus later.\n *\n * - A default and an override with the same `key` merge: the override changes\n * only the fields it names.\n * - `hidden: true` on an override removes the item.\n * - `before` / `after` place a new or moved item next to another key; an item\n * that names neither goes at the end. Neither field is kept on the result.\n * - A plain string is the catalog item of that name with its defaults\n * (`'fit'` ≡ `{ key: 'fit' }`); an entry with no `type` takes the catalog\n * item of its key as its base, so `{ key: 'fit', args: { layerId } }` is the\n * catalog's Fit with other args.\n * - An item with no key is matched by its type and its index among the keyless\n * items of that type (the second keyless divider matches the second).\n *\n * Pure: imports nothing. The catalog arrives as a `resolve` function, so this\n * layer never knows which items exist.\n */\n\nimport type { ToolbarItemBase, ToolbarItemSpec } from './toolbars';\n\n/**\n * An override for one item, matched by {@link key}: the fields to change, with\n * no `type`. The catalog item of the same key is its base when nothing else is.\n */\nexport interface ToolbarItemPatch extends Partial<ToolbarItemBase> {\n key: string;\n type?: undefined;\n [field: string]: unknown;\n}\n\n/** One entry in an item list as an author writes it: a full item, a patch by key, or a catalog key. */\nexport type ToolbarItemEntry = ToolbarItemSpec | ToolbarItemPatch | string;\n\n/** Looks a catalog item up by name; `undefined` for a name the catalog lacks. */\nexport type ToolbarItemResolver = (key: string) => ToolbarItemSpec | undefined;\n\ntype Slot = { id: string; item: ToolbarItemSpec | ToolbarItemPatch | string };\n\nconst PLACEMENT = new Set(['before', 'after']);\n\n/** The entry's key; a string is its own key. */\nfunction keyOf(entry: ToolbarItemEntry): string | undefined {\n return typeof entry === 'string' ? entry : entry.key;\n}\n\n/** Drop `before` / `after`: they place an item, they are not part of it. */\nfunction withoutPlacement<T extends object>(item: T): T {\n if (!('before' in item) && !('after' in item)) return item;\n return Object.fromEntries(Object.entries(item).filter(([k]) => !PLACEMENT.has(k))) as T;\n}\n\n/** Ids for a list: the key, or `type#n` for the n-th keyless item of that type. */\nfunction identify(entries: readonly ToolbarItemEntry[]): string[] {\n const seen = new Map<string, number>();\n return entries.map((entry) => {\n const key = keyOf(entry);\n if (key !== undefined) return key;\n const type = (entry as { type?: string }).type ?? '';\n const n = seen.get(type) ?? 0;\n seen.set(type, n + 1);\n return `${type}#${n}`;\n });\n}\n\n/** Insert at `before` / `after` when that key is present, else at the end. */\nfunction place(slots: Slot[], slot: Slot, before?: string, after?: string): void {\n const anchor = before ?? after;\n const at = anchor === undefined ? -1 : slots.findIndex((s) => s.id === anchor);\n if (at < 0) slots.push(slot);\n else slots.splice(before !== undefined ? at : at + 1, 0, slot);\n}\n\n/** Turn a string or a typeless patch into a full item through the catalog; `undefined` when it can't. */\nfunction resolveEntry(entry: Slot['item'], resolve: ToolbarItemResolver): ToolbarItemSpec | undefined {\n if (typeof entry === 'string') return resolve(entry);\n if (entry.type !== undefined) return entry as ToolbarItemSpec;\n const base = resolve(entry.key);\n return base ? ({ ...base, ...entry, type: base.type } as ToolbarItemSpec) : undefined;\n}\n\n/**\n * Merge `overrides` into `defaults` by key. With `resolve`, every string and\n * typeless patch becomes a full item and one the catalog lacks is dropped;\n * without it they stay as written, for a later merge or the renderer to\n * resolve.\n */\nexport function mergeItems(\n defaults: readonly ToolbarItemEntry[],\n overrides: readonly ToolbarItemEntry[],\n resolve: ToolbarItemResolver,\n): ToolbarItemSpec[];\nexport function mergeItems(\n defaults: readonly ToolbarItemEntry[],\n overrides: readonly ToolbarItemEntry[],\n resolve?: ToolbarItemResolver,\n): ToolbarItemEntry[];\nexport function mergeItems(\n defaults: readonly ToolbarItemEntry[],\n overrides: readonly ToolbarItemEntry[],\n resolve?: ToolbarItemResolver,\n): ToolbarItemEntry[] {\n const defaultIds = identify(defaults);\n const slots: Slot[] = defaults.map((item, i) => ({ id: defaultIds[i] as string, item }));\n const overrideIds = identify(overrides);\n\n overrides.forEach((override, i) => {\n const id = overrideIds[i] as string;\n const at = slots.findIndex((s) => s.id === id);\n const patch = typeof override === 'string' ? undefined : override;\n\n if (patch?.hidden === true) {\n if (at >= 0) slots.splice(at, 1);\n return;\n }\n const before = patch?.before;\n const after = patch?.after;\n\n if (at < 0) {\n place(slots, { id, item: patch ? withoutPlacement(patch) : override }, before, after);\n return;\n }\n const current = slots[at] as Slot;\n // A string matching a present key is that item with its defaults: nothing to change.\n const merged: Slot['item'] = patch\n ? (withoutPlacement(typeof current.item === 'string' ? { ...patch, key: current.item } : { ...current.item, ...patch }) as Slot['item'])\n : current.item;\n // Keep a full item's type when the patch names none.\n if (typeof merged !== 'string' && typeof current.item !== 'string' && merged.type === undefined) {\n (merged as { type?: string }).type = current.item.type;\n }\n if (before === undefined && after === undefined) {\n slots[at] = { id, item: merged };\n return;\n }\n slots.splice(at, 1);\n place(slots, { id, item: merged }, before, after);\n });\n\n if (!resolve) return slots.map((s) => s.item);\n const out: ToolbarItemSpec[] = [];\n for (const s of slots) {\n const item = resolveEntry(s.item, resolve);\n if (item) out.push(item);\n }\n return out;\n}\n","/** Who emitted an event. */\nexport type EventSourceKind = 'canvas' | 'layer' | 'behaviour' | 'layout' | 'store' | 'data';\n\n/** The emitting instance — `kind` + its id. */\nexport interface EventSource {\n kind: EventSourceKind;\n id: string;\n}\n\n/**\n * A structured event envelope as seen on the **tap** channel: the type, a\n * timestamp, the source instance, and the payload. One tap subscriber reading\n * these reconstructs the whole loop (input → state change → render) for telemetry\n * and collaboration.\n */\nexport interface CanvasEvent<P = unknown> {\n type: string;\n timestamp: number;\n source: EventSource;\n payload: P;\n}\n\n/** The default source for bus-level emits with no explicit origin. */\nexport const CANVAS_SOURCE: EventSource = { kind: 'canvas', id: 'canvas' };\n","import type { SpecFlush } from '../../specs/SpecStore';\nimport type { LayerFlush } from '../data/LayerData';\nimport type { FrameTick } from '../frame';\nimport type { ResolvedTheme } from '../theme/types';\nimport { CANVAS_SOURCE, type CanvasEvent, type EventSource } from './CanvasEvent';\nimport { EventEmitter, type Listener } from './EventEmitter';\n\n/**\n * The canvas-wide event map. Consumers (engine, domain) **augment** this via\n * declaration merging — `declare module '@invana/canvas-core' { interface\n * CanvasGlobalEvents { 'shape:click': … } }` — so new events are typed without\n * touching the core.\n */\nexport interface CanvasGlobalEvents {\n // ── coarse aggregate channels (kernel-emitted) ──────────────────────────────\n /**\n * A `view`-store mutation, bridged onto the bus (see `createCanvasStore`).\n * `durationMs` is the update's produce+commit wall-clock cost, when the store\n * reports it — so a tap can attribute time without a separate telemetry sink.\n */\n 'state:change': { action?: string; changedPaths: string[]; durationMs?: number };\n /** A `layer` data flush (nodes/edges/groups/annotations delta), bridged onto the bus. */\n 'data:flush': { layerId: string; delta: LayerFlush };\n /**\n * One layer's coalesced **spec** changes — the visual description, ids only.\n * Domain-free by construction: a renderer subscribes to this and never learns\n * what a node or an edge is. See `docs/renderer-split-design.md` §4.2b.\n */\n 'specs:flush': { layerId: string; delta: SpecFlush };\n /** A named data **intent** — one per data action (audit / collab), distinct from the per-frame flush. */\n 'data:intent': { action: string; layerId: string; ids: readonly string[] };\n\n // ── scene — registry composition (engine-emitted) ───────────────────────────\n 'scene:layer:add': { id: string };\n 'scene:layer:remove': { id: string };\n /**\n * A layer's whole-layer `visible` flag changed via `Layer.setVisible`. Lets\n * dependent layers (e.g. a `MiniMapLayer` mirroring a source graph) react\n * without polling. `visible` is the post-change value.\n */\n 'scene:layer:visibilitychange': { id: string; visible: boolean };\n 'scene:behaviour:register': { id: string };\n /**\n * A behaviour was removed via `BehaviourRegistry.unregister` (or `clear`).\n * Fires after `scene:behaviour:disable` (when it was enabled) and after the\n * behaviour is destroyed — the counterpart of `scene:layer:remove`.\n */\n 'scene:behaviour:unregister': { id: string };\n 'scene:behaviour:enable': { id: string };\n 'scene:behaviour:disable': { id: string };\n 'scene:layout:add': { id: string };\n 'scene:layout:remove': { id: string };\n\n // ── input — raw user input (engine/renderer-emitted; behaviours consume) ─────\n 'input:node:click': { layerId: string; id: string; x: number; y: number };\n 'input:node:hover': { layerId: string; id: string | null };\n 'input:node:drag:start': { layerId: string; id: string };\n 'input:node:drag:end': { layerId: string; id: string };\n 'input:background:click': { x: number; y: number };\n 'input:background:contextmenu': { x: number; y: number };\n /**\n * A pan **gesture** reported by the renderer (drag / keyboard / inertia) —\n * gesture *intent*, distinct from the resulting `view.interaction.camera` change\n * (a `state:change`). `x`/`y` are the world-origin offset the camera settled on.\n */\n 'input:camera:pan': { x: number; y: number };\n /** A zoom **gesture** reported by the renderer (wheel / pinch). `scale` is the resolved uniform zoom; `center*` the screen pivot. */\n 'input:camera:zoom': { scale: number; centerX: number; centerY: number };\n\n // ── layout — execution lifecycle (engine-emitted) ───────────────────────────\n /** A layout run started. `nodeCount`/`edgeCount`/`animate` describe the run when the producer knows them. */\n 'layout:run:start': {\n id: string;\n layerId: string;\n nodeCount?: number;\n edgeCount?: number;\n animate?: boolean;\n /** The run was asked to leave the camera alone (`LayoutRunOptions.preserveCamera`). */\n preserveCamera?: boolean;\n /** The run frames itself (`LayoutRunOptions.fitCamera`) — other fitters stand down. */\n fitCamera?: boolean;\n };\n /** A layout run ended. `reason` distinguishes a natural settle from an external stop / abort. */\n 'layout:run:end': {\n id: string;\n layerId: string;\n reason?: 'settled' | 'stopped' | 'cancelled';\n /** The run was asked to leave the camera alone (`LayoutRunOptions.preserveCamera`). */\n preserveCamera?: boolean;\n /** The run frames itself (`LayoutRunOptions.fitCamera`) — other fitters stand down. */\n fitCamera?: boolean;\n };\n 'layout:run:tick': { id: string; progress?: number; preserveCamera?: boolean; fitCamera?: boolean };\n /** An off-screen solve advanced — `done` of `total` iterations. Nothing is drawn until `layout:run:tick` / `end`. */\n 'layout:run:progress': { id: string; layerId: string; done: number; total: number };\n\n // ── render / canvas — lifecycle (engine/renderer-emitted) ───────────────────\n 'canvas:renderer:ready': { backend: string; capabilities?: Record<string, unknown> };\n /**\n * The active renderer crashed at **render time** and the engine has halted its\n * render loop. Emitted once (experimental WebGPU only — see\n * `CanvasOptions.preference`); the consumer should tear the canvas down and\n * re-init on `to` (WebGL). `reason` is a short diagnostic tag.\n */\n 'canvas:renderer:fallback': { from: string; to: string; reason?: string };\n /**\n * One measured engine frame — emitted once per `Canvas.tickOnce`. Carries the\n * inter-frame period, per-phase CPU breakdown, and the attributed\n * {@link InteractionKind}, so a tap can drive an FPS trace + attribute dips to\n * the gesture that caused them. See {@link FrameTick}.\n */\n 'render:loop:tick': FrameTick;\n /** The shared status-message channel. `text: null` clears; `timeout` (ms) auto-clears. */\n 'canvas:message:show': { text: string | null; timeout?: number };\n /** A tap dropped an event (filtered or sampled out) — diagnostic. */\n 'tap:dropped': { type: string; reason: 'excluded' | 'sampled' };\n\n // ── theme — resolved-theme broadcast (CanvasThemeState.set) ──────────────────\n 'theme:change': ResolvedTheme;\n}\n\n/**\n * The granular **`<domain>:<subject>:<action>`** types (`view:layer:setStyle`,\n * `data:node:add`, …) are open-ended — emitted via {@link CanvasEventBus.publish}\n * (they ride on the tap, keyed by the action label) rather than enumerated here.\n * The map above types the **finite, engine-emitted** events for `on()`/`emit()`.\n */\n\n/** Per-tap filters. */\nexport interface TapOptions {\n /** Event `type`s to drop from this tap. */\n exclude?: readonly string[];\n /** Fraction (0..1) of events to forward — cheap sampling for costly sinks. */\n sampleRate?: number;\n}\n\n/** A tap receives every emission as a structured {@link CanvasEvent}. */\nexport type Tap = (event: CanvasEvent) => void;\n\n/**\n * Canvas-wide event bus: typed `on`/`emit` for known events, **plus a tap\n * channel** that receives every emission (typed *and* forwarded scoped events) as\n * a structured {@link CanvasEvent}. The tap is the single place telemetry /\n * collaboration observe the whole stream — `bus.tap(e => sink(e))`.\n *\n * Renderer-free: the engine wires pixi pointer events *into* this; the bus knows\n * nothing about pixi.\n */\nexport class CanvasEventBus {\n private readonly emitter = new EventEmitter<CanvasGlobalEvents>();\n private readonly taps = new Set<{ fn: Tap; opts: TapOptions }>();\n private readonly now: () => number;\n private readonly rand: () => number;\n\n constructor(opts?: { now?: () => number; random?: () => number }) {\n this.now = opts?.now ?? (() => Date.now());\n this.rand = opts?.random ?? (() => Math.random());\n }\n\n /** Subscribe to a typed global event. Returns an unsubscribe fn (or use {@link off}). */\n on<K extends keyof CanvasGlobalEvents>(\n type: K,\n listener: Listener<CanvasGlobalEvents[K]>,\n ): () => void {\n return this.emitter.on(type, listener);\n }\n\n /** Remove a previously-registered typed listener (the {@link on} handler by reference). */\n off<K extends keyof CanvasGlobalEvents>(\n type: K,\n listener: Listener<CanvasGlobalEvents[K]>,\n ): void {\n this.emitter.off(type, listener);\n }\n\n /** Emit a typed global event — reaches typed listeners and the tap channel. */\n emit<K extends keyof CanvasGlobalEvents>(\n type: K,\n payload: CanvasGlobalEvents[K],\n source: EventSource = CANVAS_SOURCE,\n ): void {\n this.emitter.emit(type, payload);\n this.toTaps(type as string, payload, source);\n }\n\n /**\n * Forward a **scoped / foreign** event (not in {@link CanvasGlobalEvents}) to the\n * tap channel only — used by {@link SourceEmitter} so a store/layer/behaviour's\n * own events reach the canvas tap without being global-bus types.\n */\n publish(type: string, payload: unknown, source: EventSource): void {\n this.toTaps(type, payload, source);\n }\n\n private toTaps(type: string, payload: unknown, source: EventSource): void {\n if (this.taps.size === 0) return;\n const event: CanvasEvent = { type, timestamp: this.now(), source, payload };\n for (const { fn, opts } of [...this.taps]) {\n if (opts.exclude?.includes(type)) continue;\n if (opts.sampleRate !== undefined && this.rand() > opts.sampleRate) continue;\n fn(event);\n }\n }\n\n /** Subscribe to the whole event stream (structured envelopes). */\n tap(fn: Tap, opts: TapOptions = {}): () => void {\n const entry = { fn, opts };\n this.taps.add(entry);\n return () => this.taps.delete(entry);\n }\n\n clearTaps(): void {\n this.taps.clear();\n }\n\n removeAllListeners(): void {\n this.emitter.removeAllListeners();\n this.taps.clear();\n }\n}\n","import type { CanvasEventBus } from '../events/CanvasEventBus';\nimport type { ResolvedTheme, ThemeState } from './types';\n\n/**\n * The default {@link ThemeState} — holds the current {@link ResolvedTheme} and\n * broadcasts `theme:change` on the bus whenever it is {@link set}. Renderer-free;\n * a single publisher (the domain `ThemeBehaviour`) resolves authored config →\n * `ResolvedTheme` and calls {@link set}. Theme-aware layers subscribe to\n * `theme:change` (or read {@link current}) and recolour.\n */\nexport class CanvasThemeState implements ThemeState {\n private _current: ResolvedTheme | null = null;\n\n constructor(private readonly bus: CanvasEventBus) {}\n\n current(): ResolvedTheme | null {\n return this._current;\n }\n\n set(theme: ResolvedTheme): void {\n this._current = theme;\n this.bus.emit('theme:change', theme, { kind: 'store', id: 'theme' });\n }\n}\n","/**\n * Renderer-free **theme state** for the kernel — the fully-**resolved** theme the\n * engine publishes and theme-aware layers recolour from. Relocated from the\n * engine (`@invana/canvas`); roles are plain `string` keys → colour numbers (the\n * named `ColorRole` vocabulary stays in `@invana/graph`).\n *\n * Two distinct things, don't conflate them:\n * - **Authored theme config** (registry / active family / mode / accent) lives in\n * `view.definition.theme` (serialisable, synced).\n * - **The resolved theme** below is the *derived* output a `ThemeBehaviour`\n * computes from that config + mode, and publishes via {@link ThemeState.set}.\n */\n\n/** The concrete kind a theme mode resolves to. */\nexport type ThemeKind = 'light' | 'dark';\n\n/** Mode selector. `'system'` follows the host `prefers-color-scheme`; the rest pin. */\nexport type ThemeMode = 'system' | 'light' | 'dark';\n\n/** A fully-resolved theme — every role already a colour number. Plain JSON; no pixi. */\nexport interface ResolvedTheme {\n readonly kind: ThemeKind;\n /** Opaque family name (`'default'` | `'forest'` | …) — meaningful to the app, not the kernel. */\n readonly name: string;\n /** Role name → `0xRRGGBB`. The engine theme has no role *enum*; roles are strings. */\n readonly palette: Readonly<Record<string, number>>;\n /** Optional fill-by-category ramp (consumed by colour-by-label / minimap). */\n readonly categorical?: readonly number[];\n}\n\n/** The theme channel — read the current resolved theme, or set (and broadcast) a new one. */\nexport interface ThemeState {\n /** The current resolved theme, or `null` before the first {@link set}. */\n current(): ResolvedTheme | null;\n /** Store + broadcast a resolved theme (emits `theme:change`). */\n set(theme: ResolvedTheme): void;\n}\n\n// ─── The `inherit` sentinel ──────────────────────────────────────────────────\n\n/**\n * The **inherit sentinel** — the value a themed colour option carries to mean\n * *\"resolve me from the active theme's palette\"* rather than pinning a colour.\n *\n * It exists because a single-tier option has no other way to say it. An option\n * that is simply absent falls back to a hardcoded default; an option holding a\n * colour pins that colour. `'inherit'` is the third state, and it is the one\n * that should usually be the *default*:\n *\n * | Value | Meaning |\n * |---|---|\n * | `'inherit'` | Follow the palette role the surface declares. Recolours on every `theme:change` |\n * | `0x0f172a` / `'#0f172a'` | Pinned by the author. The theme never touches it |\n *\n * **Config vocabulary, never spec vocabulary.** `'inherit'` is legal in a\n * serialisable *option* and is resolved — via {@link resolveThemed} — at the\n * moment a surface paints. It must never reach a renderer spec: the renderer\n * sees numbers, always.\n *\n * Cascading surfaces don't need it. Where a value already resolves through\n * tiers (a graph node's style: layer template → per-type binding → per-node →\n * state), **absence already means inherit**, exactly as in CSS, and the theme\n * belongs in a tier *below* the author rather than in a sentinel.\n *\n * @see rfc:feat-2026-09-11-a-colour-is-either-themed-or-manual-never-both\n */\nexport const INHERIT = 'inherit';\n\n/** The literal type of {@link INHERIT}. */\nexport type Inherit = typeof INHERIT;\n\n/**\n * A themed option: either a concrete value of `T` (pinned by the author) or\n * {@link INHERIT} (resolved from the palette). Resolve with\n * {@link resolveThemed}.\n */\nexport type Themed<T> = T | Inherit;\n\n/** Narrow a themed option to the {@link INHERIT} sentinel. */\nexport function isInherit(value: unknown): value is Inherit {\n return value === INHERIT;\n}\n\n/**\n * Resolve a themed colour option against a published palette.\n *\n * A concrete value passes through untouched — an author-set colour always wins\n * over the theme, and keeps winning across theme switches. {@link INHERIT}\n * reads the first of `roles` the palette actually carries, falling back to\n * `fallback` when no theme has been published yet or the palette omits every\n * role (which is what the single-layer `ThemeBehaviour` shorthand's empty\n * palette does).\n *\n * @param value The option as authored — a colour, or {@link INHERIT}.\n * @param palette The active `ResolvedTheme.palette`, or `null` before the first publish.\n * @param roles Role name, or names tried in order (e.g. `['divider', 'stroke']`).\n * @param fallback Used when `value` is `'inherit'` and no role resolves.\n *\n * @example\n * ```ts\n * // `backgroundColor` defaults to 'inherit' → follows the theme's `surface`\n * const fill = resolveThemed(opts.backgroundColor, theme?.palette, 'surface', '#f8fafc');\n * ```\n */\nexport function resolveThemed<T>(\n value: Themed<T>,\n palette: Readonly<Record<string, number>> | null | undefined,\n roles: string | readonly string[],\n fallback: T,\n): T | number {\n if (!isInherit(value)) return value;\n if (palette) {\n for (const role of typeof roles === 'string' ? [roles] : roles) {\n const resolved = palette[role];\n if (resolved !== undefined) return resolved;\n }\n }\n return fallback;\n}\n","/**\n * `ColumnStore<TSchema>` — typed-array column store for **bulk hot data** (the\n * kernel's machine-rate **DATA-HOT lane**: node `x`/`y`, flags, bulk attrs).\n *\n * Relocated into `@invana/canvas-store` (decision D1) so the renderer-free kernel\n * owns the data hot path; `@invana/canvas` consumes it (and may re-export for\n * back-compat). Imports **no** drawing library.\n *\n * Designed to scale to millions of items at machine-rate mutation (1000s/sec from\n * external feeds). Where the reactive store (immer) makes per-mutation\n * structural-sharing trade-offs that cap out around 5–10k for hot data,\n * `ColumnStore` mutates typed-array slots in place at ~10 ns per write — so\n * layout churn / position streams **never** touch the reactive/CRDT path.\n *\n * **Mental model:** one id-keyed object `{ id:'n-42', x:100, y:50 }` becomes\n * slot 17 across N parallel typed-array columns. Lookup is id → slot\n * (`Map<string, number>`), then columns are read/written by indexing slot. Slots\n * recycle on remove, so buffers stay compact under churn.\n *\n * @example\n * type NodeSchema = { x: 'f32'; y: 'f32'; flags: 'u8' };\n * const nodes = new ColumnStore<NodeSchema>({ x: 'f32', y: 'f32', flags: 'u8' });\n * nodes.add('n-1', { x: 10, y: 20, flags: 0 });\n * // Renderer / layout fast path — hold refs once, write directly:\n * const xCol = nodes.column('x'); const slot = nodes.slot('n-1')!;\n * xCol[slot] = 40; // ~10 ns\n * nodes.touch(); // bump version after fast-path writes\n */\n\n// ─── Schema ───────────────────────────────────────────────────────────────\n\n/**\n * Numeric type tags for typed-array columns. Each maps to a JS TypedArray ctor.\n * `i8/u8` — bytes (booleans, bitfields, packed enums); `i16/u16` — short ints;\n * `i32/u32` — slot refs / packed colours / hashes; `f32` — coordinates / weights\n * (default); `f64` — only when precision matters.\n */\nexport type ColumnType = 'i8' | 'u8' | 'i16' | 'u16' | 'i32' | 'u32' | 'f32' | 'f64';\n\nexport type ColumnSchema = Record<string, ColumnType>;\n\n// All TypedArray slots round-trip as `number`.\nexport type ColumnValue<T extends ColumnType> = T extends 'f32' | 'f64' ? number : number;\n\n// Map a `ColumnType` tag to its underlying TypedArray.\nexport type ColumnArray<T extends ColumnType> = T extends 'i8'\n ? Int8Array\n : T extends 'u8'\n ? Uint8Array\n : T extends 'i16'\n ? Int16Array\n : T extends 'u16'\n ? Uint16Array\n : T extends 'i32'\n ? Int32Array\n : T extends 'u32'\n ? Uint32Array\n : T extends 'f32'\n ? Float32Array\n : T extends 'f64'\n ? Float64Array\n : never;\n\n/** Shape of a row in `add()` / `addBulk()`: each schema field maps to a number. */\nexport type RowOf<TSchema extends ColumnSchema> = {\n [K in keyof TSchema]: ColumnValue<TSchema[K]>;\n};\n\n// ─── TypedArray ctor lookup ───────────────────────────────────────────────\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst TYPED_ARRAY_CTOR: Record<ColumnType, new (length: number) => any> = {\n i8: Int8Array,\n u8: Uint8Array,\n i16: Int16Array,\n u16: Uint16Array,\n i32: Int32Array,\n u32: Uint32Array,\n f32: Float32Array,\n f64: Float64Array,\n};\n\n// ─── Options ──────────────────────────────────────────────────────────────\n\nexport interface ColumnStoreOptions {\n /** Initial slot capacity. Doubles on overflow. Default 256. */\n initialCapacity?: number;\n /** Max capacity. Throws on overflow. Default 16_777_216 (~16M). */\n maxCapacity?: number;\n}\n\n// ─── ColumnStore ──────────────────────────────────────────────────────────\n\nexport class ColumnStore<TSchema extends ColumnSchema = ColumnSchema> {\n private readonly schema: TSchema;\n private readonly columnNames: readonly (keyof TSchema)[];\n private readonly maxCapacity: number;\n\n /** id → slot. The only object-keyed lookup on the hot path. */\n private readonly idIndex: Map<string, number> = new Map();\n /** slot → id. Filled slots have a string; recycled holes have `undefined`. */\n private readonly idReverse: (string | undefined)[] = [];\n /** Stack of recycled slots. `add()` pops from here before extending. */\n private readonly freeSlots: number[] = [];\n\n /** TypedArray per column. Replaced on grow (new buffer with copied data). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private columns: Record<keyof TSchema, any>;\n\n /** Current capacity (length of each TypedArray). */\n private _capacity: number;\n /** High-water mark — largest slot index ever assigned + 1. Not necessarily filled. */\n private _highWater = 0;\n\n /** Mutation version. Increments on any add/remove/set or `touch()`. */\n private _version = 0;\n\n constructor(schema: TSchema, opts: ColumnStoreOptions = {}) {\n this.schema = schema;\n this.columnNames = Object.keys(schema) as (keyof TSchema)[];\n this._capacity = Math.max(1, opts.initialCapacity ?? 256);\n this.maxCapacity = opts.maxCapacity ?? 16_777_216;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.columns = {} as Record<keyof TSchema, any>;\n for (const name of this.columnNames) {\n const Ctor = TYPED_ARRAY_CTOR[schema[name]];\n this.columns[name] = new Ctor(this._capacity);\n }\n }\n\n // ─── Read accessors ─────────────────────────────────────────────────────\n\n /** Number of items currently stored. */\n get size(): number {\n return this.idIndex.size;\n }\n\n /** Current allocated capacity. Grows automatically when filled. */\n get capacity(): number {\n return this._capacity;\n }\n\n /** Mutation counter — bumps on any change. Subscribers diff this. */\n get version(): number {\n return this._version;\n }\n\n /** True iff `id` has been added. */\n has(id: string): boolean {\n return this.idIndex.has(id);\n }\n\n /** Returns the slot for `id`, or `undefined`. Useful for the renderer fast path. */\n slot(id: string): number | undefined {\n return this.idIndex.get(id);\n }\n\n /** Returns the id at `slot`, or `undefined` if the slot is free. */\n idAt(slot: number): string | undefined {\n return this.idReverse[slot];\n }\n\n /**\n * Direct access to a column's TypedArray. **Holds a stable reference until the\n * column is grown** (then the buffer is replaced). Use {@link version} to detect\n * grow events. Renderer/layout fast path: cache `column(name)` + `slot(id)` once\n * per frame and write directly, then call {@link touch}.\n */\n column<K extends keyof TSchema>(name: K): ColumnArray<TSchema[K]> {\n return this.columns[name] as ColumnArray<TSchema[K]>;\n }\n\n /** Read a single value. ~50 ns: Map.get + TypedArray read. */\n get<K extends keyof TSchema>(id: string, name: K): ColumnValue<TSchema[K]> | undefined {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return undefined;\n return this.columns[name][slot] as ColumnValue<TSchema[K]>;\n }\n\n /** Materialise a full row by id. Allocates an object — avoid in hot loops. */\n row(id: string): RowOf<TSchema> | undefined {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return undefined;\n const out = {} as RowOf<TSchema>;\n for (const name of this.columnNames) {\n out[name] = this.columns[name][slot];\n }\n return out;\n }\n\n // ─── Mutation ───────────────────────────────────────────────────────────\n\n /** Add a new item. Throws if `id` already exists. Reuses a recycled slot when available. */\n add(id: string, row: RowOf<TSchema>): number {\n if (this.idIndex.has(id)) {\n throw new Error(`ColumnStore: id \"${id}\" already exists`);\n }\n const slot = this.allocSlot();\n this.idIndex.set(id, slot);\n this.idReverse[slot] = id;\n for (const name of this.columnNames) {\n this.columns[name][slot] = row[name];\n }\n this._version++;\n return slot;\n }\n\n /** Bulk add. Grows once if needed (cheaper than N individual grows). Throws on duplicate id. */\n addBulk(items: ReadonlyArray<{ id: string; row: RowOf<TSchema> }>): void {\n if (items.length === 0) return;\n const projected = this.idIndex.size + items.length;\n if (projected > this._capacity) this.grow(projected);\n for (const { id, row } of items) {\n if (this.idIndex.has(id)) {\n throw new Error(`ColumnStore.addBulk: id \"${id}\" already exists`);\n }\n const slot = this.allocSlot();\n this.idIndex.set(id, slot);\n this.idReverse[slot] = id;\n for (const name of this.columnNames) {\n this.columns[name][slot] = row[name];\n }\n }\n this._version++;\n }\n\n /** Set a single field. ~50 ns. No-op if id doesn't exist. */\n set<K extends keyof TSchema>(id: string, name: K, value: ColumnValue<TSchema[K]>): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n this.columns[name][slot] = value;\n this._version++;\n }\n\n /** Update multiple fields of one item in one call (one version bump). */\n update(id: string, partial: Partial<RowOf<TSchema>>): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n for (const name of this.columnNames) {\n if (name in partial) {\n this.columns[name][slot] = partial[name] as number;\n }\n }\n this._version++;\n }\n\n /** Remove an item. Recycles the slot. No-op if id doesn't exist. */\n remove(id: string): void {\n const slot = this.idIndex.get(id);\n if (slot === undefined) return;\n this.idIndex.delete(id);\n this.idReverse[slot] = undefined;\n this.freeSlots.push(slot);\n this._version++;\n }\n\n /** Bulk remove. */\n removeBulk(ids: readonly string[]): void {\n for (const id of ids) {\n const slot = this.idIndex.get(id);\n if (slot === undefined) continue;\n this.idIndex.delete(id);\n this.idReverse[slot] = undefined;\n this.freeSlots.push(slot);\n }\n this._version++;\n }\n\n /**\n * Mark the store as mutated without an API change — call after batches of\n * fast-path writes via `column(...)[slot] = ...` so version-driven subscribers\n * re-read.\n */\n touch(): void {\n this._version++;\n }\n\n /** Drop all items + recycled slots. Keeps capacity (no shrink). */\n clear(): void {\n this.idIndex.clear();\n this.idReverse.length = 0;\n this.freeSlots.length = 0;\n this._highWater = 0;\n this._version++;\n }\n\n // ─── Iteration ──────────────────────────────────────────────────────────\n\n /** Iterate (id, slot) for currently-live ids. O(size) — does not walk holes. */\n forEach(cb: (id: string, slot: number) => void): void {\n for (const [id, slot] of this.idIndex) cb(id, slot);\n }\n\n /** Iterator over live ids only. */\n ids(): IterableIterator<string> {\n return this.idIndex.keys();\n }\n\n // ─── Internals ──────────────────────────────────────────────────────────\n\n private allocSlot(): number {\n const recycled = this.freeSlots.pop();\n if (recycled !== undefined) return recycled;\n if (this._highWater >= this._capacity) this.grow(this._capacity * 2);\n return this._highWater++;\n }\n\n /** Grow each column to at least `target` (doubling past it). */\n private grow(target: number): void {\n let next = this._capacity;\n while (next < target) next *= 2;\n if (next > this.maxCapacity) {\n throw new Error(`ColumnStore: requested capacity ${target} exceeds max ${this.maxCapacity}`);\n }\n for (const name of this.columnNames) {\n const Ctor = TYPED_ARRAY_CTOR[this.schema[name]];\n const grown = new Ctor(next);\n grown.set(this.columns[name]);\n this.columns[name] = grown;\n }\n this._capacity = next;\n }\n}\n","/**\n * `LayerData` — the **non-reactive** graph data for one source: four record\n * collections (nodes · edges · groups · annotations) with full CRUD, **bulk\n * position updates** (layout output), and **one coalesced `flush` per frame**\n * carrying a per-kind delta. Subscribers (the renderer) rebuild only the delta.\n *\n * **Two lanes (the two physics).** Bulk + machine-rate → it lives *outside* the\n * reactive `view` store:\n * - **COLD** — `Map<id, record>` for human-rate fields (payload/label/style/…).\n * - **HOT** — a typed-array {@link ColumnStore} for node **positions** (`x`/`y`)\n * and a `flags` byte (has-position / pinned / disabled / hidden). A position\n * write is ~10 ns (one `Float32Array` slot), no per-node object, no GC. The\n * layout/renderer fast path holds the column ref and writes slots directly\n * (see {@link positions} + {@link touchPositions}).\n *\n * `node(id)` stitches the two lanes back into one record on read (cold reads are\n * human-rate; the hot path reads the column directly). The `flush` delta shape is\n * **unchanged** by the lane split — `moved` (position-only) stays separate from\n * `changed` (structure), so a move is a transform-only re-render.\n *\n * **When** the coalesced flush fires is the {@link FlushMode} (default `'microtask'`);\n * the engine flips its stores to `'manual'` and drains them from one rAF loop. See\n * `docs/canvas-store-data-event-flow.md` §2.2.\n */\n\nimport { ColumnStore } from './ColumnStore';\nimport { scheduleFlush, type FlushMode } from './flush';\n\nexport interface NodeRecord {\n id: string;\n x?: number;\n y?: number;\n [key: string]: unknown;\n}\nexport interface EdgeRecord {\n id: string;\n source: string;\n target: string;\n [key: string]: unknown;\n}\nexport interface GroupRecord {\n id: string;\n memberIds: string[];\n /** Derived encapsulating geometry (hull / rect / …) — computed by a deriver. */\n geometry?: unknown;\n [key: string]: unknown;\n}\nexport interface AnnotationRecord {\n id: string;\n kind: string;\n [key: string]: unknown;\n}\n\n/** Added / changed / removed ids for one collection. */\nexport interface KindDelta {\n added: string[];\n changed: string[];\n removed: string[];\n}\n/** Nodes also carry `moved` — position-only changes (transform-only re-render). */\nexport interface NodeDelta extends KindDelta {\n /** Ids whose position changed this frame. Empty when {@link movedAll} is set. */\n moved: string[];\n /**\n * Every node moved (a force-sim tick via {@link LayerData.touchPositions}) —\n * `moved` is left **empty** so the kernel doesn't allocate an N-id array each\n * frame; the renderer iterates all positions directly. O(1) per flush.\n */\n movedAll: boolean;\n}\n\n/** The per-frame coalesced delta across all four collections. */\nexport interface LayerFlush {\n nodes: NodeDelta;\n edges: KindDelta;\n groups: KindDelta;\n annotations: KindDelta;\n /** Monotonic version — bumps once per flush. */\n version: number;\n}\n\n/** Bulk seed/replace input. */\nexport interface GraphInput {\n nodes?: readonly NodeRecord[];\n edges?: readonly EdgeRecord[];\n groups?: readonly GroupRecord[];\n annotations?: readonly AnnotationRecord[];\n}\n\n/** The hot-lane schema: positions (`x`/`y`) + a packed `flags` byte. */\nexport type PosSchema = { x: 'f32'; y: 'f32'; flags: 'u8' };\nconst POS_SCHEMA: PosSchema = { x: 'f32', y: 'f32', flags: 'u8' };\n\n/** Bits in the node `flags` column. `HAS_POSITION` distinguishes unset from `(0,0)`. */\nexport const NODE_FLAG = {\n HAS_POSITION: 1,\n PINNED: 2,\n DISABLED: 4,\n HIDDEN: 8,\n} as const;\n\n/** Streaming/ingestion lifecycle for a data source. */\nexport type QueryStatus = 'idle' | 'loading' | 'streaming' | 'error';\n\n/** A named data mutation, recorded for audit / collaboration (distinct from the per-frame flush). */\nexport interface IntentLogEntry {\n action: string;\n ids?: readonly string[];\n ts: number;\n}\n\ninterface KindDirty {\n added: Set<string>;\n changed: Set<string>;\n removed: Set<string>;\n}\nconst newDirty = (): KindDirty => ({ added: new Set(), changed: new Set(), removed: new Set() });\nconst drain = (d: KindDirty): KindDelta => ({\n added: [...d.added],\n changed: [...d.changed],\n removed: [...d.removed],\n});\nconst clearDirty = (d: KindDirty): void => {\n d.added.clear();\n d.changed.clear();\n d.removed.clear();\n};\n\nexport class LayerData {\n /** COLD lane — node records WITHOUT `x`/`y` (positions live in {@link _pos}). */\n private readonly _nodes = new Map<string, NodeRecord>();\n /** HOT lane — typed-array `x`/`y`/`flags` columns, keyed by node id. */\n private readonly _pos = new ColumnStore<PosSchema>(POS_SCHEMA);\n private readonly _edges = new Map<string, EdgeRecord>();\n private readonly _groups = new Map<string, GroupRecord>();\n private readonly _annotations = new Map<string, AnnotationRecord>();\n\n private readonly dNodes = newDirty();\n private readonly dMoved = new Set<string>(); // position-only node changes\n private _movedAll = false; // set by touchPositions() — every node moved (direct-column fast path)\n private readonly dEdges = newDirty();\n private readonly dGroups = newDirty();\n private readonly dAnnotations = newDirty();\n\n private readonly listeners = new Set<(e: LayerFlush) => void>();\n private version = 0;\n private scheduled = false;\n private flushMode: FlushMode = 'microtask';\n private cancel: (() => void) | undefined;\n\n // ── stream / query status (small, human-rate; observable) ──────────────────\n private _status: QueryStatus = 'idle';\n private readonly _intents: IntentLogEntry[] = [];\n private readonly statusListeners = new Set<(status: QueryStatus) => void>();\n\n // ── subscribe ─────────────────────────────────────────────────────────────\n /** Subscribe to coalesced `flush` deltas. Returns an unsubscribe. */\n on(event: 'flush', listener: (e: LayerFlush) => void): () => void {\n void event;\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /** {@link DataSource} contract — alias for `on('flush', …)`. */\n onFlush(listener: (e: LayerFlush) => void): () => void {\n return this.on('flush', listener);\n }\n\n /**\n * Choose **when** a flush fires ({@link FlushMode}). `'manual'` disarms any pending\n * auto-flush so only an explicit {@link flush} emits — used when the engine drives\n * every layer's data from one rAF loop.\n */\n setFlushMode(mode: FlushMode): void {\n this.flushMode = mode;\n if (mode === 'manual' && this.scheduled) {\n this.cancel?.();\n this.scheduled = false;\n }\n }\n\n // ── reads ─────────────────────────────────────────────────────────────────\n /** Read a node, **stitching** its cold record with its hot `x`/`y` (when set). */\n node(id: string): NodeRecord | undefined {\n const cold = this._nodes.get(id);\n if (!cold) return undefined;\n const slot = this._pos.slot(id);\n if (slot === undefined) return cold;\n const flags = this._pos.column('flags')[slot] ?? 0;\n if ((flags & NODE_FLAG.HAS_POSITION) === 0) return cold;\n return { ...cold, x: this._pos.column('x')[slot], y: this._pos.column('y')[slot] };\n }\n edge(id: string): EdgeRecord | undefined {\n return this._edges.get(id);\n }\n group(id: string): GroupRecord | undefined {\n return this._groups.get(id);\n }\n annotation(id: string): AnnotationRecord | undefined {\n return this._annotations.get(id);\n }\n nodes(): NodeRecord[] {\n return [...this._nodes.keys()].map((id) => this.node(id)!);\n }\n edges(): EdgeRecord[] {\n return [...this._edges.values()];\n }\n groups(): GroupRecord[] {\n return [...this._groups.values()];\n }\n annotations(): AnnotationRecord[] {\n return [...this._annotations.values()];\n }\n get counts(): { nodes: number; edges: number; groups: number; annotations: number } {\n return {\n nodes: this._nodes.size,\n edges: this._edges.size,\n groups: this._groups.size,\n annotations: this._annotations.size,\n };\n }\n\n // ── hot-lane fast path (layout / renderer) ─────────────────────────────────\n /**\n * Direct access to the typed-array position columns. Hold the ref + a slot once\n * and write in place (~10 ns/slot), then call {@link touchPositions} to emit one\n * coalesced moved flush. `positions.slot(id)` maps id → column index.\n */\n get positions(): ColumnStore<PosSchema> {\n return this._pos;\n }\n\n /**\n * Bulk-apply layout output from an **interleaved** `[x0,y0,x1,y1,…]` buffer —\n * the layout fast path. Skips ids that aren't present; marks each `moved`.\n */\n setPositionsBulk(ids: readonly string[], xy: ArrayLike<number>): void {\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i]!;\n if (!this._nodes.has(id)) continue;\n this.writePos(id, xy[i * 2], xy[i * 2 + 1], false);\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n }\n this.schedule();\n }\n\n /**\n * After writing position slots directly via {@link positions}, call this to bump\n * the version and emit **one** flush that marks every node `moved` (the per-tick\n * force-sim path — \"everything moved\", transform-only).\n */\n touchPositions(): void {\n this._pos.touch();\n this._movedAll = true;\n this.schedule();\n }\n\n /** Read a node's `flags` byte, or `undefined`. */\n nodeFlags(id: string): number | undefined {\n return this._pos.get(id, 'flags');\n }\n\n /** Toggle a {@link NODE_FLAG} bit (e.g. pinned/disabled) — marks the node `changed`. */\n setNodeFlag(id: string, flag: number, on: boolean): void {\n const cur = this._pos.get(id, 'flags');\n if (cur === undefined) return;\n const next = on ? cur | flag : cur & ~flag;\n if (next === cur) return;\n this._pos.set(id, 'flags', next);\n if (!this.dNodes.added.has(id)) this.dNodes.changed.add(id);\n this.schedule();\n }\n\n // ── stream / query status ──────────────────────────────────────────────────\n /** Current ingestion lifecycle status. */\n get status(): QueryStatus {\n return this._status;\n }\n /** Set the ingestion status; notifies {@link onStatus} listeners on change. */\n setStatus(status: QueryStatus): void {\n if (status === this._status) return;\n this._status = status;\n for (const l of [...this.statusListeners]) l(status);\n }\n /** Subscribe to status changes. Returns an unsubscribe. */\n onStatus(listener: (status: QueryStatus) => void): () => void {\n this.statusListeners.add(listener);\n return () => this.statusListeners.delete(listener);\n }\n /** The data-mutation audit trail (one entry per named action). */\n intents(): readonly IntentLogEntry[] {\n return this._intents;\n }\n /** Record a named data intent (audit / collab). */\n logIntent(action: string, ids?: readonly string[], ts: number = Date.now()): void {\n this._intents.push({ action, ids, ts });\n }\n\n // ── bulk ──────────────────────────────────────────────────────────────────\n /** Replace the whole graph — diffs each collection into the next flush. */\n setData(input: GraphInput): void {\n if (input.nodes) this.replaceNodes(input.nodes);\n if (input.edges) this.replaceKind(this._edges, this.dEdges, input.edges);\n if (input.groups) this.replaceKind(this._groups, this.dGroups, input.groups);\n if (input.annotations) this.replaceKind(this._annotations, this.dAnnotations, input.annotations);\n this.schedule();\n }\n\n /** Bulk-apply layout output (positions) → marks nodes `moved` (transform-only). */\n applyPositions(positions: Iterable<{ id: string; x: number; y: number }>): void {\n for (const { id, x, y } of positions) {\n if (!this._nodes.has(id)) continue;\n this.writePos(id, x, y, false);\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n }\n this.schedule();\n }\n\n // ── nodes ─────────────────────────────────────────────────────────────────\n addNode(n: NodeRecord): void {\n this.upsertNode(n);\n this.schedule();\n }\n updateNode(id: string, patch: Partial<NodeRecord>): void {\n if (!this._nodes.has(id)) return;\n const keys = Object.keys(patch);\n const positionOnly = keys.length > 0 && keys.every((k) => k === 'x' || k === 'y');\n if ('x' in patch || 'y' in patch) {\n this.writePos(id, patch.x as number | undefined, patch.y as number | undefined, false);\n }\n const { x: _x, y: _y, ...rest } = patch;\n if (Object.keys(rest).length > 0) {\n const cur = this._nodes.get(id)!;\n this._nodes.set(id, { ...cur, ...rest } as NodeRecord);\n }\n if (positionOnly) {\n if (!this.dNodes.added.has(id) && !this.dNodes.changed.has(id)) this.dMoved.add(id);\n } else {\n if (!this.dNodes.added.has(id)) this.dNodes.changed.add(id);\n this.dMoved.delete(id);\n }\n this.schedule();\n }\n removeNode(id: string): void {\n if (!this._nodes.has(id)) return;\n this._nodes.delete(id);\n this._pos.remove(id);\n this.dNodes.changed.delete(id);\n this.dMoved.delete(id);\n if (this.dNodes.added.delete(id)) {\n this.schedule();\n return; // added then removed before flush → net no-op\n }\n this.dNodes.removed.add(id);\n this.schedule();\n }\n\n // ── edges ─────────────────────────────────────────────────────────────────\n addEdge(e: EdgeRecord): void {\n this.upsert(this._edges, this.dEdges, e);\n this.schedule();\n }\n updateEdge(id: string, patch: Partial<EdgeRecord>): void {\n if (this.patchRecord(this._edges, this.dEdges, id, patch)) this.schedule();\n }\n removeEdge(id: string): void {\n this.removeFrom(this._edges, this.dEdges, id);\n this.schedule();\n }\n\n // ── groups ────────────────────────────────────────────────────────────────\n addGroup(g: GroupRecord): void {\n this.upsert(this._groups, this.dGroups, g);\n this.schedule();\n }\n updateGroup(id: string, patch: Partial<GroupRecord>): void {\n if (this.patchRecord(this._groups, this.dGroups, id, patch)) this.schedule();\n }\n removeGroup(id: string): void {\n this.removeFrom(this._groups, this.dGroups, id);\n this.schedule();\n }\n\n // ── annotations ───────────────────────────────────────────────────────────\n addAnnotation(a: AnnotationRecord): void {\n this.upsert(this._annotations, this.dAnnotations, a);\n this.schedule();\n }\n updateAnnotation(id: string, patch: Partial<AnnotationRecord>): void {\n if (this.patchRecord(this._annotations, this.dAnnotations, id, patch)) this.schedule();\n }\n removeAnnotation(id: string): void {\n this.removeFrom(this._annotations, this.dAnnotations, id);\n this.schedule();\n }\n\n // ── flush ─────────────────────────────────────────────────────────────────\n /** Emit the pending delta now (the engine calls this once per frame). */\n flush(): void {\n this.scheduled = false;\n const movedAll = this._movedAll;\n this._movedAll = false;\n const hasMoved = movedAll ? this._nodes.size > 0 : this.dMoved.size > 0;\n const empty =\n this.isClean(this.dNodes) &&\n !hasMoved &&\n this.isClean(this.dEdges) &&\n this.isClean(this.dGroups) &&\n this.isClean(this.dAnnotations);\n if (empty) return;\n\n // `movedAll` (force-sim tick) is signalled as a flag — never enumerated — so a\n // full-graph move is O(1) here; the renderer iterates the position column.\n const moved = movedAll ? [] : [...this.dMoved];\n\n const event: LayerFlush = {\n nodes: { ...drain(this.dNodes), moved, movedAll },\n edges: drain(this.dEdges),\n groups: drain(this.dGroups),\n annotations: drain(this.dAnnotations),\n version: ++this.version,\n };\n clearDirty(this.dNodes);\n this.dMoved.clear();\n clearDirty(this.dEdges);\n clearDirty(this.dGroups);\n clearDirty(this.dAnnotations);\n for (const l of [...this.listeners]) l(event);\n }\n\n // ── internals ─────────────────────────────────────────────────────────────\n private schedule(): void {\n if (this.scheduled || this.flushMode === 'manual') return;\n this.scheduled = true;\n this.cancel = scheduleFlush(this.flushMode, () => this.flush());\n }\n\n private isClean(d: KindDirty): boolean {\n return d.added.size === 0 && d.changed.size === 0 && d.removed.size === 0;\n }\n\n /** Insert/replace a node: cold record (minus x/y) + hot position columns. */\n private upsertNode(n: NodeRecord): void {\n const { x, y, ...rest } = n;\n const existed = this._nodes.has(n.id);\n this._nodes.set(n.id, rest as NodeRecord);\n this.writePos(n.id, x, y, true);\n if (existed) {\n this.dNodes.removed.delete(n.id);\n if (!this.dNodes.added.has(n.id)) this.dNodes.changed.add(n.id);\n } else {\n this.dNodes.added.add(n.id);\n this.dNodes.removed.delete(n.id);\n }\n }\n\n /**\n * Write a node's position into the hot column. `replace` (used on full upsert)\n * clears the `HAS_POSITION` bit when no `x`/`y` is supplied; otherwise a partial\n * update keeps the existing coordinate for an omitted axis.\n */\n private writePos(id: string, x: number | undefined, y: number | undefined, replace: boolean): void {\n const has = x !== undefined || y !== undefined;\n if (this._pos.has(id)) {\n if (has) {\n const cx = x ?? this._pos.get(id, 'x') ?? 0;\n const cy = y ?? this._pos.get(id, 'y') ?? 0;\n const flags = (this._pos.get(id, 'flags') ?? 0) | NODE_FLAG.HAS_POSITION;\n this._pos.update(id, { x: cx, y: cy, flags });\n } else if (replace) {\n const flags = (this._pos.get(id, 'flags') ?? 0) & ~NODE_FLAG.HAS_POSITION;\n this._pos.update(id, { x: 0, y: 0, flags });\n }\n } else {\n this._pos.add(id, { x: x ?? 0, y: y ?? 0, flags: has ? NODE_FLAG.HAS_POSITION : 0 });\n }\n }\n\n private replaceNodes(next: readonly NodeRecord[]): void {\n const nextIds = new Set(next.map((r) => r.id));\n for (const id of [...this._nodes.keys()]) {\n if (!nextIds.has(id)) this.removeNode(id);\n }\n for (const r of next) this.upsertNode(r);\n }\n\n private upsert<R extends { id: string }>(map: Map<string, R>, dirty: KindDirty, record: R): void {\n const existed = map.has(record.id);\n map.set(record.id, record);\n if (existed) {\n dirty.removed.delete(record.id);\n if (!dirty.added.has(record.id)) dirty.changed.add(record.id);\n } else {\n dirty.added.add(record.id);\n dirty.removed.delete(record.id);\n }\n }\n\n private patchRecord<R extends { id: string }>(\n map: Map<string, R>,\n dirty: KindDirty,\n id: string,\n patch: Partial<R>,\n ): boolean {\n const cur = map.get(id);\n if (!cur) return false;\n map.set(id, { ...cur, ...patch });\n if (!dirty.added.has(id)) dirty.changed.add(id);\n return true;\n }\n\n private removeFrom<R extends { id: string }>(map: Map<string, R>, dirty: KindDirty, id: string): boolean {\n if (!map.has(id)) return false;\n map.delete(id);\n dirty.changed.delete(id);\n if (dirty.added.delete(id)) return true; // added then removed before flush → net no-op\n dirty.removed.add(id);\n return true;\n }\n\n private replaceKind<R extends { id: string }>(\n map: Map<string, R>,\n dirty: KindDirty,\n next: readonly R[],\n ): void {\n const nextIds = new Set(next.map((r) => r.id));\n for (const id of [...map.keys()]) {\n if (!nextIds.has(id)) this.removeFrom(map, dirty, id);\n }\n for (const r of next) this.upsert(map, dirty, r);\n }\n}\n"]}